GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10259 lines
380 KiB

2 months ago
  1. /**
  2. * @license
  3. * Copyright 2021 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /**
  18. * <code>firebase</code> is a global namespace from which all Firebase
  19. * services are accessed.
  20. */
  21. declare namespace firebase {
  22. /**
  23. * @hidden
  24. */
  25. type NextFn<T> = (value: T) => void;
  26. /**
  27. * @hidden
  28. */
  29. type ErrorFn<E = Error> = (error: E) => void;
  30. /**
  31. * @hidden
  32. */
  33. type CompleteFn = () => void;
  34. /**
  35. * `FirebaseError` is a subclass of the standard JavaScript `Error` object. In
  36. * addition to a message string and stack trace, it contains a string code.
  37. */
  38. interface FirebaseError {
  39. /**
  40. * Error codes are strings using the following format: `"service/string-code"`.
  41. * Some examples include `"app/no-app"` and `"auth/user-not-found"`.
  42. *
  43. * While the message for a given error can change, the code will remain the same
  44. * between backward-compatible versions of the Firebase SDK.
  45. */
  46. code: string;
  47. /**
  48. * An explanatory message for the error that just occurred.
  49. *
  50. * This message is designed to be helpful to you, the developer. Because
  51. * it generally does not convey meaningful information to end users,
  52. * this message should not be displayed in your application.
  53. */
  54. message: string;
  55. /**
  56. * The name of the class of errors, which is `"FirebaseError"`.
  57. */
  58. name: 'FirebaseError';
  59. /**
  60. * A string value containing the execution backtrace when the error originally
  61. * occurred. This may not always be available.
  62. *
  63. * When it is available, this information can be sent to
  64. * {@link https://firebase.google.com/support/ Firebase Support} to help
  65. * explain the cause of an error.
  66. */
  67. stack?: string;
  68. }
  69. /**
  70. * @hidden
  71. */
  72. interface Observer<T, E = Error> {
  73. next: NextFn<T>;
  74. error: ErrorFn<E>;
  75. complete: CompleteFn;
  76. }
  77. /**
  78. * The JS SDK supports 5 log levels and also allows a user the ability to
  79. * silence the logs altogether.
  80. *
  81. * The order is as follows:
  82. * silent < debug < verbose < info < warn < error
  83. */
  84. type LogLevel = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent';
  85. /**
  86. * The current SDK version.
  87. */
  88. var SDK_VERSION: string;
  89. /**
  90. * Registers a library's name and version for platform logging purposes.
  91. * @param library Name of 1p or 3p library (e.g. firestore, angularfire)
  92. * @param version Current version of that library.
  93. * @param variant Bundle variant, e.g., node, rn, etc.
  94. */
  95. function registerVersion(
  96. library: string,
  97. version: string,
  98. variant?: string
  99. ): void;
  100. /**
  101. * Sets log level for all Firebase packages.
  102. *
  103. * All of the log types above the current log level are captured (i.e. if
  104. * you set the log level to `info`, errors are logged, but `debug` and
  105. * `verbose` logs are not).
  106. */
  107. function setLogLevel(logLevel: LogLevel): void;
  108. /**
  109. * Sets log handler for all Firebase packages.
  110. * @param logCallback An optional custom log handler that executes user code whenever
  111. * the Firebase SDK makes a logging call.
  112. */
  113. function onLog(
  114. logCallback: (callbackParams: {
  115. /**
  116. * Level of event logged.
  117. */
  118. level: LogLevel;
  119. /**
  120. * Any text from logged arguments joined into one string.
  121. */
  122. message: string;
  123. /**
  124. * The raw arguments passed to the log call.
  125. */
  126. args: any[];
  127. /**
  128. * A string indicating the name of the package that made the log call,
  129. * such as `@firebase/firestore`.
  130. */
  131. type: string;
  132. }) => void,
  133. options?: {
  134. /**
  135. * Threshhold log level. Only logs at or above this level trigger the `logCallback`
  136. * passed to `onLog`.
  137. */
  138. level: LogLevel;
  139. }
  140. ): void;
  141. /**
  142. * @hidden
  143. */
  144. type Unsubscribe = () => void;
  145. /**
  146. * A user account.
  147. */
  148. interface User extends firebase.UserInfo {
  149. /**
  150. * Deletes and signs out the user.
  151. *
  152. * <b>Important:</b> this is a security-sensitive operation that requires the
  153. * user to have recently signed in. If this requirement isn't met, ask the user
  154. * to authenticate again and then call
  155. * {@link firebase.User.reauthenticateWithCredential}.
  156. *
  157. * <h4>Error Codes</h4>
  158. * <dl>
  159. * <dt>auth/requires-recent-login</dt>
  160. * <dd>Thrown if the user's last sign-in time does not meet the security
  161. * threshold. Use {@link firebase.User.reauthenticateWithCredential} to
  162. * resolve. This does not apply if the user is anonymous.</dd>
  163. * </dl>
  164. */
  165. delete(): Promise<void>;
  166. emailVerified: boolean;
  167. getIdTokenResult(
  168. forceRefresh?: boolean
  169. ): Promise<firebase.auth.IdTokenResult>;
  170. /**
  171. * Returns a JSON Web Token (JWT) used to identify the user to a Firebase
  172. * service.
  173. *
  174. * Returns the current token if it has not expired. Otherwise, this will
  175. * refresh the token and return a new one.
  176. *
  177. * @param forceRefresh Force refresh regardless of token
  178. * expiration.
  179. */
  180. getIdToken(forceRefresh?: boolean): Promise<string>;
  181. isAnonymous: boolean;
  182. /**
  183. * Links the user account with the given credentials and returns any available
  184. * additional user information, such as user name.
  185. *
  186. * <h4>Error Codes</h4>
  187. * <dl>
  188. * <dt>auth/provider-already-linked</dt>
  189. * <dd>Thrown if the provider has already been linked to the user. This error is
  190. * thrown even if this is not the same provider's account that is currently
  191. * linked to the user.</dd>
  192. * <dt>auth/invalid-credential</dt>
  193. * <dd>Thrown if the provider's credential is not valid. This can happen if it
  194. * has already expired when calling link, or if it used invalid token(s).
  195. * See the Firebase documentation for your provider, and make sure you pass
  196. * in the correct parameters to the credential method.</dd>
  197. * <dt>auth/credential-already-in-use</dt>
  198. * <dd>Thrown if the account corresponding to the credential already exists
  199. * among your users, or is already linked to a Firebase User.
  200. * For example, this error could be thrown if you are upgrading an anonymous
  201. * user to a Google user by linking a Google credential to it and the Google
  202. * credential used is already associated with an existing Firebase Google
  203. * user.
  204. * The fields <code>error.email</code>, <code>error.phoneNumber</code>, and
  205. * <code>error.credential</code> ({@link firebase.auth.AuthCredential})
  206. * may be provided, depending on the type of credential. You can recover
  207. * from this error by signing in with <code>error.credential</code> directly
  208. * via {@link firebase.auth.Auth.signInWithCredential}.</dd>
  209. * <dt>auth/email-already-in-use</dt>
  210. * <dd>Thrown if the email corresponding to the credential already exists
  211. * among your users. When thrown while linking a credential to an existing
  212. * user, an <code>error.email</code> and <code>error.credential</code>
  213. * ({@link firebase.auth.AuthCredential}) fields are also provided.
  214. * You have to link the credential to the existing user with that email if
  215. * you wish to continue signing in with that credential. To do so, call
  216. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}, sign in to
  217. * <code>error.email</code> via one of the providers returned and then
  218. * {@link firebase.User.linkWithCredential} the original credential to that
  219. * newly signed in user.</dd>
  220. * <dt>auth/operation-not-allowed</dt>
  221. * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go
  222. * to the Firebase Console for your project, in the Auth section and the
  223. * <strong>Sign in Method</strong> tab and configure the provider.</dd>
  224. * <dt>auth/invalid-email</dt>
  225. * <dd>Thrown if the email used in a
  226. * {@link firebase.auth.EmailAuthProvider.credential} is invalid.</dd>
  227. * <dt>auth/wrong-password</dt>
  228. * <dd>Thrown if the password used in a
  229. * {@link firebase.auth.EmailAuthProvider.credential} is not correct or
  230. * when the user associated with the email does not have a password.</dd>
  231. * <dt>auth/invalid-verification-code</dt>
  232. * <dd>Thrown if the credential is a
  233. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  234. * code of the credential is not valid.</dd>
  235. * <dt>auth/invalid-verification-id</dt>
  236. * <dd>Thrown if the credential is a
  237. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  238. * ID of the credential is not valid.</dd>
  239. * </dl>
  240. *
  241. * @deprecated This method is deprecated. Use
  242. * {@link firebase.User.linkWithCredential} instead.
  243. *
  244. * @param credential The auth credential.
  245. */
  246. linkAndRetrieveDataWithCredential(
  247. credential: firebase.auth.AuthCredential
  248. ): Promise<firebase.auth.UserCredential>;
  249. /**
  250. * Links the user account with the given credentials.
  251. *
  252. * <h4>Error Codes</h4>
  253. * <dl>
  254. * <dt>auth/provider-already-linked</dt>
  255. * <dd>Thrown if the provider has already been linked to the user. This error is
  256. * thrown even if this is not the same provider's account that is currently
  257. * linked to the user.</dd>
  258. * <dt>auth/invalid-credential</dt>
  259. * <dd>Thrown if the provider's credential is not valid. This can happen if it
  260. * has already expired when calling link, or if it used invalid token(s).
  261. * See the Firebase documentation for your provider, and make sure you pass
  262. * in the correct parameters to the credential method.</dd>
  263. * <dt>auth/credential-already-in-use</dt>
  264. * <dd>Thrown if the account corresponding to the credential already exists
  265. * among your users, or is already linked to a Firebase User.
  266. * For example, this error could be thrown if you are upgrading an anonymous
  267. * user to a Google user by linking a Google credential to it and the Google
  268. * credential used is already associated with an existing Firebase Google
  269. * user.
  270. * The fields <code>error.email</code>, <code>error.phoneNumber</code>, and
  271. * <code>error.credential</code> ({@link firebase.auth.AuthCredential})
  272. * may be provided, depending on the type of credential. You can recover
  273. * from this error by signing in with <code>error.credential</code> directly
  274. * via {@link firebase.auth.Auth.signInWithCredential}.</dd>
  275. * <dt>auth/email-already-in-use</dt>
  276. * <dd>Thrown if the email corresponding to the credential already exists
  277. * among your users. When thrown while linking a credential to an existing
  278. * user, an <code>error.email</code> and <code>error.credential</code>
  279. * ({@link firebase.auth.AuthCredential}) fields are also provided.
  280. * You have to link the credential to the existing user with that email if
  281. * you wish to continue signing in with that credential. To do so, call
  282. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}, sign in to
  283. * <code>error.email</code> via one of the providers returned and then
  284. * {@link firebase.User.linkWithCredential} the original credential to that
  285. * newly signed in user.</dd>
  286. * <dt>auth/operation-not-allowed</dt>
  287. * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go
  288. * to the Firebase Console for your project, in the Auth section and the
  289. * <strong>Sign in Method</strong> tab and configure the provider.</dd>
  290. * <dt>auth/invalid-email</dt>
  291. * <dd>Thrown if the email used in a
  292. * {@link firebase.auth.EmailAuthProvider.credential} is invalid.</dd>
  293. * <dt>auth/wrong-password</dt>
  294. * <dd>Thrown if the password used in a
  295. * {@link firebase.auth.EmailAuthProvider.credential} is not correct or
  296. * when the user associated with the email does not have a password.</dd>
  297. * <dt>auth/invalid-verification-code</dt>
  298. * <dd>Thrown if the credential is a
  299. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  300. * code of the credential is not valid.</dd>
  301. * <dt>auth/invalid-verification-id</dt>
  302. * <dd>Thrown if the credential is a
  303. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  304. * ID of the credential is not valid.</dd>
  305. * </dl>
  306. *
  307. * @param credential The auth credential.
  308. */
  309. linkWithCredential(
  310. credential: firebase.auth.AuthCredential
  311. ): Promise<firebase.auth.UserCredential>;
  312. /**
  313. * Links the user account with the given phone number.
  314. *
  315. * <h4>Error Codes</h4>
  316. * <dl>
  317. * <dt>auth/provider-already-linked</dt>
  318. * <dd>Thrown if the provider has already been linked to the user. This error is
  319. * thrown even if this is not the same provider's account that is currently
  320. * linked to the user.</dd>
  321. * <dt>auth/captcha-check-failed</dt>
  322. * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if
  323. * this method was called from a non-whitelisted domain.</dd>
  324. * <dt>auth/invalid-phone-number</dt>
  325. * <dd>Thrown if the phone number has an invalid format.</dd>
  326. * <dt>auth/missing-phone-number</dt>
  327. * <dd>Thrown if the phone number is missing.</dd>
  328. * <dt>auth/quota-exceeded</dt>
  329. * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd>
  330. * <dt>auth/user-disabled</dt>
  331. * <dd>Thrown if the user corresponding to the given phone number has been
  332. * disabled.</dd>
  333. * <dt>auth/credential-already-in-use</dt>
  334. * <dd>Thrown if the account corresponding to the phone number already exists
  335. * among your users, or is already linked to a Firebase User.
  336. * The fields <code>error.phoneNumber</code> and
  337. * <code>error.credential</code> ({@link firebase.auth.AuthCredential})
  338. * are provided in this case. You can recover from this error by signing in
  339. * with that credential directly via
  340. * {@link firebase.auth.Auth.signInWithCredential}.</dd>
  341. * <dt>auth/operation-not-allowed</dt>
  342. * <dd>Thrown if you have not enabled the phone authentication provider in the
  343. * Firebase Console. Go to the Firebase Console for your project, in the
  344. * Auth section and the <strong>Sign in Method</strong> tab and configure
  345. * the provider.</dd>
  346. * </dl>
  347. *
  348. * @param phoneNumber The user's phone number in E.164 format (e.g.
  349. * +16505550101).
  350. * @param applicationVerifier
  351. */
  352. linkWithPhoneNumber(
  353. phoneNumber: string,
  354. applicationVerifier: firebase.auth.ApplicationVerifier
  355. ): Promise<firebase.auth.ConfirmationResult>;
  356. /**
  357. * Links the authenticated provider to the user account using a pop-up based
  358. * OAuth flow.
  359. *
  360. * If the linking is successful, the returned result will contain the user
  361. * and the provider's credential.
  362. *
  363. * <h4>Error Codes</h4>
  364. * <dl>
  365. * <dt>auth/auth-domain-config-required</dt>
  366. * <dd>Thrown if authDomain configuration is not provided when calling
  367. * firebase.initializeApp(). Check Firebase Console for instructions on
  368. * determining and passing that field.</dd>
  369. * <dt>auth/cancelled-popup-request</dt>
  370. * <dd>Thrown if successive popup operations are triggered. Only one popup
  371. * request is allowed at one time on a user or an auth instance. All the
  372. * popups would fail with this error except for the last one.</dd>
  373. * <dt>auth/credential-already-in-use</dt>
  374. * <dd>Thrown if the account corresponding to the credential already exists
  375. * among your users, or is already linked to a Firebase User.
  376. * For example, this error could be thrown if you are upgrading an anonymous
  377. * user to a Google user by linking a Google credential to it and the Google
  378. * credential used is already associated with an existing Firebase Google
  379. * user.
  380. * An <code>error.email</code> and <code>error.credential</code>
  381. * ({@link firebase.auth.AuthCredential}) fields are also provided. You can
  382. * recover from this error by signing in with that credential directly via
  383. * {@link firebase.auth.Auth.signInWithCredential}.</dd>
  384. * <dt>auth/email-already-in-use</dt>
  385. * <dd>Thrown if the email corresponding to the credential already exists
  386. * among your users. When thrown while linking a credential to an existing
  387. * user, an <code>error.email</code> and <code>error.credential</code>
  388. * ({@link firebase.auth.AuthCredential}) fields are also provided.
  389. * You have to link the credential to the existing user with that email if
  390. * you wish to continue signing in with that credential. To do so, call
  391. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}, sign in to
  392. * <code>error.email</code> via one of the providers returned and then
  393. * {@link firebase.User.linkWithCredential} the original credential to that
  394. * newly signed in user.</dd>
  395. * <dt>auth/operation-not-allowed</dt>
  396. * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go
  397. * to the Firebase Console for your project, in the Auth section and the
  398. * <strong>Sign in Method</strong> tab and configure the provider.</dd>
  399. * <dt>auth/popup-blocked</dt>
  400. * <dt>auth/operation-not-supported-in-this-environment</dt>
  401. * <dd>Thrown if this operation is not supported in the environment your
  402. * application is running on. "location.protocol" must be http or https.
  403. * </dd>
  404. * <dd>Thrown if the popup was blocked by the browser, typically when this
  405. * operation is triggered outside of a click handler.</dd>
  406. * <dt>auth/popup-closed-by-user</dt>
  407. * <dd>Thrown if the popup window is closed by the user without completing the
  408. * sign in to the provider.</dd>
  409. * <dt>auth/provider-already-linked</dt>
  410. * <dd>Thrown if the provider has already been linked to the user. This error is
  411. * thrown even if this is not the same provider's account that is currently
  412. * linked to the user.</dd>
  413. * <dt>auth/unauthorized-domain</dt>
  414. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  415. * Firebase project. Edit the list of authorized domains from the Firebase
  416. * console.</dd>
  417. * </dl>
  418. *
  419. * @webonly
  420. *
  421. * @example
  422. * ```javascript
  423. * // Creates the provider object.
  424. * var provider = new firebase.auth.FacebookAuthProvider();
  425. * // You can add additional scopes to the provider:
  426. * provider.addScope('email');
  427. * provider.addScope('user_friends');
  428. * // Link with popup:
  429. * user.linkWithPopup(provider).then(function(result) {
  430. * // The firebase.User instance:
  431. * var user = result.user;
  432. * // The Facebook firebase.auth.AuthCredential containing the Facebook
  433. * // access token:
  434. * var credential = result.credential;
  435. * }, function(error) {
  436. * // An error happened.
  437. * });
  438. * ```
  439. *
  440. * @param provider The provider to authenticate.
  441. * The provider has to be an OAuth provider. Non-OAuth providers like {@link
  442. * firebase.auth.EmailAuthProvider} will throw an error.
  443. */
  444. linkWithPopup(
  445. provider: firebase.auth.AuthProvider
  446. ): Promise<firebase.auth.UserCredential>;
  447. /**
  448. * Links the authenticated provider to the user account using a full-page
  449. * redirect flow.
  450. *
  451. * <h4>Error Codes</h4>
  452. * <dl>
  453. * <dt>auth/auth-domain-config-required</dt>
  454. * <dd>Thrown if authDomain configuration is not provided when calling
  455. * firebase.initializeApp(). Check Firebase Console for instructions on
  456. * determining and passing that field.</dd>
  457. * <dt>auth/operation-not-supported-in-this-environment</dt>
  458. * <dd>Thrown if this operation is not supported in the environment your
  459. * application is running on. "location.protocol" must be http or https.
  460. * </dd>
  461. * <dt>auth/provider-already-linked</dt>
  462. * <dd>Thrown if the provider has already been linked to the user. This error is
  463. * thrown even if this is not the same provider's account that is currently
  464. * linked to the user.</dd>
  465. * <dt>auth/unauthorized-domain</dt>
  466. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  467. * Firebase project. Edit the list of authorized domains from the Firebase
  468. * console.</dd>
  469. * </dl>
  470. *
  471. * @param provider The provider to authenticate.
  472. * The provider has to be an OAuth provider. Non-OAuth providers like {@link
  473. * firebase.auth.EmailAuthProvider} will throw an error.
  474. */
  475. linkWithRedirect(provider: firebase.auth.AuthProvider): Promise<void>;
  476. metadata: firebase.auth.UserMetadata;
  477. /**
  478. * The {@link firebase.User.MultiFactorUser} object corresponding to the current user.
  479. * This is used to access all multi-factor properties and operations related to the
  480. * current user.
  481. */
  482. multiFactor: firebase.User.MultiFactorUser;
  483. /**
  484. * The phone number normalized based on the E.164 standard (e.g. +16505550101)
  485. * for the current user. This is null if the user has no phone credential linked
  486. * to the account.
  487. */
  488. phoneNumber: string | null;
  489. providerData: (firebase.UserInfo | null)[];
  490. /**
  491. * Re-authenticates a user using a fresh credential, and returns any available
  492. * additional user information, such as user name. Use before operations
  493. * such as {@link firebase.User.updatePassword} that require tokens from recent
  494. * sign-in attempts.
  495. *
  496. * <h4>Error Codes</h4>
  497. * <dl>
  498. * <dt>auth/user-mismatch</dt>
  499. * <dd>Thrown if the credential given does not correspond to the user.</dd>
  500. * <dt>auth/user-not-found</dt>
  501. * <dd>Thrown if the credential given does not correspond to any existing user.
  502. * </dd>
  503. * <dt>auth/invalid-credential</dt>
  504. * <dd>Thrown if the provider's credential is not valid. This can happen if it
  505. * has already expired when calling link, or if it used invalid token(s).
  506. * See the Firebase documentation for your provider, and make sure you pass
  507. * in the correct parameters to the credential method.</dd>
  508. * <dt>auth/invalid-email</dt>
  509. * <dd>Thrown if the email used in a
  510. * {@link firebase.auth.EmailAuthProvider.credential} is invalid.</dd>
  511. * <dt>auth/wrong-password</dt>
  512. * <dd>Thrown if the password used in a
  513. * {@link firebase.auth.EmailAuthProvider.credential} is not correct or when
  514. * the user associated with the email does not have a password.</dd>
  515. * <dt>auth/invalid-verification-code</dt>
  516. * <dd>Thrown if the credential is a
  517. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  518. * code of the credential is not valid.</dd>
  519. * <dt>auth/invalid-verification-id</dt>
  520. * <dd>Thrown if the credential is a
  521. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  522. * ID of the credential is not valid.</dd>
  523. * </dl>
  524. *
  525. * @deprecated
  526. * This method is deprecated. Use
  527. * {@link firebase.User.reauthenticateWithCredential} instead.
  528. *
  529. * @param credential
  530. */
  531. reauthenticateAndRetrieveDataWithCredential(
  532. credential: firebase.auth.AuthCredential
  533. ): Promise<firebase.auth.UserCredential>;
  534. /**
  535. * Re-authenticates a user using a fresh credential. Use before operations
  536. * such as {@link firebase.User.updatePassword} that require tokens from recent
  537. * sign-in attempts.
  538. *
  539. * <h4>Error Codes</h4>
  540. * <dl>
  541. * <dt>auth/user-mismatch</dt>
  542. * <dd>Thrown if the credential given does not correspond to the user.</dd>
  543. * <dt>auth/user-not-found</dt>
  544. * <dd>Thrown if the credential given does not correspond to any existing user.
  545. * </dd>
  546. * <dt>auth/invalid-credential</dt>
  547. * <dd>Thrown if the provider's credential is not valid. This can happen if it
  548. * has already expired when calling link, or if it used invalid token(s).
  549. * See the Firebase documentation for your provider, and make sure you pass
  550. * in the correct parameters to the credential method.</dd>
  551. * <dt>auth/invalid-email</dt>
  552. * <dd>Thrown if the email used in a
  553. * {@link firebase.auth.EmailAuthProvider.credential} is invalid.</dd>
  554. * <dt>auth/wrong-password</dt>
  555. * <dd>Thrown if the password used in a
  556. * {@link firebase.auth.EmailAuthProvider.credential} is not correct or when
  557. * the user associated with the email does not have a password.</dd>
  558. * <dt>auth/invalid-verification-code</dt>
  559. * <dd>Thrown if the credential is a
  560. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  561. * code of the credential is not valid.</dd>
  562. * <dt>auth/invalid-verification-id</dt>
  563. * <dd>Thrown if the credential is a
  564. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  565. * ID of the credential is not valid.</dd>
  566. * </dl>
  567. *
  568. * @param credential
  569. */
  570. reauthenticateWithCredential(
  571. credential: firebase.auth.AuthCredential
  572. ): Promise<firebase.auth.UserCredential>;
  573. /**
  574. * Re-authenticates a user using a fresh credential. Use before operations
  575. * such as {@link firebase.User.updatePassword} that require tokens from recent
  576. * sign-in attempts.
  577. *
  578. * <h4>Error Codes</h4>
  579. * <dl>
  580. * <dt>auth/user-mismatch</dt>
  581. * <dd>Thrown if the credential given does not correspond to the user.</dd>
  582. * <dt>auth/user-not-found</dt>
  583. * <dd>Thrown if the credential given does not correspond to any existing user.
  584. * </dd>
  585. * <dt>auth/captcha-check-failed</dt>
  586. * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if
  587. * this method was called from a non-whitelisted domain.</dd>
  588. * <dt>auth/invalid-phone-number</dt>
  589. * <dd>Thrown if the phone number has an invalid format.</dd>
  590. * <dt>auth/missing-phone-number</dt>
  591. * <dd>Thrown if the phone number is missing.</dd>
  592. * <dt>auth/quota-exceeded</dt>
  593. * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd>
  594. * </dl>
  595. *
  596. * @param phoneNumber The user's phone number in E.164 format (e.g.
  597. * +16505550101).
  598. * @param applicationVerifier
  599. */
  600. reauthenticateWithPhoneNumber(
  601. phoneNumber: string,
  602. applicationVerifier: firebase.auth.ApplicationVerifier
  603. ): Promise<firebase.auth.ConfirmationResult>;
  604. /**
  605. * Reauthenticates the current user with the specified provider using a pop-up
  606. * based OAuth flow.
  607. *
  608. * If the reauthentication is successful, the returned result will contain the
  609. * user and the provider's credential.
  610. *
  611. * <h4>Error Codes</h4>
  612. * <dl>
  613. * <dt>auth/auth-domain-config-required</dt>
  614. * <dd>Thrown if authDomain configuration is not provided when calling
  615. * firebase.initializeApp(). Check Firebase Console for instructions on
  616. * determining and passing that field.</dd>
  617. * <dt>auth/cancelled-popup-request</dt>
  618. * <dd>Thrown if successive popup operations are triggered. Only one popup
  619. * request is allowed at one time on a user or an auth instance. All the
  620. * popups would fail with this error except for the last one.</dd>
  621. * <dt>auth/user-mismatch</dt>
  622. * <dd>Thrown if the credential given does not correspond to the user.</dd>
  623. * <dt>auth/operation-not-allowed</dt>
  624. * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go
  625. * to the Firebase Console for your project, in the Auth section and the
  626. * <strong>Sign in Method</strong> tab and configure the provider.</dd>
  627. * <dt>auth/popup-blocked</dt>
  628. * <dd>Thrown if the popup was blocked by the browser, typically when this
  629. * operation is triggered outside of a click handler.</dd>
  630. * <dt>auth/operation-not-supported-in-this-environment</dt>
  631. * <dd>Thrown if this operation is not supported in the environment your
  632. * application is running on. "location.protocol" must be http or https.
  633. * </dd>
  634. * <dt>auth/popup-closed-by-user</dt>
  635. * <dd>Thrown if the popup window is closed by the user without completing the
  636. * sign in to the provider.</dd>
  637. * <dt>auth/unauthorized-domain</dt>
  638. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  639. * Firebase project. Edit the list of authorized domains from the Firebase
  640. * console.</dd>
  641. * </dl>
  642. *
  643. * @webonly
  644. *
  645. * @example
  646. * ```javascript
  647. * // Creates the provider object.
  648. * var provider = new firebase.auth.FacebookAuthProvider();
  649. * // You can add additional scopes to the provider:
  650. * provider.addScope('email');
  651. * provider.addScope('user_friends');
  652. * // Reauthenticate with popup:
  653. * user.reauthenticateWithPopup(provider).then(function(result) {
  654. * // The firebase.User instance:
  655. * var user = result.user;
  656. * // The Facebook firebase.auth.AuthCredential containing the Facebook
  657. * // access token:
  658. * var credential = result.credential;
  659. * }, function(error) {
  660. * // An error happened.
  661. * });
  662. * ```
  663. *
  664. * @param provider The provider to authenticate.
  665. * The provider has to be an OAuth provider. Non-OAuth providers like {@link
  666. * firebase.auth.EmailAuthProvider} will throw an error.
  667. */
  668. reauthenticateWithPopup(
  669. provider: firebase.auth.AuthProvider
  670. ): Promise<firebase.auth.UserCredential>;
  671. /**
  672. * Reauthenticates the current user with the specified OAuth provider using a
  673. * full-page redirect flow.
  674. *
  675. * <h4>Error Codes</h4>
  676. * <dl>
  677. * <dt>auth/auth-domain-config-required</dt>
  678. * <dd>Thrown if authDomain configuration is not provided when calling
  679. * firebase.initializeApp(). Check Firebase Console for instructions on
  680. * determining and passing that field.</dd>
  681. * <dt>auth/operation-not-supported-in-this-environment</dt>
  682. * <dd>Thrown if this operation is not supported in the environment your
  683. * application is running on. "location.protocol" must be http or https.
  684. * </dd>
  685. * <dt>auth/user-mismatch</dt>
  686. * <dd>Thrown if the credential given does not correspond to the user.</dd>
  687. * <dt>auth/unauthorized-domain</dt>
  688. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  689. * Firebase project. Edit the list of authorized domains from the Firebase
  690. * console.</dd>
  691. * </dl>
  692. *
  693. * @webonly
  694. *
  695. * @param provider The provider to authenticate.
  696. * The provider has to be an OAuth provider. Non-OAuth providers like {@link
  697. * firebase.auth.EmailAuthProvider} will throw an error.
  698. */
  699. reauthenticateWithRedirect(
  700. provider: firebase.auth.AuthProvider
  701. ): Promise<void>;
  702. refreshToken: string;
  703. /**
  704. * Refreshes the current user, if signed in.
  705. *
  706. */
  707. reload(): Promise<void>;
  708. /**
  709. * Sends a verification email to a user.
  710. *
  711. * The verification process is completed by calling
  712. * {@link firebase.auth.Auth.applyActionCode}
  713. *
  714. * <h4>Error Codes</h4>
  715. * <dl>
  716. * <dt>auth/missing-android-pkg-name</dt>
  717. * <dd>An Android package name must be provided if the Android app is required
  718. * to be installed.</dd>
  719. * <dt>auth/missing-continue-uri</dt>
  720. * <dd>A continue URL must be provided in the request.</dd>
  721. * <dt>auth/missing-ios-bundle-id</dt>
  722. * <dd>An iOS bundle ID must be provided if an App Store ID is provided.</dd>
  723. * <dt>auth/invalid-continue-uri</dt>
  724. * <dd>The continue URL provided in the request is invalid.</dd>
  725. * <dt>auth/unauthorized-continue-uri</dt>
  726. * <dd>The domain of the continue URL is not whitelisted. Whitelist
  727. * the domain in the Firebase console.</dd>
  728. * </dl>
  729. *
  730. * @example
  731. * ```javascript
  732. * var actionCodeSettings = {
  733. * url: 'https://www.example.com/cart?email=user@example.com&cartId=123',
  734. * iOS: {
  735. * bundleId: 'com.example.ios'
  736. * },
  737. * android: {
  738. * packageName: 'com.example.android',
  739. * installApp: true,
  740. * minimumVersion: '12'
  741. * },
  742. * handleCodeInApp: true
  743. * };
  744. * firebase.auth().currentUser.sendEmailVerification(actionCodeSettings)
  745. * .then(function() {
  746. * // Verification email sent.
  747. * })
  748. * .catch(function(error) {
  749. * // Error occurred. Inspect error.code.
  750. * });
  751. * ```
  752. *
  753. * @param actionCodeSettings The action
  754. * code settings. If specified, the state/continue URL will be set as the
  755. * "continueUrl" parameter in the email verification link. The default email
  756. * verification landing page will use this to display a link to go back to
  757. * the app if it is installed.
  758. * If the actionCodeSettings is not specified, no URL is appended to the
  759. * action URL.
  760. * The state URL provided must belong to a domain that is whitelisted by the
  761. * developer in the console. Otherwise an error will be thrown.
  762. * Mobile app redirects will only be applicable if the developer configures
  763. * and accepts the Firebase Dynamic Links terms of condition.
  764. * The Android package name and iOS bundle ID will be respected only if they
  765. * are configured in the same Firebase Auth project used.
  766. */
  767. sendEmailVerification(
  768. actionCodeSettings?: firebase.auth.ActionCodeSettings | null
  769. ): Promise<void>;
  770. /**
  771. * The current user's tenant ID. This is a read-only property, which indicates
  772. * the tenant ID used to sign in the current user. This is null if the user is
  773. * signed in from the parent project.
  774. *
  775. * @example
  776. * ```javascript
  777. * // Set the tenant ID on Auth instance.
  778. * firebase.auth().tenantId = TENANT_PROJECT_ID;
  779. *
  780. * // All future sign-in request now include tenant ID.
  781. * firebase.auth().signInWithEmailAndPassword(email, password)
  782. * .then(function(result) {
  783. * // result.user.tenantId should be ‘TENANT_PROJECT_ID’.
  784. * }).catch(function(error) {
  785. * // Handle error.
  786. * });
  787. * ```
  788. */
  789. tenantId: string | null;
  790. /**
  791. * Returns a JSON-serializable representation of this object.
  792. *
  793. * @return A JSON-serializable representation of this object.
  794. */
  795. toJSON(): Object;
  796. /**
  797. * Unlinks a provider from a user account.
  798. *
  799. * <h4>Error Codes</h4>
  800. * <dl>
  801. * <dt>auth/no-such-provider</dt>
  802. * <dd>Thrown if the user does not have this provider linked or when the
  803. * provider ID given does not exist.</dd>
  804. * </dt>
  805. *
  806. * @param providerId
  807. */
  808. unlink(providerId: string): Promise<firebase.User>;
  809. /**
  810. * Updates the user's email address.
  811. *
  812. * An email will be sent to the original email address (if it was set) that
  813. * allows to revoke the email address change, in order to protect them from
  814. * account hijacking.
  815. *
  816. * <b>Important:</b> this is a security sensitive operation that requires the
  817. * user to have recently signed in. If this requirement isn't met, ask the user
  818. * to authenticate again and then call
  819. * {@link firebase.User.reauthenticateWithCredential}.
  820. *
  821. * <h4>Error Codes</h4>
  822. * <dl>
  823. * <dt>auth/invalid-email</dt>
  824. * <dd>Thrown if the email used is invalid.</dd>
  825. * <dt>auth/email-already-in-use</dt>
  826. * <dd>Thrown if the email is already used by another user.</dd>
  827. * <dt>auth/requires-recent-login</dt>
  828. * <dd>Thrown if the user's last sign-in time does not meet the security
  829. * threshold. Use {@link firebase.User.reauthenticateWithCredential} to
  830. * resolve. This does not apply if the user is anonymous.</dd>
  831. * </dl>
  832. *
  833. * @param newEmail The new email address.
  834. */
  835. updateEmail(newEmail: string): Promise<void>;
  836. /**
  837. * Updates the user's password.
  838. *
  839. * <b>Important:</b> this is a security sensitive operation that requires the
  840. * user to have recently signed in. If this requirement isn't met, ask the user
  841. * to authenticate again and then call
  842. * {@link firebase.User.reauthenticateWithCredential}.
  843. *
  844. * <h4>Error Codes</h4>
  845. * <dl>
  846. * <dt>auth/weak-password</dt>
  847. * <dd>Thrown if the password is not strong enough.</dd>
  848. * <dt>auth/requires-recent-login</dt>
  849. * <dd>Thrown if the user's last sign-in time does not meet the security
  850. * threshold. Use {@link firebase.User.reauthenticateWithCredential} to
  851. * resolve. This does not apply if the user is anonymous.</dd>
  852. * </dl>
  853. *
  854. * @param newPassword
  855. */
  856. updatePassword(newPassword: string): Promise<void>;
  857. /**
  858. * Updates the user's phone number.
  859. *
  860. * <h4>Error Codes</h4>
  861. * <dl>
  862. * <dt>auth/invalid-verification-code</dt>
  863. * <dd>Thrown if the verification code of the credential is not valid.</dd>
  864. * <dt>auth/invalid-verification-id</dt>
  865. * <dd>Thrown if the verification ID of the credential is not valid.</dd>
  866. * </dl>
  867. *
  868. * @param phoneCredential
  869. */
  870. updatePhoneNumber(
  871. phoneCredential: firebase.auth.AuthCredential
  872. ): Promise<void>;
  873. /**
  874. * Updates a user's profile data.
  875. *
  876. * @example
  877. * ```javascript
  878. * // Updates the user attributes:
  879. * user.updateProfile({
  880. * displayName: "Jane Q. User",
  881. * photoURL: "https://example.com/jane-q-user/profile.jpg"
  882. * }).then(function() {
  883. * // Profile updated successfully!
  884. * // "Jane Q. User"
  885. * var displayName = user.displayName;
  886. * // "https://example.com/jane-q-user/profile.jpg"
  887. * var photoURL = user.photoURL;
  888. * }, function(error) {
  889. * // An error happened.
  890. * });
  891. *
  892. * // Passing a null value will delete the current attribute's value, but not
  893. * // passing a property won't change the current attribute's value:
  894. * // Let's say we're using the same user than before, after the update.
  895. * user.updateProfile({photoURL: null}).then(function() {
  896. * // Profile updated successfully!
  897. * // "Jane Q. User", hasn't changed.
  898. * var displayName = user.displayName;
  899. * // Now, this is null.
  900. * var photoURL = user.photoURL;
  901. * }, function(error) {
  902. * // An error happened.
  903. * });
  904. * ```
  905. *
  906. * @param profile The profile's
  907. * displayName and photoURL to update.
  908. */
  909. updateProfile(profile: {
  910. displayName?: string | null;
  911. photoURL?: string | null;
  912. }): Promise<void>;
  913. /**
  914. * Sends a verification email to a new email address. The user's email will be
  915. * updated to the new one after being verified.
  916. *
  917. * If you have a custom email action handler, you can complete the verification
  918. * process by calling {@link firebase.auth.Auth.applyActionCode}.
  919. *
  920. * <h4>Error Codes</h4>
  921. * <dl>
  922. * <dt>auth/missing-android-pkg-name</dt>
  923. * <dd>An Android package name must be provided if the Android app is required
  924. * to be installed.</dd>
  925. * <dt>auth/missing-continue-uri</dt>
  926. * <dd>A continue URL must be provided in the request.</dd>
  927. * <dt>auth/missing-ios-bundle-id</dt>
  928. * <dd>An iOS bundle ID must be provided if an App Store ID is provided.</dd>
  929. * <dt>auth/invalid-continue-uri</dt>
  930. * <dd>The continue URL provided in the request is invalid.</dd>
  931. * <dt>auth/unauthorized-continue-uri</dt>
  932. * <dd>The domain of the continue URL is not whitelisted. Whitelist
  933. * the domain in the Firebase console.</dd>
  934. * </dl>
  935. *
  936. * @example
  937. * ```javascript
  938. * var actionCodeSettings = {
  939. * url: 'https://www.example.com/cart?email=user@example.com&cartId=123',
  940. * iOS: {
  941. * bundleId: 'com.example.ios'
  942. * },
  943. * android: {
  944. * packageName: 'com.example.android',
  945. * installApp: true,
  946. * minimumVersion: '12'
  947. * },
  948. * handleCodeInApp: true
  949. * };
  950. * firebase.auth().currentUser.verifyBeforeUpdateEmail(
  951. * 'user@example.com', actionCodeSettings)
  952. * .then(function() {
  953. * // Verification email sent.
  954. * })
  955. * .catch(function(error) {
  956. * // Error occurred. Inspect error.code.
  957. * });
  958. * ```
  959. *
  960. * @param newEmail The email address to be verified and updated to.
  961. * @param actionCodeSettings The action
  962. * code settings. If specified, the state/continue URL will be set as the
  963. * "continueUrl" parameter in the email verification link. The default email
  964. * verification landing page will use this to display a link to go back to
  965. * the app if it is installed.
  966. * If the actionCodeSettings is not specified, no URL is appended to the
  967. * action URL.
  968. * The state URL provided must belong to a domain that is whitelisted by the
  969. * developer in the console. Otherwise an error will be thrown.
  970. * Mobile app redirects will only be applicable if the developer configures
  971. * and accepts the Firebase Dynamic Links terms of condition.
  972. * The Android package name and iOS bundle ID will be respected only if they
  973. * are configured in the same Firebase Auth project used.
  974. */
  975. verifyBeforeUpdateEmail(
  976. newEmail: string,
  977. actionCodeSettings?: firebase.auth.ActionCodeSettings | null
  978. ): Promise<void>;
  979. }
  980. /**
  981. * User profile information, visible only to the Firebase project's
  982. * apps.
  983. *
  984. */
  985. interface UserInfo {
  986. displayName: string | null;
  987. email: string | null;
  988. phoneNumber: string | null;
  989. photoURL: string | null;
  990. providerId: string;
  991. /**
  992. * The user's unique ID.
  993. */
  994. uid: string;
  995. }
  996. type FirebaseSignInProvider =
  997. | 'custom'
  998. | 'email'
  999. | 'password'
  1000. | 'phone'
  1001. | 'anonymous'
  1002. | 'google.com'
  1003. | 'facebook.com'
  1004. | 'github.com'
  1005. | 'twitter.com'
  1006. | 'microsoft.com'
  1007. | 'apple.com';
  1008. interface FirebaseIdToken {
  1009. /** Always set to https://securetoken.google.com/PROJECT_ID */
  1010. iss: string;
  1011. /** Always set to PROJECT_ID */
  1012. aud: string;
  1013. /** The user's unique ID */
  1014. sub: string;
  1015. /** The token issue time, in seconds since epoch */
  1016. iat: number;
  1017. /** The token expiry time, normally 'iat' + 3600 */
  1018. exp: number;
  1019. /** The user's unique ID. Must be equal to 'sub' */
  1020. user_id: string;
  1021. /** The time the user authenticated, normally 'iat' */
  1022. auth_time: number;
  1023. /** The sign in provider, only set when the provider is 'anonymous' */
  1024. provider_id?: 'anonymous';
  1025. /** The user's primary email */
  1026. email?: string;
  1027. /** The user's email verification status */
  1028. email_verified?: boolean;
  1029. /** The user's primary phone number */
  1030. phone_number?: string;
  1031. /** The user's display name */
  1032. name?: string;
  1033. /** The user's profile photo URL */
  1034. picture?: string;
  1035. /** Information on all identities linked to this user */
  1036. firebase: {
  1037. /** The primary sign-in provider */
  1038. sign_in_provider: FirebaseSignInProvider;
  1039. /** A map of providers to the user's list of unique identifiers from each provider */
  1040. identities?: { [provider in FirebaseSignInProvider]?: string[] };
  1041. };
  1042. /** Custom claims set by the developer */
  1043. [claim: string]: unknown;
  1044. // NO LONGER SUPPORTED. Use "sub" instead. (Not a jsdoc comment to avoid generating docs.)
  1045. uid?: never;
  1046. }
  1047. export type EmulatorMockTokenOptions = (
  1048. | { user_id: string }
  1049. | { sub: string }
  1050. ) &
  1051. Partial<FirebaseIdToken>;
  1052. /**
  1053. * Retrieves a Firebase {@link firebase.app.App app} instance.
  1054. *
  1055. * When called with no arguments, the default app is returned. When an app name
  1056. * is provided, the app corresponding to that name is returned.
  1057. *
  1058. * An exception is thrown if the app being retrieved has not yet been
  1059. * initialized.
  1060. *
  1061. * @example
  1062. * ```javascript
  1063. * // Return the default app
  1064. * var app = firebase.app();
  1065. * ```
  1066. *
  1067. * @example
  1068. * ```javascript
  1069. * // Return a named app
  1070. * var otherApp = firebase.app("otherApp");
  1071. * ```
  1072. *
  1073. * @param name Optional name of the app to return. If no name is
  1074. * provided, the default is `"[DEFAULT]"`.
  1075. *
  1076. * @return The app corresponding to the provided app name.
  1077. * If no app name is provided, the default app is returned.
  1078. */
  1079. function app(name?: string): firebase.app.App;
  1080. /**
  1081. * A (read-only) array of all initialized apps.
  1082. */
  1083. var apps: firebase.app.App[];
  1084. /**
  1085. * Gets the {@link firebase.auth.Auth `Auth`} service for the default app or a
  1086. * given app.
  1087. *
  1088. * `firebase.auth()` can be called with no arguments to access the default app's
  1089. * {@link firebase.auth.Auth `Auth`} service or as `firebase.auth(app)` to
  1090. * access the {@link firebase.auth.Auth `Auth`} service associated with a
  1091. * specific app.
  1092. *
  1093. * @example
  1094. * ```javascript
  1095. *
  1096. * // Get the Auth service for the default app
  1097. * var defaultAuth = firebase.auth();
  1098. * ```
  1099. * @example
  1100. * ```javascript
  1101. *
  1102. * // Get the Auth service for a given app
  1103. * var otherAuth = firebase.auth(otherApp);
  1104. * ```
  1105. * @param app
  1106. */
  1107. function auth(app?: firebase.app.App): firebase.auth.Auth;
  1108. /**
  1109. * Gets the {@link firebase.database.Database `Database`} service for the
  1110. * default app or a given app.
  1111. *
  1112. * `firebase.database()` can be called with no arguments to access the default
  1113. * app's {@link firebase.database.Database `Database`} service or as
  1114. * `firebase.database(app)` to access the
  1115. * {@link firebase.database.Database `Database`} service associated with a
  1116. * specific app.
  1117. *
  1118. * `firebase.database` is also a namespace that can be used to access global
  1119. * constants and methods associated with the `Database` service.
  1120. *
  1121. * @example
  1122. * ```javascript
  1123. * // Get the Database service for the default app
  1124. * var defaultDatabase = firebase.database();
  1125. * ```
  1126. *
  1127. * @example
  1128. * ```javascript
  1129. * // Get the Database service for a specific app
  1130. * var otherDatabase = firebase.database(app);
  1131. * ```
  1132. *
  1133. * @namespace
  1134. * @param app Optional app whose Database service to
  1135. * return. If not provided, the default Database service will be returned.
  1136. * @return The default Database service if no app
  1137. * is provided or the Database service associated with the provided app.
  1138. */
  1139. function database(app?: firebase.app.App): firebase.database.Database;
  1140. /**
  1141. * Creates and initializes a Firebase {@link firebase.app.App app} instance.
  1142. *
  1143. * See
  1144. * {@link
  1145. * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app
  1146. * Add Firebase to your app} and
  1147. * {@link
  1148. * https://firebase.google.com/docs/web/learn-more#multiple-projects
  1149. * Initialize multiple projects} for detailed documentation.
  1150. *
  1151. * @example
  1152. * ```javascript
  1153. *
  1154. * // Initialize default app
  1155. * // Retrieve your own options values by adding a web app on
  1156. * // https://console.firebase.google.com
  1157. * firebase.initializeApp({
  1158. * apiKey: "AIza....", // Auth / General Use
  1159. * appId: "1:27992087142:web:ce....", // General Use
  1160. * projectId: "my-firebase-project", // General Use
  1161. * authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect
  1162. * databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database
  1163. * storageBucket: "YOUR_APP.appspot.com", // Storage
  1164. * messagingSenderId: "123456789", // Cloud Messaging
  1165. * measurementId: "G-12345" // Analytics
  1166. * });
  1167. * ```
  1168. *
  1169. * @example
  1170. * ```javascript
  1171. *
  1172. * // Initialize another app
  1173. * var otherApp = firebase.initializeApp({
  1174. * apiKey: "AIza....",
  1175. * appId: "1:27992087142:web:ce....",
  1176. * projectId: "my-firebase-project",
  1177. * databaseURL: "https://<OTHER_DATABASE_NAME>.firebaseio.com",
  1178. * storageBucket: "<OTHER_STORAGE_BUCKET>.appspot.com"
  1179. * }, "nameOfOtherApp");
  1180. * ```
  1181. *
  1182. * @param options Options to configure the app's services.
  1183. * @param name Optional name of the app to initialize. If no name
  1184. * is provided, the default is `"[DEFAULT]"`.
  1185. *
  1186. * @return {!firebase.app.App} The initialized app.
  1187. */
  1188. function initializeApp(options: Object, name?: string): firebase.app.App;
  1189. /**
  1190. * Gets the {@link firebase.messaging.Messaging `Messaging`} service for the
  1191. * default app or a given app.
  1192. *
  1193. * `firebase.messaging()` can be called with no arguments to access the default
  1194. * app's {@link firebase.messaging.Messaging `Messaging`} service or as
  1195. * `firebase.messaging(app)` to access the
  1196. * {@link firebase.messaging.Messaging `Messaging`} service associated with a
  1197. * specific app.
  1198. *
  1199. * Calling `firebase.messaging()` in a service worker results in Firebase
  1200. * generating notifications if the push message payload has a `notification`
  1201. * parameter.
  1202. *
  1203. * @webonly
  1204. *
  1205. * @example
  1206. * ```javascript
  1207. * // Get the Messaging service for the default app
  1208. * var defaultMessaging = firebase.messaging();
  1209. * ```
  1210. *
  1211. * @example
  1212. * ```javascript
  1213. * // Get the Messaging service for a given app
  1214. * var otherMessaging = firebase.messaging(otherApp);
  1215. * ```
  1216. *
  1217. * @namespace
  1218. * @param app The app to create a Messaging service for.
  1219. * If not passed, uses the default app.
  1220. */
  1221. function messaging(app?: firebase.app.App): firebase.messaging.Messaging;
  1222. /**
  1223. * Gets the {@link firebase.storage.Storage `Storage`} service for the default
  1224. * app or a given app.
  1225. *
  1226. * `firebase.storage()` can be called with no arguments to access the default
  1227. * app's {@link firebase.storage.Storage `Storage`} service or as
  1228. * `firebase.storage(app)` to access the
  1229. * {@link firebase.storage.Storage `Storage`} service associated with a
  1230. * specific app.
  1231. *
  1232. * @example
  1233. * ```javascript
  1234. * // Get the Storage service for the default app
  1235. * var defaultStorage = firebase.storage();
  1236. * ```
  1237. *
  1238. * @example
  1239. * ```javascript
  1240. * // Get the Storage service for a given app
  1241. * var otherStorage = firebase.storage(otherApp);
  1242. * ```
  1243. *
  1244. * @param app The app to create a storage service for.
  1245. * If not passed, uses the default app.
  1246. */
  1247. function storage(app?: firebase.app.App): firebase.storage.Storage;
  1248. function firestore(app?: firebase.app.App): firebase.firestore.Firestore;
  1249. function functions(app?: firebase.app.App): firebase.functions.Functions;
  1250. /**
  1251. * Gets the {@link firebase.performance.Performance `Performance`} service.
  1252. *
  1253. * `firebase.performance()` can be called with no arguments to access the default
  1254. * app's {@link firebase.performance.Performance `Performance`} service.
  1255. * The {@link firebase.performance.Performance `Performance`} service does not work with
  1256. * any other app.
  1257. *
  1258. * @webonly
  1259. *
  1260. * @example
  1261. * ```javascript
  1262. * // Get the Performance service for the default app
  1263. * const defaultPerformance = firebase.performance();
  1264. * ```
  1265. *
  1266. * @param app The app to create a performance service for. Performance Monitoring only works with
  1267. * the default app.
  1268. * If not passed, uses the default app.
  1269. */
  1270. function performance(
  1271. app?: firebase.app.App
  1272. ): firebase.performance.Performance;
  1273. /**
  1274. * Gets the {@link firebase.remoteConfig.RemoteConfig `RemoteConfig`} instance.
  1275. *
  1276. * @webonly
  1277. *
  1278. * @example
  1279. * ```javascript
  1280. * // Get the RemoteConfig instance for the default app
  1281. * const defaultRemoteConfig = firebase.remoteConfig();
  1282. * ```
  1283. *
  1284. * @param app The app to create a Remote Config service for. If not passed, uses the default app.
  1285. */
  1286. function remoteConfig(
  1287. app?: firebase.app.App
  1288. ): firebase.remoteConfig.RemoteConfig;
  1289. /**
  1290. * Gets the {@link firebase.analytics.Analytics `Analytics`} service.
  1291. *
  1292. * `firebase.analytics()` can be called with no arguments to access the default
  1293. * app's {@link firebase.analytics.Analytics `Analytics`} service.
  1294. *
  1295. * @webonly
  1296. *
  1297. * @example
  1298. * ```javascript
  1299. * // Get the Analytics service for the default app
  1300. * const defaultAnalytics = firebase.analytics();
  1301. * ```
  1302. *
  1303. * @param app The app to create an analytics service for.
  1304. * If not passed, uses the default app.
  1305. */
  1306. function analytics(app?: firebase.app.App): firebase.analytics.Analytics;
  1307. function appCheck(app?: firebase.app.App): firebase.appCheck.AppCheck;
  1308. }
  1309. declare namespace firebase.app {
  1310. /**
  1311. * A Firebase App holds the initialization information for a collection of
  1312. * services.
  1313. *
  1314. * Do not call this constructor directly. Instead, use
  1315. * {@link firebase.initializeApp|`firebase.initializeApp()`} to create an app.
  1316. *
  1317. */
  1318. interface App {
  1319. /**
  1320. * Gets the {@link firebase.auth.Auth `Auth`} service for the current app.
  1321. *
  1322. * @example
  1323. * ```javascript
  1324. * var auth = app.auth();
  1325. * // The above is shorthand for:
  1326. * // var auth = firebase.auth(app);
  1327. * ```
  1328. */
  1329. auth(): firebase.auth.Auth;
  1330. /**
  1331. * Gets the {@link firebase.database.Database `Database`} service for the
  1332. * current app.
  1333. *
  1334. * @example
  1335. * ```javascript
  1336. * var database = app.database();
  1337. * // The above is shorthand for:
  1338. * // var database = firebase.database(app);
  1339. * ```
  1340. */
  1341. database(url?: string): firebase.database.Database;
  1342. /**
  1343. * Renders this app unusable and frees the resources of all associated
  1344. * services.
  1345. *
  1346. * @example
  1347. * ```javascript
  1348. * app.delete()
  1349. * .then(function() {
  1350. * console.log("App deleted successfully");
  1351. * })
  1352. * .catch(function(error) {
  1353. * console.log("Error deleting app:", error);
  1354. * });
  1355. * ```
  1356. */
  1357. delete(): Promise<any>;
  1358. /**
  1359. * Gets the {@link firebase.installations.Installations `Installations`} service for the
  1360. * current app.
  1361. *
  1362. * @webonly
  1363. *
  1364. * @example
  1365. * ```javascript
  1366. * const installations = app.installations();
  1367. * // The above is shorthand for:
  1368. * // const installations = firebase.installations(app);
  1369. * ```
  1370. */
  1371. installations(): firebase.installations.Installations;
  1372. /**
  1373. * Gets the {@link firebase.messaging.Messaging `Messaging`} service for the
  1374. * current app.
  1375. *
  1376. * @webonly
  1377. *
  1378. * @example
  1379. * ```javascript
  1380. * var messaging = app.messaging();
  1381. * // The above is shorthand for:
  1382. * // var messaging = firebase.messaging(app);
  1383. * ```
  1384. */
  1385. messaging(): firebase.messaging.Messaging;
  1386. /**
  1387. * The (read-only) name for this app.
  1388. *
  1389. * The default app's name is `"[DEFAULT]"`.
  1390. *
  1391. * @example
  1392. * ```javascript
  1393. * // The default app's name is "[DEFAULT]"
  1394. * firebase.initializeApp(defaultAppConfig);
  1395. * console.log(firebase.app().name); // "[DEFAULT]"
  1396. * ```
  1397. *
  1398. * @example
  1399. * ```javascript
  1400. * // A named app's name is what you provide to initializeApp()
  1401. * var otherApp = firebase.initializeApp(otherAppConfig, "other");
  1402. * console.log(otherApp.name); // "other"
  1403. * ```
  1404. */
  1405. name: string;
  1406. /**
  1407. * The settable config flag for GDPR opt-in/opt-out
  1408. */
  1409. automaticDataCollectionEnabled: boolean;
  1410. /**
  1411. * The (read-only) configuration options for this app. These are the original
  1412. * parameters given in
  1413. * {@link firebase.initializeApp `firebase.initializeApp()`}.
  1414. *
  1415. * @example
  1416. * ```javascript
  1417. * var app = firebase.initializeApp(config);
  1418. * console.log(app.options.databaseURL === config.databaseURL); // true
  1419. * ```
  1420. */
  1421. options: Object;
  1422. /**
  1423. * Gets the {@link firebase.storage.Storage `Storage`} service for the current
  1424. * app, optionally initialized with a custom storage bucket.
  1425. *
  1426. * @example
  1427. * ```javascript
  1428. * var storage = app.storage();
  1429. * // The above is shorthand for:
  1430. * // var storage = firebase.storage(app);
  1431. * ```
  1432. *
  1433. * @example
  1434. * ```javascript
  1435. * var storage = app.storage("gs://your-app.appspot.com");
  1436. * ```
  1437. *
  1438. * @param url The gs:// url to your Firebase Storage Bucket.
  1439. * If not passed, uses the app's default Storage Bucket.
  1440. */
  1441. storage(url?: string): firebase.storage.Storage;
  1442. firestore(): firebase.firestore.Firestore;
  1443. functions(regionOrCustomDomain?: string): firebase.functions.Functions;
  1444. /**
  1445. * Gets the {@link firebase.performance.Performance `Performance`} service for the
  1446. * current app. If the current app is not the default one, throws an error.
  1447. *
  1448. * @webonly
  1449. *
  1450. * @example
  1451. * ```javascript
  1452. * const perf = app.performance();
  1453. * // The above is shorthand for:
  1454. * // const perf = firebase.performance(app);
  1455. * ```
  1456. */
  1457. performance(): firebase.performance.Performance;
  1458. /**
  1459. * Gets the {@link firebase.remoteConfig.RemoteConfig `RemoteConfig`} instance.
  1460. *
  1461. * @webonly
  1462. *
  1463. * @example
  1464. * ```javascript
  1465. * const rc = app.remoteConfig();
  1466. * // The above is shorthand for:
  1467. * // const rc = firebase.remoteConfig(app);
  1468. * ```
  1469. */
  1470. remoteConfig(): firebase.remoteConfig.RemoteConfig;
  1471. /**
  1472. * Gets the {@link firebase.analytics.Analytics `Analytics`} service for the
  1473. * current app. If the current app is not the default one, throws an error.
  1474. *
  1475. * @webonly
  1476. *
  1477. * @example
  1478. * ```javascript
  1479. * const analytics = app.analytics();
  1480. * // The above is shorthand for:
  1481. * // const analytics = firebase.analytics(app);
  1482. * ```
  1483. */
  1484. analytics(): firebase.analytics.Analytics;
  1485. appCheck(): firebase.appCheck.AppCheck;
  1486. }
  1487. }
  1488. /**
  1489. * @webonly
  1490. */
  1491. declare namespace firebase.appCheck {
  1492. /**
  1493. * Result returned by
  1494. * {@link firebase.appCheck.AppCheck.getToken `firebase.appCheck().getToken()`}.
  1495. */
  1496. interface AppCheckTokenResult {
  1497. token: string;
  1498. }
  1499. /*
  1500. * reCAPTCHA v3 token provider.
  1501. */
  1502. class ReCaptchaV3Provider {
  1503. /**
  1504. * @param siteKey - reCAPTCHA v3 site key (public key).
  1505. */
  1506. constructor(siteKey: string);
  1507. }
  1508. /*
  1509. * reCAPTCHA Enterprise token provider.
  1510. */
  1511. class ReCaptchaEnterpriseProvider {
  1512. /**
  1513. * @param keyId - reCAPTCHA Enterprise key ID.
  1514. */
  1515. constructor(keyId: string);
  1516. }
  1517. /*
  1518. * Custom token provider.
  1519. */
  1520. class CustomProvider {
  1521. /**
  1522. * @param options - Options for creating the custom provider.
  1523. */
  1524. constructor(options: CustomProviderOptions);
  1525. }
  1526. /**
  1527. * Options when creating a CustomProvider.
  1528. */
  1529. interface CustomProviderOptions {
  1530. /**
  1531. * Function to get an App Check token through a custom provider
  1532. * service.
  1533. */
  1534. getToken: () => Promise<AppCheckToken>;
  1535. }
  1536. /**
  1537. * The Firebase AppCheck service interface.
  1538. *
  1539. * Do not call this constructor directly. Instead, use
  1540. * {@link firebase.appCheck `firebase.appCheck()`}.
  1541. */
  1542. export interface AppCheck {
  1543. /**
  1544. * Activate AppCheck
  1545. * @param provider This can be a `ReCaptchaV3Provider` instance,
  1546. * a `ReCaptchaEnterpriseProvider` instance, a `CustomProvider` instance,
  1547. * an object with a custom `getToken()` method, or a reCAPTCHA site key.
  1548. * @param isTokenAutoRefreshEnabled If true, the SDK automatically
  1549. * refreshes App Check tokens as needed. If undefined, defaults to the
  1550. * value of `app.automaticDataCollectionEnabled`, which defaults to
  1551. * false and can be set in the app config.
  1552. */
  1553. activate(
  1554. provider:
  1555. | ReCaptchaV3Provider
  1556. | ReCaptchaEnterpriseProvider
  1557. | CustomProvider
  1558. | AppCheckProvider
  1559. | { getToken: () => AppCheckToken }
  1560. | string,
  1561. isTokenAutoRefreshEnabled?: boolean
  1562. ): void;
  1563. /**
  1564. *
  1565. * @param isTokenAutoRefreshEnabled If true, the SDK automatically
  1566. * refreshes App Check tokens as needed. This overrides any value set
  1567. * during `activate()`.
  1568. */
  1569. setTokenAutoRefreshEnabled(isTokenAutoRefreshEnabled: boolean): void;
  1570. /**
  1571. * Get the current App Check token. Attaches to the most recent
  1572. * in-flight request if one is present. Returns null if no token
  1573. * is present and no token requests are in-flight.
  1574. *
  1575. * @param forceRefresh - If true, will always try to fetch a fresh token.
  1576. * If false, will use a cached token if found in storage.
  1577. */
  1578. getToken(
  1579. forceRefresh?: boolean
  1580. ): Promise<firebase.appCheck.AppCheckTokenResult>;
  1581. /**
  1582. * Registers a listener to changes in the token state. There can be more
  1583. * than one listener registered at the same time for one or more
  1584. * App Check instances. The listeners call back on the UI thread whenever
  1585. * the current token associated with this App Check instance changes.
  1586. *
  1587. * @param observer An object with `next`, `error`, and `complete`
  1588. * properties. `next` is called with an
  1589. * {@link firebase.appCheck.AppCheckTokenResult `AppCheckTokenResult`}
  1590. * whenever the token changes. `error` is optional and is called if an
  1591. * error is thrown by the listener (the `next` function). `complete`
  1592. * is unused, as the token stream is unending.
  1593. *
  1594. * @returns A function that unsubscribes this listener.
  1595. */
  1596. onTokenChanged(observer: {
  1597. next: (tokenResult: firebase.appCheck.AppCheckTokenResult) => void;
  1598. error?: (error: Error) => void;
  1599. complete?: () => void;
  1600. }): Unsubscribe;
  1601. /**
  1602. * Registers a listener to changes in the token state. There can be more
  1603. * than one listener registered at the same time for one or more
  1604. * App Check instances. The listeners call back on the UI thread whenever
  1605. * the current token associated with this App Check instance changes.
  1606. *
  1607. * @param onNext When the token changes, this function is called with aa
  1608. * {@link firebase.appCheck.AppCheckTokenResult `AppCheckTokenResult`}.
  1609. * @param onError Optional. Called if there is an error thrown by the
  1610. * listener (the `onNext` function).
  1611. * @param onCompletion Currently unused, as the token stream is unending.
  1612. * @returns A function that unsubscribes this listener.
  1613. */
  1614. onTokenChanged(
  1615. onNext: (tokenResult: firebase.appCheck.AppCheckTokenResult) => void,
  1616. onError?: (error: Error) => void,
  1617. onCompletion?: () => void
  1618. ): Unsubscribe;
  1619. }
  1620. /**
  1621. * An App Check provider. This can be either the built-in reCAPTCHA
  1622. * provider or a custom provider. For more on custom providers, see
  1623. * https://firebase.google.com/docs/app-check/web-custom-provider
  1624. */
  1625. interface AppCheckProvider {
  1626. /**
  1627. * Returns an AppCheck token.
  1628. */
  1629. getToken(): Promise<AppCheckToken>;
  1630. }
  1631. /**
  1632. * The token returned from an {@link firebase.appCheck.AppCheckProvider `AppCheckProvider`}.
  1633. */
  1634. interface AppCheckToken {
  1635. /**
  1636. * The token string in JWT format.
  1637. */
  1638. readonly token: string;
  1639. /**
  1640. * The local timestamp after which the token will expire.
  1641. */
  1642. readonly expireTimeMillis: number;
  1643. }
  1644. }
  1645. /**
  1646. * @webonly
  1647. */
  1648. declare namespace firebase.installations {
  1649. /**
  1650. * The Firebase Installations service interface.
  1651. *
  1652. * Do not call this constructor directly. Instead, use
  1653. * {@link firebase.installations `firebase.installations()`}.
  1654. */
  1655. export interface Installations {
  1656. /**
  1657. * The {@link firebase.app.App app} associated with the `Installations` service
  1658. * instance.
  1659. *
  1660. * @example
  1661. * ```javascript
  1662. * var app = analytics.app;
  1663. * ```
  1664. */
  1665. app: firebase.app.App;
  1666. /**
  1667. * Creates a Firebase Installation if there isn't one for the app and
  1668. * returns the Installation ID.
  1669. *
  1670. * @return Firebase Installation ID
  1671. */
  1672. getId(): Promise<string>;
  1673. /**
  1674. * Returns an Authentication Token for the current Firebase Installation.
  1675. *
  1676. * @return Firebase Installation Authentication Token
  1677. */
  1678. getToken(forceRefresh?: boolean): Promise<string>;
  1679. /**
  1680. * Deletes the Firebase Installation and all associated data.
  1681. */
  1682. delete(): Promise<void>;
  1683. /**
  1684. * Sets a new callback that will get called when Installlation ID changes.
  1685. * Returns an unsubscribe function that will remove the callback when called.
  1686. */
  1687. onIdChange(callback: (installationId: string) => void): () => void;
  1688. }
  1689. }
  1690. /**
  1691. * @webonly
  1692. */
  1693. declare namespace firebase.performance {
  1694. /**
  1695. * The Firebase Performance Monitoring service interface.
  1696. *
  1697. * Do not call this constructor directly. Instead, use
  1698. * {@link firebase.performance `firebase.performance()`}.
  1699. */
  1700. export interface Performance {
  1701. /**
  1702. * The {@link firebase.app.App app} associated with the `Performance` service
  1703. * instance.
  1704. *
  1705. * @example
  1706. * ```javascript
  1707. * var app = analytics.app;
  1708. * ```
  1709. */
  1710. app: firebase.app.App;
  1711. /**
  1712. * Creates an uninitialized instance of {@link firebase.performance.Trace `trace`} and returns
  1713. * it.
  1714. *
  1715. * @param traceName The name of the trace instance.
  1716. * @return The Trace instance.
  1717. */
  1718. trace(traceName: string): Trace;
  1719. /**
  1720. * Controls the logging of automatic traces and HTTP/S network monitoring.
  1721. */
  1722. instrumentationEnabled: boolean;
  1723. /**
  1724. * Controls the logging of custom traces.
  1725. */
  1726. dataCollectionEnabled: boolean;
  1727. }
  1728. export interface Trace {
  1729. /**
  1730. * Starts the timing for the {@link firebase.performance.Trace `trace`} instance.
  1731. */
  1732. start(): void;
  1733. /**
  1734. * Stops the timing of the {@link firebase.performance.Trace `trace`} instance and logs the
  1735. * data of the instance.
  1736. */
  1737. stop(): void;
  1738. /**
  1739. * Records a {@link firebase.performance.Trace `trace`} from given parameters. This provides a
  1740. * direct way to use {@link firebase.performance.Trace `trace`} without a need to start/stop.
  1741. * This is useful for use cases in which the {@link firebase.performance.Trace `trace`} cannot
  1742. * directly be used (e.g. if the duration was captured before the Performance SDK was loaded).
  1743. *
  1744. * @param startTime Trace start time since epoch in millisec.
  1745. * @param duration The duraction of the trace in millisec.
  1746. * @param options An object which can optionally hold maps of custom metrics and
  1747. * custom attributes.
  1748. */
  1749. record(
  1750. startTime: number,
  1751. duration: number,
  1752. options?: {
  1753. metrics?: { [key: string]: number };
  1754. attributes?: { [key: string]: string };
  1755. }
  1756. ): void;
  1757. /**
  1758. * Adds to the value of a custom metric. If a custom metric with the provided name does not
  1759. * exist, it creates one with that name and the value equal to the given number.
  1760. *
  1761. * @param metricName The name of the custom metric.
  1762. * @param num The number to be added to the value of the custom metric. If not provided, it
  1763. * uses a default value of one.
  1764. */
  1765. incrementMetric(metricName: string, num?: number): void;
  1766. /**
  1767. * Sets the value of the specified custom metric to the given number regardless of whether
  1768. * a metric with that name already exists on the {@link firebase.performance.Trace `trace`}
  1769. * instance or not.
  1770. *
  1771. * @param metricName Name of the custom metric.
  1772. * @param num Value to of the custom metric.
  1773. */
  1774. putMetric(metricName: string, num: number): void;
  1775. /**
  1776. * Returns the value of the custom metric by that name. If a custom metric with that name does
  1777. * not exist returns zero.
  1778. *
  1779. * @param metricName Name of the custom metric.
  1780. */
  1781. getMetric(metricName: string): number;
  1782. /**
  1783. * Set a custom attribute of a {@link firebase.performance.Trace `trace`} to a certain value.
  1784. *
  1785. * @param attr Name of the custom attribute.
  1786. * @param value Value of the custom attribute.
  1787. */
  1788. putAttribute(attr: string, value: string): void;
  1789. /**
  1790. * Retrieves the value that the custom attribute is set to.
  1791. *
  1792. * @param attr Name of the custom attribute.
  1793. */
  1794. getAttribute(attr: string): string | undefined;
  1795. /**
  1796. * Removes the specified custom attribute from a {@link firebase.performance.Trace `trace`}
  1797. * instance.
  1798. *
  1799. * @param attr Name of the custom attribute.
  1800. */
  1801. removeAttribute(attr: string): void;
  1802. /**
  1803. * Returns a map of all custom attributes of a {@link firebase.performance.Trace `trace`}
  1804. * instance.
  1805. */
  1806. getAttributes(): { [key: string]: string };
  1807. }
  1808. }
  1809. /**
  1810. * @webonly
  1811. */
  1812. declare namespace firebase.remoteConfig {
  1813. /**
  1814. * The Firebase Remote Config service interface.
  1815. *
  1816. * Do not call this constructor directly. Instead, use
  1817. * {@link firebase.remoteConfig `firebase.remoteConfig()`}.
  1818. */
  1819. export interface RemoteConfig {
  1820. /**
  1821. * The {@link firebase.app.App app} associated with the `Performance` service
  1822. * instance.
  1823. *
  1824. * @example
  1825. * ```javascript
  1826. * var app = analytics.app;
  1827. * ```
  1828. */
  1829. app: firebase.app.App;
  1830. /**
  1831. * Defines configuration for the Remote Config SDK.
  1832. */
  1833. settings: Settings;
  1834. /**
  1835. * Object containing default values for configs.
  1836. */
  1837. defaultConfig: { [key: string]: string | number | boolean };
  1838. /**
  1839. * The Unix timestamp in milliseconds of the last <i>successful</i> fetch, or negative one if
  1840. * the {@link RemoteConfig} instance either hasn't fetched or initialization
  1841. * is incomplete.
  1842. */
  1843. fetchTimeMillis: number;
  1844. /**
  1845. * The status of the last fetch <i>attempt</i>.
  1846. */
  1847. lastFetchStatus: FetchStatus;
  1848. /**
  1849. * Makes the last fetched config available to the getters.
  1850. * Returns a promise which resolves to true if the current call activated the fetched configs.
  1851. * If the fetched configs were already activated, the promise will resolve to false.
  1852. */
  1853. activate(): Promise<boolean>;
  1854. /**
  1855. * Ensures the last activated config are available to the getters.
  1856. */
  1857. ensureInitialized(): Promise<void>;
  1858. /**
  1859. * Fetches and caches configuration from the Remote Config service.
  1860. */
  1861. fetch(): Promise<void>;
  1862. /**
  1863. * Performs fetch and activate operations, as a convenience.
  1864. * Returns a promise which resolves to true if the current call activated the fetched configs.
  1865. * If the fetched configs were already activated, the promise will resolve to false.
  1866. */
  1867. fetchAndActivate(): Promise<boolean>;
  1868. /**
  1869. * Gets all config.
  1870. */
  1871. getAll(): { [key: string]: Value };
  1872. /**
  1873. * Gets the value for the given key as a boolean.
  1874. *
  1875. * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.
  1876. */
  1877. getBoolean(key: string): boolean;
  1878. /**
  1879. * Gets the value for the given key as a number.
  1880. *
  1881. * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.
  1882. */
  1883. getNumber(key: string): number;
  1884. /**
  1885. * Gets the value for the given key as a String.
  1886. *
  1887. * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.
  1888. */
  1889. getString(key: string): string;
  1890. /**
  1891. * Gets the {@link Value} for the given key.
  1892. */
  1893. getValue(key: string): Value;
  1894. /**
  1895. * Defines the log level to use.
  1896. */
  1897. setLogLevel(logLevel: LogLevel): void;
  1898. }
  1899. /**
  1900. * Indicates the source of a value.
  1901. *
  1902. * <ul>
  1903. * <li>"static" indicates the value was defined by a static constant.</li>
  1904. * <li>"default" indicates the value was defined by default config.</li>
  1905. * <li>"remote" indicates the value was defined by fetched config.</li>
  1906. * </ul>
  1907. */
  1908. export type ValueSource = 'static' | 'default' | 'remote';
  1909. /**
  1910. * Wraps a value with metadata and type-safe getters.
  1911. */
  1912. export interface Value {
  1913. /**
  1914. * Gets the value as a boolean.
  1915. *
  1916. * The following values (case insensitive) are interpreted as true:
  1917. * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false.
  1918. */
  1919. asBoolean(): boolean;
  1920. /**
  1921. * Gets the value as a number. Comparable to calling <code>Number(value) || 0</code>.
  1922. */
  1923. asNumber(): number;
  1924. /**
  1925. * Gets the value as a string.
  1926. */
  1927. asString(): string;
  1928. /**
  1929. * Gets the {@link ValueSource} for the given key.
  1930. */
  1931. getSource(): ValueSource;
  1932. }
  1933. /**
  1934. * Defines configuration options for the Remote Config SDK.
  1935. */
  1936. export interface Settings {
  1937. /**
  1938. * Defines the maximum age in milliseconds of an entry in the config cache before
  1939. * it is considered stale. Defaults to 43200000 (Twelve hours).
  1940. */
  1941. minimumFetchIntervalMillis: number;
  1942. /**
  1943. * Defines the maximum amount of milliseconds to wait for a response when fetching
  1944. * configuration from the Remote Config server. Defaults to 60000 (One minute).
  1945. */
  1946. fetchTimeoutMillis: number;
  1947. }
  1948. /**
  1949. * Summarizes the outcome of the last attempt to fetch config from the Firebase Remote Config server.
  1950. *
  1951. * <ul>
  1952. * <li>"no-fetch-yet" indicates the {@link RemoteConfig} instance has not yet attempted
  1953. * to fetch config, or that SDK initialization is incomplete.</li>
  1954. * <li>"success" indicates the last attempt succeeded.</li>
  1955. * <li>"failure" indicates the last attempt failed.</li>
  1956. * <li>"throttle" indicates the last attempt was rate-limited.</li>
  1957. * </ul>
  1958. */
  1959. export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle';
  1960. /**
  1961. * Defines levels of Remote Config logging.
  1962. */
  1963. export type LogLevel = 'debug' | 'error' | 'silent';
  1964. /**
  1965. * This method provides two different checks:
  1966. *
  1967. * 1. Check if IndexedDB exists in the browser environment.
  1968. * 2. Check if the current browser context allows IndexedDB `open()` calls.
  1969. *
  1970. * It returns a `Promise` which resolves to true if a {@link RemoteConfig} instance
  1971. * can be initialized in this environment, or false if it cannot.
  1972. */
  1973. export function isSupported(): Promise<boolean>;
  1974. }
  1975. declare namespace firebase.functions {
  1976. /**
  1977. * An HttpsCallableResult wraps a single result from a function call.
  1978. */
  1979. export interface HttpsCallableResult {
  1980. readonly data: any;
  1981. }
  1982. /**
  1983. * An HttpsCallable is a reference to a "callable" http trigger in
  1984. * Google Cloud Functions.
  1985. */
  1986. export interface HttpsCallable {
  1987. (data?: any): Promise<HttpsCallableResult>;
  1988. }
  1989. export interface HttpsCallableOptions {
  1990. timeout?: number;
  1991. }
  1992. /**
  1993. * The Cloud Functions for Firebase service interface.
  1994. *
  1995. * Do not call this constructor directly. Instead, use
  1996. * {@link firebase.functions `firebase.functions()`}.
  1997. */
  1998. export class Functions {
  1999. private constructor();
  2000. /**
  2001. * Modify this instance to communicate with the Cloud Functions emulator.
  2002. *
  2003. * Note: this must be called before this instance has been used to do any operations.
  2004. *
  2005. * @param host The emulator host (ex: localhost)
  2006. * @param port The emulator port (ex: 5001)
  2007. */
  2008. useEmulator(host: string, port: number): void;
  2009. /**
  2010. * Changes this instance to point to a Cloud Functions emulator running
  2011. * locally. See https://firebase.google.com/docs/functions/local-emulator
  2012. *
  2013. * @deprecated Prefer the useEmulator(host, port) method.
  2014. * @param origin The origin of the local emulator, such as
  2015. * "http://localhost:5005".
  2016. */
  2017. useFunctionsEmulator(url: string): void;
  2018. /**
  2019. * Gets an `HttpsCallable` instance that refers to the function with the given
  2020. * name.
  2021. *
  2022. * @param name The name of the https callable function.
  2023. * @param options The options for this HttpsCallable instance.
  2024. * @return The `HttpsCallable` instance.
  2025. */
  2026. httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable;
  2027. }
  2028. /**
  2029. * The set of Firebase Functions status codes. The codes are the same at the
  2030. * ones exposed by gRPC here:
  2031. * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  2032. *
  2033. * Possible values:
  2034. * - 'cancelled': The operation was cancelled (typically by the caller).
  2035. * - 'unknown': Unknown error or an error from a different error domain.
  2036. * - 'invalid-argument': Client specified an invalid argument. Note that this
  2037. * differs from 'failed-precondition'. 'invalid-argument' indicates
  2038. * arguments that are problematic regardless of the state of the system
  2039. * (e.g. an invalid field name).
  2040. * - 'deadline-exceeded': Deadline expired before operation could complete.
  2041. * For operations that change the state of the system, this error may be
  2042. * returned even if the operation has completed successfully. For example,
  2043. * a successful response from a server could have been delayed long enough
  2044. * for the deadline to expire.
  2045. * - 'not-found': Some requested document was not found.
  2046. * - 'already-exists': Some document that we attempted to create already
  2047. * exists.
  2048. * - 'permission-denied': The caller does not have permission to execute the
  2049. * specified operation.
  2050. * - 'resource-exhausted': Some resource has been exhausted, perhaps a
  2051. * per-user quota, or perhaps the entire file system is out of space.
  2052. * - 'failed-precondition': Operation was rejected because the system is not
  2053. * in a state required for the operation's execution.
  2054. * - 'aborted': The operation was aborted, typically due to a concurrency
  2055. * issue like transaction aborts, etc.
  2056. * - 'out-of-range': Operation was attempted past the valid range.
  2057. * - 'unimplemented': Operation is not implemented or not supported/enabled.
  2058. * - 'internal': Internal errors. Means some invariants expected by
  2059. * underlying system has been broken. If you see one of these errors,
  2060. * something is very broken.
  2061. * - 'unavailable': The service is currently unavailable. This is most likely
  2062. * a transient condition and may be corrected by retrying with a backoff.
  2063. * - 'data-loss': Unrecoverable data loss or corruption.
  2064. * - 'unauthenticated': The request does not have valid authentication
  2065. * credentials for the operation.
  2066. */
  2067. export type FunctionsErrorCode =
  2068. | 'ok'
  2069. | 'cancelled'
  2070. | 'unknown'
  2071. | 'invalid-argument'
  2072. | 'deadline-exceeded'
  2073. | 'not-found'
  2074. | 'already-exists'
  2075. | 'permission-denied'
  2076. | 'resource-exhausted'
  2077. | 'failed-precondition'
  2078. | 'aborted'
  2079. | 'out-of-range'
  2080. | 'unimplemented'
  2081. | 'internal'
  2082. | 'unavailable'
  2083. | 'data-loss'
  2084. | 'unauthenticated';
  2085. export interface HttpsError extends Error {
  2086. /**
  2087. * A standard error code that will be returned to the client. This also
  2088. * determines the HTTP status code of the response, as defined in code.proto.
  2089. */
  2090. readonly code: FunctionsErrorCode;
  2091. /**
  2092. * Extra data to be converted to JSON and included in the error response.
  2093. */
  2094. readonly details?: any;
  2095. }
  2096. }
  2097. declare namespace firebase.auth {
  2098. /**
  2099. * A utility class to parse email action URLs.
  2100. */
  2101. class ActionCodeURL {
  2102. private constructor();
  2103. /**
  2104. * The API key of the email action link.
  2105. */
  2106. apiKey: string;
  2107. /**
  2108. * The action code of the email action link.
  2109. */
  2110. code: string;
  2111. /**
  2112. * The continue URL of the email action link. Null if not provided.
  2113. */
  2114. continueUrl: string | null;
  2115. /**
  2116. * The language code of the email action link. Null if not provided.
  2117. */
  2118. languageCode: string | null;
  2119. /**
  2120. * The action performed by the email action link. It returns from one
  2121. * of the types from {@link firebase.auth.ActionCodeInfo}.
  2122. */
  2123. operation: firebase.auth.ActionCodeInfo.Operation;
  2124. /**
  2125. * Parses the email action link string and returns an ActionCodeURL object
  2126. * if the link is valid, otherwise returns null.
  2127. *
  2128. * @param link The email action link string.
  2129. * @return The ActionCodeURL object, or null if the link is invalid.
  2130. */
  2131. static parseLink(link: string): firebase.auth.ActionCodeURL | null;
  2132. /**
  2133. * The tenant ID of the email action link. Null if the email action
  2134. * is from the parent project.
  2135. */
  2136. tenantId: string | null;
  2137. }
  2138. /**
  2139. * A response from {@link firebase.auth.Auth.checkActionCode}.
  2140. */
  2141. interface ActionCodeInfo {
  2142. /**
  2143. * The data associated with the action code.
  2144. *
  2145. * For the `PASSWORD_RESET`, `VERIFY_EMAIL`, and `RECOVER_EMAIL` actions, this object
  2146. * contains an `email` field with the address the email was sent to.
  2147. *
  2148. * For the RECOVER_EMAIL action, which allows a user to undo an email address
  2149. * change, this object also contains a `previousEmail` field with the user account's
  2150. * current email address. After the action completes, the user's email address will
  2151. * revert to the value in the `email` field from the value in `previousEmail` field.
  2152. *
  2153. * For the VERIFY_AND_CHANGE_EMAIL action, which allows a user to verify the email
  2154. * before updating it, this object contains a `previousEmail` field with the user
  2155. * account's email address before updating. After the action completes, the user's
  2156. * email address will be updated to the value in the `email` field from the value
  2157. * in `previousEmail` field.
  2158. *
  2159. * For the REVERT_SECOND_FACTOR_ADDITION action, which allows a user to unenroll
  2160. * a newly added second factor, this object contains a `multiFactorInfo` field with
  2161. * the information about the second factor. For phone second factor, the
  2162. * `multiFactorInfo` is a {@link firebase.auth.PhoneMultiFactorInfo} object,
  2163. * which contains the phone number.
  2164. */
  2165. data: {
  2166. email?: string | null;
  2167. /**
  2168. * @deprecated
  2169. * This field is deprecated in favor of previousEmail.
  2170. */
  2171. fromEmail?: string | null;
  2172. multiFactorInfo?: firebase.auth.MultiFactorInfo | null;
  2173. previousEmail?: string | null;
  2174. };
  2175. /**
  2176. * The type of operation that generated the action code. This could be:
  2177. * <ul>
  2178. * <li>`EMAIL_SIGNIN`: email sign in code generated via
  2179. * {@link firebase.auth.Auth.sendSignInLinkToEmail}.</li>
  2180. * <li>`PASSWORD_RESET`: password reset code generated via
  2181. * {@link firebase.auth.Auth.sendPasswordResetEmail}.</li>
  2182. * <li>`RECOVER_EMAIL`: email change revocation code generated via
  2183. * {@link firebase.User.updateEmail}.</li>
  2184. * <li>`REVERT_SECOND_FACTOR_ADDITION`: revert second factor addition
  2185. * code generated via
  2186. * {@link firebase.User.MultiFactorUser.enroll}.</li>
  2187. * <li>`VERIFY_AND_CHANGE_EMAIL`: verify and change email code generated
  2188. * via {@link firebase.User.verifyBeforeUpdateEmail}.</li>
  2189. * <li>`VERIFY_EMAIL`: email verification code generated via
  2190. * {@link firebase.User.sendEmailVerification}.</li>
  2191. * </ul>
  2192. */
  2193. operation: string;
  2194. }
  2195. /**
  2196. * This is the interface that defines the required continue/state URL with
  2197. * optional Android and iOS bundle identifiers.
  2198. * The action code setting fields are:
  2199. * <ul>
  2200. * <li><p>url: Sets the link continue/state URL, which has different meanings
  2201. * in different contexts:</p>
  2202. * <ul>
  2203. * <li>When the link is handled in the web action widgets, this is the deep
  2204. * link in the continueUrl query parameter.</li>
  2205. * <li>When the link is handled in the app directly, this is the continueUrl
  2206. * query parameter in the deep link of the Dynamic Link.</li>
  2207. * </ul>
  2208. * </li>
  2209. * <li>iOS: Sets the iOS bundle ID. This will try to open the link in an iOS app
  2210. * if it is installed.</li>
  2211. * <li>android: Sets the Android package name. This will try to open the link in
  2212. * an android app if it is installed. If installApp is passed, it specifies
  2213. * whether to install the Android app if the device supports it and the app
  2214. * is not already installed. If this field is provided without a
  2215. * packageName, an error is thrown explaining that the packageName must be
  2216. * provided in conjunction with this field.
  2217. * If minimumVersion is specified, and an older version of the app is
  2218. * installed, the user is taken to the Play Store to upgrade the app.</li>
  2219. * <li>handleCodeInApp: The default is false. When set to true, the action code
  2220. * link will be be sent as a Universal Link or Android App Link and will be
  2221. * opened by the app if installed. In the false case, the code will be sent
  2222. * to the web widget first and then on continue will redirect to the app if
  2223. * installed.</li>
  2224. * </ul>
  2225. */
  2226. type ActionCodeSettings = {
  2227. android?: {
  2228. installApp?: boolean;
  2229. minimumVersion?: string;
  2230. packageName: string;
  2231. };
  2232. handleCodeInApp?: boolean;
  2233. iOS?: { bundleId: string };
  2234. url: string;
  2235. dynamicLinkDomain?: string;
  2236. };
  2237. /**
  2238. * A structure containing additional user information from a federated identity
  2239. * provider.
  2240. */
  2241. type AdditionalUserInfo = {
  2242. isNewUser: boolean;
  2243. profile: Object | null;
  2244. providerId: string;
  2245. username?: string | null;
  2246. };
  2247. /**
  2248. * A verifier for domain verification and abuse prevention. Currently, the
  2249. * only implementation is {@link firebase.auth.RecaptchaVerifier}.
  2250. */
  2251. interface ApplicationVerifier {
  2252. /**
  2253. * Identifies the type of application verifier (e.g. "recaptcha").
  2254. */
  2255. type: string;
  2256. /**
  2257. * Executes the verification process.
  2258. * @return A Promise for a token that can be used to
  2259. * assert the validity of a request.
  2260. */
  2261. verify(): Promise<string>;
  2262. }
  2263. /**
  2264. * Interface representing an Auth instance's settings, currently used for
  2265. * enabling/disabling app verification for phone Auth testing.
  2266. */
  2267. interface AuthSettings {
  2268. /**
  2269. * When set, this property disables app verification for the purpose of testing
  2270. * phone authentication. For this property to take effect, it needs to be set
  2271. * before rendering a reCAPTCHA app verifier. When this is disabled, a
  2272. * mock reCAPTCHA is rendered instead. This is useful for manual testing during
  2273. * development or for automated integration tests.
  2274. *
  2275. * In order to use this feature, you will need to
  2276. * {@link https://firebase.google.com/docs/auth/web/phone-auth#test-with-whitelisted-phone-numbers
  2277. * whitelist your phone number} via the
  2278. * Firebase Console.
  2279. *
  2280. * The default value is false (app verification is enabled).
  2281. */
  2282. appVerificationDisabledForTesting: boolean;
  2283. }
  2284. /**
  2285. * Interface representing the Auth config.
  2286. *
  2287. * @public
  2288. */
  2289. export interface Config {
  2290. /**
  2291. * The API Key used to communicate with the Firebase Auth backend.
  2292. */
  2293. apiKey: string;
  2294. /**
  2295. * The host at which the Firebase Auth backend is running.
  2296. */
  2297. apiHost: string;
  2298. /**
  2299. * The scheme used to communicate with the Firebase Auth backend.
  2300. */
  2301. apiScheme: string;
  2302. /**
  2303. * The host at which the Secure Token API is running.
  2304. */
  2305. tokenApiHost: string;
  2306. /**
  2307. * The SDK Client Version.
  2308. */
  2309. sdkClientVersion: string;
  2310. /**
  2311. * The domain at which the web widgets are hosted (provided via Firebase Config).
  2312. */
  2313. authDomain?: string;
  2314. }
  2315. /**
  2316. * Configuration of Firebase Authentication Emulator.
  2317. */
  2318. export interface EmulatorConfig {
  2319. /**
  2320. * The protocol used to communicate with the emulator ("http"/"https").
  2321. */
  2322. readonly protocol: string;
  2323. /**
  2324. * The hostname of the emulator, which may be a domain ("localhost"), IPv4 address ("127.0.0.1")
  2325. * or quoted IPv6 address ("[::1]").
  2326. */
  2327. readonly host: string;
  2328. /**
  2329. * The port of the emulator, or null if port isn't specified (i.e. protocol default).
  2330. */
  2331. readonly port: number | null;
  2332. /**
  2333. * The emulator-specific options.
  2334. */
  2335. readonly options: {
  2336. /**
  2337. * Whether the warning banner attached to the DOM was disabled.
  2338. */
  2339. readonly disableWarnings: boolean;
  2340. };
  2341. }
  2342. /**
  2343. * The Firebase Auth service interface.
  2344. *
  2345. * Do not call this constructor directly. Instead, use
  2346. * {@link firebase.auth `firebase.auth()`}.
  2347. *
  2348. * See
  2349. * {@link https://firebase.google.com/docs/auth/ Firebase Authentication}
  2350. * for a full guide on how to use the Firebase Auth service.
  2351. *
  2352. */
  2353. interface Auth {
  2354. /** The name of the app associated with the Auth service instance. */
  2355. readonly name: string;
  2356. /** The config used to initialize this instance. */
  2357. readonly config: Config;
  2358. /** The current emulator configuration (or null). */
  2359. readonly emulatorConfig: EmulatorConfig | null;
  2360. /**
  2361. * The {@link firebase.app.App app} associated with the `Auth` service
  2362. * instance.
  2363. *
  2364. * @example
  2365. * ```javascript
  2366. * var app = auth.app;
  2367. * ```
  2368. */
  2369. app: firebase.app.App;
  2370. /**
  2371. * Applies a verification code sent to the user by email or other out-of-band
  2372. * mechanism.
  2373. *
  2374. * <h4>Error Codes</h4>
  2375. * <dl>
  2376. * <dt>auth/expired-action-code</dt>
  2377. * <dd>Thrown if the action code has expired.</dd>
  2378. * <dt>auth/invalid-action-code</dt>
  2379. * <dd>Thrown if the action code is invalid. This can happen if the code is
  2380. * malformed or has already been used.</dd>
  2381. * <dt>auth/user-disabled</dt>
  2382. * <dd>Thrown if the user corresponding to the given action code has been
  2383. * disabled.</dd>
  2384. * <dt>auth/user-not-found</dt>
  2385. * <dd>Thrown if there is no user corresponding to the action code. This may
  2386. * have happened if the user was deleted between when the action code was
  2387. * issued and when this method was called.</dd>
  2388. * </dl>
  2389. *
  2390. * @param code A verification code sent to the user.
  2391. */
  2392. applyActionCode(code: string): Promise<void>;
  2393. /**
  2394. * Checks a verification code sent to the user by email or other out-of-band
  2395. * mechanism.
  2396. *
  2397. * Returns metadata about the code.
  2398. *
  2399. * <h4>Error Codes</h4>
  2400. * <dl>
  2401. * <dt>auth/expired-action-code</dt>
  2402. * <dd>Thrown if the action code has expired.</dd>
  2403. * <dt>auth/invalid-action-code</dt>
  2404. * <dd>Thrown if the action code is invalid. This can happen if the code is
  2405. * malformed or has already been used.</dd>
  2406. * <dt>auth/user-disabled</dt>
  2407. * <dd>Thrown if the user corresponding to the given action code has been
  2408. * disabled.</dd>
  2409. * <dt>auth/user-not-found</dt>
  2410. * <dd>Thrown if there is no user corresponding to the action code. This may
  2411. * have happened if the user was deleted between when the action code was
  2412. * issued and when this method was called.</dd>
  2413. * </dl>
  2414. *
  2415. * @param code A verification code sent to the user.
  2416. */
  2417. checkActionCode(code: string): Promise<firebase.auth.ActionCodeInfo>;
  2418. /**
  2419. * Completes the password reset process, given a confirmation code and new
  2420. * password.
  2421. *
  2422. * <h4>Error Codes</h4>
  2423. * <dl>
  2424. * <dt>auth/expired-action-code</dt>
  2425. * <dd>Thrown if the password reset code has expired.</dd>
  2426. * <dt>auth/invalid-action-code</dt>
  2427. * <dd>Thrown if the password reset code is invalid. This can happen if the
  2428. * code is malformed or has already been used.</dd>
  2429. * <dt>auth/user-disabled</dt>
  2430. * <dd>Thrown if the user corresponding to the given password reset code has
  2431. * been disabled.</dd>
  2432. * <dt>auth/user-not-found</dt>
  2433. * <dd>Thrown if there is no user corresponding to the password reset code. This
  2434. * may have happened if the user was deleted between when the code was
  2435. * issued and when this method was called.</dd>
  2436. * <dt>auth/weak-password</dt>
  2437. * <dd>Thrown if the new password is not strong enough.</dd>
  2438. * </dl>
  2439. *
  2440. * @param code The confirmation code send via email to the user.
  2441. * @param newPassword The new password.
  2442. */
  2443. confirmPasswordReset(code: string, newPassword: string): Promise<void>;
  2444. /**
  2445. * Creates a new user account associated with the specified email address and
  2446. * password.
  2447. *
  2448. * On successful creation of the user account, this user will also be
  2449. * signed in to your application.
  2450. *
  2451. * User account creation can fail if the account already exists or the password
  2452. * is invalid.
  2453. *
  2454. * Note: The email address acts as a unique identifier for the user and
  2455. * enables an email-based password reset. This function will create
  2456. * a new user account and set the initial user password.
  2457. *
  2458. * <h4>Error Codes</h4>
  2459. * <dl>
  2460. * <dt>auth/email-already-in-use</dt>
  2461. * <dd>Thrown if there already exists an account with the given email
  2462. * address.</dd>
  2463. * <dt>auth/invalid-email</dt>
  2464. * <dd>Thrown if the email address is not valid.</dd>
  2465. * <dt>auth/operation-not-allowed</dt>
  2466. * <dd>Thrown if email/password accounts are not enabled. Enable email/password
  2467. * accounts in the Firebase Console, under the Auth tab.</dd>
  2468. * <dt>auth/weak-password</dt>
  2469. * <dd>Thrown if the password is not strong enough.</dd>
  2470. * </dl>
  2471. *
  2472. * @example
  2473. * ```javascript
  2474. * firebase.auth().createUserWithEmailAndPassword(email, password)
  2475. * .catch(function(error) {
  2476. * // Handle Errors here.
  2477. * var errorCode = error.code;
  2478. * var errorMessage = error.message;
  2479. * if (errorCode == 'auth/weak-password') {
  2480. * alert('The password is too weak.');
  2481. * } else {
  2482. * alert(errorMessage);
  2483. * }
  2484. * console.log(error);
  2485. * });
  2486. * ```
  2487. * @param email The user's email address.
  2488. * @param password The user's chosen password.
  2489. */
  2490. createUserWithEmailAndPassword(
  2491. email: string,
  2492. password: string
  2493. ): Promise<firebase.auth.UserCredential>;
  2494. /**
  2495. * The currently signed-in user (or null).
  2496. */
  2497. currentUser: firebase.User | null;
  2498. /**
  2499. * Gets the list of possible sign in methods for the given email address. This
  2500. * is useful to differentiate methods of sign-in for the same provider,
  2501. * eg. `EmailAuthProvider` which has 2 methods of sign-in, email/password and
  2502. * email/link.
  2503. *
  2504. * <h4>Error Codes</h4>
  2505. * <dl>
  2506. * <dt>auth/invalid-email</dt>
  2507. * <dd>Thrown if the email address is not valid.</dd>
  2508. * </dl>
  2509. */
  2510. fetchSignInMethodsForEmail(email: string): Promise<Array<string>>;
  2511. /**
  2512. * Checks if an incoming link is a sign-in with email link.
  2513. */
  2514. isSignInWithEmailLink(emailLink: string): boolean;
  2515. /**
  2516. * Returns a UserCredential from the redirect-based sign-in flow.
  2517. *
  2518. * If sign-in succeeded, returns the signed in user. If sign-in was
  2519. * unsuccessful, fails with an error. If no redirect operation was called, returns `null`.
  2520. *
  2521. * <h4>Error Codes</h4>
  2522. * <dl>
  2523. * <dt>auth/account-exists-with-different-credential</dt>
  2524. * <dd>Thrown if there already exists an account with the email address
  2525. * asserted by the credential. Resolve this by calling
  2526. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail} with the error.email
  2527. * and then asking the user to sign in using one of the returned providers.
  2528. * Once the user is signed in, the original credential retrieved from the
  2529. * error.credential can be linked to the user with
  2530. * {@link firebase.User.linkWithCredential} to prevent the user from signing
  2531. * in again to the original provider via popup or redirect. If you are using
  2532. * redirects for sign in, save the credential in session storage and then
  2533. * retrieve on redirect and repopulate the credential using for example
  2534. * {@link firebase.auth.GoogleAuthProvider.credential} depending on the
  2535. * credential provider id and complete the link.</dd>
  2536. * <dt>auth/auth-domain-config-required</dt>
  2537. * <dd>Thrown if authDomain configuration is not provided when calling
  2538. * firebase.initializeApp(). Check Firebase Console for instructions on
  2539. * determining and passing that field.</dd>
  2540. * <dt>auth/credential-already-in-use</dt>
  2541. * <dd>Thrown if the account corresponding to the credential already exists
  2542. * among your users, or is already linked to a Firebase User.
  2543. * For example, this error could be thrown if you are upgrading an anonymous
  2544. * user to a Google user by linking a Google credential to it and the Google
  2545. * credential used is already associated with an existing Firebase Google
  2546. * user.
  2547. * An <code>error.email</code> and <code>error.credential</code>
  2548. * ({@link firebase.auth.AuthCredential}) fields are also provided. You can
  2549. * recover from this error by signing in with that credential directly via
  2550. * {@link firebase.auth.Auth.signInWithCredential}.</dd>
  2551. * <dt>auth/email-already-in-use</dt>
  2552. * <dd>Thrown if the email corresponding to the credential already exists
  2553. * among your users. When thrown while linking a credential to an existing
  2554. * user, an <code>error.email</code> and <code>error.credential</code>
  2555. * ({@link firebase.auth.AuthCredential}) fields are also provided.
  2556. * You have to link the credential to the existing user with that email if
  2557. * you wish to continue signing in with that credential. To do so, call
  2558. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}, sign in to
  2559. * <code>error.email</code> via one of the providers returned and then
  2560. * {@link firebase.User.linkWithCredential} the original credential to that
  2561. * newly signed in user.</dd>
  2562. * <dt>auth/operation-not-allowed</dt>
  2563. * <dd>Thrown if the type of account corresponding to the credential
  2564. * is not enabled. Enable the account type in the Firebase Console, under
  2565. * the Auth tab.</dd>
  2566. * <dt>auth/operation-not-supported-in-this-environment</dt>
  2567. * <dd>Thrown if this operation is not supported in the environment your
  2568. * application is running on. "location.protocol" must be http or https.
  2569. * </dd>
  2570. * <dt>auth/timeout</dt>
  2571. * <dd>Thrown typically if the app domain is not authorized for OAuth operations
  2572. * for your Firebase project. Edit the list of authorized domains from the
  2573. * Firebase console.</dd>
  2574. * </dl>
  2575. *
  2576. * @webonly
  2577. *
  2578. * @example
  2579. * ```javascript
  2580. * // First, we perform the signInWithRedirect.
  2581. * // Creates the provider object.
  2582. * var provider = new firebase.auth.FacebookAuthProvider();
  2583. * // You can add additional scopes to the provider:
  2584. * provider.addScope('email');
  2585. * provider.addScope('user_friends');
  2586. * // Sign in with redirect:
  2587. * auth.signInWithRedirect(provider)
  2588. * ////////////////////////////////////////////////////////////
  2589. * // The user is redirected to the provider's sign in flow...
  2590. * ////////////////////////////////////////////////////////////
  2591. * // Then redirected back to the app, where we check the redirect result:
  2592. * auth.getRedirectResult().then(function(result) {
  2593. * // The firebase.User instance:
  2594. * var user = result.user;
  2595. * // The Facebook firebase.auth.AuthCredential containing the Facebook
  2596. * // access token:
  2597. * var credential = result.credential;
  2598. * // As this API can be used for sign-in, linking and reauthentication,
  2599. * // check the operationType to determine what triggered this redirect
  2600. * // operation.
  2601. * var operationType = result.operationType;
  2602. * }, function(error) {
  2603. * // The provider's account email, can be used in case of
  2604. * // auth/account-exists-with-different-credential to fetch the providers
  2605. * // linked to the email:
  2606. * var email = error.email;
  2607. * // The provider's credential:
  2608. * var credential = error.credential;
  2609. * // In case of auth/account-exists-with-different-credential error,
  2610. * // you can fetch the providers using this:
  2611. * if (error.code === 'auth/account-exists-with-different-credential') {
  2612. * auth.fetchSignInMethodsForEmail(email).then(function(providers) {
  2613. * // The returned 'providers' is a list of the available providers
  2614. * // linked to the email address. Please refer to the guide for a more
  2615. * // complete explanation on how to recover from this error.
  2616. * });
  2617. * }
  2618. * });
  2619. * ```
  2620. */
  2621. getRedirectResult(): Promise<firebase.auth.UserCredential>;
  2622. /**
  2623. * The current Auth instance's language code. This is a readable/writable
  2624. * property. When set to null, the default Firebase Console language setting
  2625. * is applied. The language code will propagate to email action templates
  2626. * (password reset, email verification and email change revocation), SMS
  2627. * templates for phone authentication, reCAPTCHA verifier and OAuth
  2628. * popup/redirect operations provided the specified providers support
  2629. * localization with the language code specified.
  2630. */
  2631. languageCode: string | null;
  2632. /**
  2633. * The current Auth instance's settings. This is used to edit/read configuration
  2634. * related options like app verification mode for phone authentication.
  2635. */
  2636. settings: firebase.auth.AuthSettings;
  2637. /**
  2638. * Adds an observer for changes to the user's sign-in state.
  2639. *
  2640. * Prior to 4.0.0, this triggered the observer when users were signed in,
  2641. * signed out, or when the user's ID token changed in situations such as token
  2642. * expiry or password change. After 4.0.0, the observer is only triggered
  2643. * on sign-in or sign-out.
  2644. *
  2645. * To keep the old behavior, see {@link firebase.auth.Auth.onIdTokenChanged}.
  2646. *
  2647. * @example
  2648. * ```javascript
  2649. * firebase.auth().onAuthStateChanged(function(user) {
  2650. * if (user) {
  2651. * // User is signed in.
  2652. * }
  2653. * });
  2654. * ```
  2655. */
  2656. onAuthStateChanged(
  2657. nextOrObserver:
  2658. | firebase.Observer<any>
  2659. | ((a: firebase.User | null) => any),
  2660. error?: (a: firebase.auth.Error) => any,
  2661. completed?: firebase.Unsubscribe
  2662. ): firebase.Unsubscribe;
  2663. /**
  2664. * Adds an observer for changes to the signed-in user's ID token, which includes
  2665. * sign-in, sign-out, and token refresh events. This method has the same
  2666. * behavior as {@link firebase.auth.Auth.onAuthStateChanged} had prior to 4.0.0.
  2667. *
  2668. * @example
  2669. * ```javascript
  2670. * firebase.auth().onIdTokenChanged(function(user) {
  2671. * if (user) {
  2672. * // User is signed in or token was refreshed.
  2673. * }
  2674. * });
  2675. * ```
  2676. * @param
  2677. * nextOrObserver An observer object or a function triggered on change.
  2678. * @param error Optional A function
  2679. * triggered on auth error.
  2680. * @param completed Optional A function triggered when the
  2681. * observer is removed.
  2682. */
  2683. onIdTokenChanged(
  2684. nextOrObserver:
  2685. | firebase.Observer<any>
  2686. | ((a: firebase.User | null) => any),
  2687. error?: (a: firebase.auth.Error) => any,
  2688. completed?: firebase.Unsubscribe
  2689. ): firebase.Unsubscribe;
  2690. /**
  2691. * Sends a sign-in email link to the user with the specified email.
  2692. *
  2693. * The sign-in operation has to always be completed in the app unlike other out
  2694. * of band email actions (password reset and email verifications). This is
  2695. * because, at the end of the flow, the user is expected to be signed in and
  2696. * their Auth state persisted within the app.
  2697. *
  2698. * To complete sign in with the email link, call
  2699. * {@link firebase.auth.Auth.signInWithEmailLink} with the email address and
  2700. * the email link supplied in the email sent to the user.
  2701. *
  2702. * <h4>Error Codes</h4>
  2703. * <dl>
  2704. * <dt>auth/argument-error</dt>
  2705. * <dd>Thrown if handleCodeInApp is false.</dd>
  2706. * <dt>auth/invalid-email</dt>
  2707. * <dd>Thrown if the email address is not valid.</dd>
  2708. * <dt>auth/missing-android-pkg-name</dt>
  2709. * <dd>An Android package name must be provided if the Android app is required
  2710. * to be installed.</dd>
  2711. * <dt>auth/missing-continue-uri</dt>
  2712. * <dd>A continue URL must be provided in the request.</dd>
  2713. * <dt>auth/missing-ios-bundle-id</dt>
  2714. * <dd>An iOS Bundle ID must be provided if an App Store ID is provided.</dd>
  2715. * <dt>auth/invalid-continue-uri</dt>
  2716. * <dd>The continue URL provided in the request is invalid.</dd>
  2717. * <dt>auth/unauthorized-continue-uri</dt>
  2718. * <dd>The domain of the continue URL is not whitelisted. Whitelist
  2719. * the domain in the Firebase console.</dd>
  2720. * </dl>
  2721. *
  2722. * @example
  2723. * ```javascript
  2724. * var actionCodeSettings = {
  2725. * // The URL to redirect to for sign-in completion. This is also the deep
  2726. * // link for mobile redirects. The domain (www.example.com) for this URL
  2727. * // must be whitelisted in the Firebase Console.
  2728. * url: 'https://www.example.com/finishSignUp?cartId=1234',
  2729. * iOS: {
  2730. * bundleId: 'com.example.ios'
  2731. * },
  2732. * android: {
  2733. * packageName: 'com.example.android',
  2734. * installApp: true,
  2735. * minimumVersion: '12'
  2736. * },
  2737. * // This must be true.
  2738. * handleCodeInApp: true
  2739. * };
  2740. * firebase.auth().sendSignInLinkToEmail('user@example.com', actionCodeSettings)
  2741. * .then(function() {
  2742. * // The link was successfully sent. Inform the user. Save the email
  2743. * // locally so you don't need to ask the user for it again if they open
  2744. * // the link on the same device.
  2745. * })
  2746. * .catch(function(error) {
  2747. * // Some error occurred, you can inspect the code: error.code
  2748. * });
  2749. * ```
  2750. * @param email The email account to sign in with.
  2751. * @param actionCodeSettings The action
  2752. * code settings. The action code settings which provides Firebase with
  2753. * instructions on how to construct the email link. This includes the
  2754. * sign in completion URL or the deep link for mobile redirects, the mobile
  2755. * apps to use when the sign-in link is opened on an Android or iOS device.
  2756. * Mobile app redirects will only be applicable if the developer configures
  2757. * and accepts the Firebase Dynamic Links terms of condition.
  2758. * The Android package name and iOS bundle ID will be respected only if they
  2759. * are configured in the same Firebase Auth project used.
  2760. */
  2761. sendSignInLinkToEmail(
  2762. email: string,
  2763. actionCodeSettings: firebase.auth.ActionCodeSettings
  2764. ): Promise<void>;
  2765. /**
  2766. * Sends a password reset email to the given email address.
  2767. *
  2768. * To complete the password reset, call
  2769. * {@link firebase.auth.Auth.confirmPasswordReset} with the code supplied in the
  2770. * email sent to the user, along with the new password specified by the user.
  2771. *
  2772. * <h4>Error Codes</h4>
  2773. * <dl>
  2774. * <dt>auth/invalid-email</dt>
  2775. * <dd>Thrown if the email address is not valid.</dd>
  2776. * <dt>auth/missing-android-pkg-name</dt>
  2777. * <dd>An Android package name must be provided if the Android app is required
  2778. * to be installed.</dd>
  2779. * <dt>auth/missing-continue-uri</dt>
  2780. * <dd>A continue URL must be provided in the request.</dd>
  2781. * <dt>auth/missing-ios-bundle-id</dt>
  2782. * <dd>An iOS Bundle ID must be provided if an App Store ID is provided.</dd>
  2783. * <dt>auth/invalid-continue-uri</dt>
  2784. * <dd>The continue URL provided in the request is invalid.</dd>
  2785. * <dt>auth/unauthorized-continue-uri</dt>
  2786. * <dd>The domain of the continue URL is not whitelisted. Whitelist
  2787. * the domain in the Firebase console.</dd>
  2788. * <dt>auth/user-not-found</dt>
  2789. * <dd>Thrown if there is no user corresponding to the email address.</dd>
  2790. * </dl>
  2791. *
  2792. * @example
  2793. * ```javascript
  2794. * var actionCodeSettings = {
  2795. * url: 'https://www.example.com/?email=user@example.com',
  2796. * iOS: {
  2797. * bundleId: 'com.example.ios'
  2798. * },
  2799. * android: {
  2800. * packageName: 'com.example.android',
  2801. * installApp: true,
  2802. * minimumVersion: '12'
  2803. * },
  2804. * handleCodeInApp: true
  2805. * };
  2806. * firebase.auth().sendPasswordResetEmail(
  2807. * 'user@example.com', actionCodeSettings)
  2808. * .then(function() {
  2809. * // Password reset email sent.
  2810. * })
  2811. * .catch(function(error) {
  2812. * // Error occurred. Inspect error.code.
  2813. * });
  2814. * ```
  2815. *
  2816. * @param email The email address with the password to be reset.
  2817. * @param actionCodeSettings The action
  2818. * code settings. If specified, the state/continue URL will be set as the
  2819. * "continueUrl" parameter in the password reset link. The default password
  2820. * reset landing page will use this to display a link to go back to the app
  2821. * if it is installed.
  2822. * If the actionCodeSettings is not specified, no URL is appended to the
  2823. * action URL.
  2824. * The state URL provided must belong to a domain that is whitelisted by the
  2825. * developer in the console. Otherwise an error will be thrown.
  2826. * Mobile app redirects will only be applicable if the developer configures
  2827. * and accepts the Firebase Dynamic Links terms of condition.
  2828. * The Android package name and iOS bundle ID will be respected only if they
  2829. * are configured in the same Firebase Auth project used.
  2830. */
  2831. sendPasswordResetEmail(
  2832. email: string,
  2833. actionCodeSettings?: firebase.auth.ActionCodeSettings | null
  2834. ): Promise<void>;
  2835. /**
  2836. * Changes the current type of persistence on the current Auth instance for the
  2837. * currently saved Auth session and applies this type of persistence for
  2838. * future sign-in requests, including sign-in with redirect requests. This will
  2839. * return a promise that will resolve once the state finishes copying from one
  2840. * type of storage to the other.
  2841. * Calling a sign-in method after changing persistence will wait for that
  2842. * persistence change to complete before applying it on the new Auth state.
  2843. *
  2844. * This makes it easy for a user signing in to specify whether their session
  2845. * should be remembered or not. It also makes it easier to never persist the
  2846. * Auth state for applications that are shared by other users or have sensitive
  2847. * data.
  2848. *
  2849. * The default for web browser apps and React Native apps is 'local' (provided
  2850. * the browser supports this mechanism) whereas it is 'none' for Node.js backend
  2851. * apps.
  2852. *
  2853. * <h4>Error Codes (thrown synchronously)</h4>
  2854. * <dl>
  2855. * <dt>auth/invalid-persistence-type</dt>
  2856. * <dd>Thrown if the specified persistence type is invalid.</dd>
  2857. * <dt>auth/unsupported-persistence-type</dt>
  2858. * <dd>Thrown if the current environment does not support the specified
  2859. * persistence type.</dd>
  2860. * </dl>
  2861. *
  2862. * @example
  2863. * ```javascript
  2864. * firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
  2865. * .then(function() {
  2866. * // Existing and future Auth states are now persisted in the current
  2867. * // session only. Closing the window would clear any existing state even if
  2868. * // a user forgets to sign out.
  2869. * });
  2870. * ```
  2871. */
  2872. setPersistence(persistence: firebase.auth.Auth.Persistence): Promise<void>;
  2873. /**
  2874. * Asynchronously signs in with the given credentials, and returns any available
  2875. * additional user information, such as user name.
  2876. *
  2877. * <h4>Error Codes</h4>
  2878. * <dl>
  2879. * <dt>auth/account-exists-with-different-credential</dt>
  2880. * <dd>Thrown if there already exists an account with the email address
  2881. * asserted by the credential. Resolve this by calling
  2882. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail} and then asking the
  2883. * user to sign in using one of the returned providers. Once the user is
  2884. * signed in, the original credential can be linked to the user with
  2885. * {@link firebase.User.linkWithCredential}.</dd>
  2886. * <dt>auth/invalid-credential</dt>
  2887. * <dd>Thrown if the credential is malformed or has expired.</dd>
  2888. * <dt>auth/operation-not-allowed</dt>
  2889. * <dd>Thrown if the type of account corresponding to the credential
  2890. * is not enabled. Enable the account type in the Firebase Console, under
  2891. * the Auth tab.</dd>
  2892. * <dt>auth/user-disabled</dt>
  2893. * <dd>Thrown if the user corresponding to the given credential has been
  2894. * disabled.</dd>
  2895. * <dt>auth/user-not-found</dt>
  2896. * <dd>Thrown if signing in with a credential from
  2897. * {@link firebase.auth.EmailAuthProvider.credential} and there is no user
  2898. * corresponding to the given email. </dd>
  2899. * <dt>auth/wrong-password</dt>
  2900. * <dd>Thrown if signing in with a credential from
  2901. * {@link firebase.auth.EmailAuthProvider.credential} and the password is
  2902. * invalid for the given email, or if the account corresponding to the email
  2903. * does not have a password set.</dd>
  2904. * <dt>auth/invalid-verification-code</dt>
  2905. * <dd>Thrown if the credential is a
  2906. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  2907. * code of the credential is not valid.</dd>
  2908. * <dt>auth/invalid-verification-id</dt>
  2909. * <dd>Thrown if the credential is a
  2910. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  2911. * ID of the credential is not valid.</dd>
  2912. * </dl>
  2913. *
  2914. * @deprecated
  2915. * This method is deprecated. Use
  2916. * {@link firebase.auth.Auth.signInWithCredential} instead.
  2917. *
  2918. * @example
  2919. * ```javascript
  2920. * firebase.auth().signInAndRetrieveDataWithCredential(credential)
  2921. * .then(function(userCredential) {
  2922. * console.log(userCredential.additionalUserInfo.username);
  2923. * });
  2924. * ```
  2925. * @param credential The auth credential.
  2926. */
  2927. signInAndRetrieveDataWithCredential(
  2928. credential: firebase.auth.AuthCredential
  2929. ): Promise<firebase.auth.UserCredential>;
  2930. /**
  2931. * Asynchronously signs in as an anonymous user.
  2932. *
  2933. *
  2934. * If there is already an anonymous user signed in, that user will be returned;
  2935. * otherwise, a new anonymous user identity will be created and returned.
  2936. *
  2937. * <h4>Error Codes</h4>
  2938. * <dl>
  2939. * <dt>auth/operation-not-allowed</dt>
  2940. * <dd>Thrown if anonymous accounts are not enabled. Enable anonymous accounts
  2941. * in the Firebase Console, under the Auth tab.</dd>
  2942. * </dl>
  2943. *
  2944. * @example
  2945. * ```javascript
  2946. * firebase.auth().signInAnonymously().catch(function(error) {
  2947. * // Handle Errors here.
  2948. * var errorCode = error.code;
  2949. * var errorMessage = error.message;
  2950. *
  2951. * if (errorCode === 'auth/operation-not-allowed') {
  2952. * alert('You must enable Anonymous auth in the Firebase Console.');
  2953. * } else {
  2954. * console.error(error);
  2955. * }
  2956. * });
  2957. * ```
  2958. */
  2959. signInAnonymously(): Promise<firebase.auth.UserCredential>;
  2960. /**
  2961. * Asynchronously signs in with the given credentials.
  2962. *
  2963. * <h4>Error Codes</h4>
  2964. * <dl>
  2965. * <dt>auth/account-exists-with-different-credential</dt>
  2966. * <dd>Thrown if there already exists an account with the email address
  2967. * asserted by the credential. Resolve this by calling
  2968. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail} and then asking the
  2969. * user to sign in using one of the returned providers. Once the user is
  2970. * signed in, the original credential can be linked to the user with
  2971. * {@link firebase.User.linkWithCredential}.</dd>
  2972. * <dt>auth/invalid-credential</dt>
  2973. * <dd>Thrown if the credential is malformed or has expired.</dd>
  2974. * <dt>auth/operation-not-allowed</dt>
  2975. * <dd>Thrown if the type of account corresponding to the credential
  2976. * is not enabled. Enable the account type in the Firebase Console, under
  2977. * the Auth tab.</dd>
  2978. * <dt>auth/user-disabled</dt>
  2979. * <dd>Thrown if the user corresponding to the given credential has been
  2980. * disabled.</dd>
  2981. * <dt>auth/user-not-found</dt>
  2982. * <dd>Thrown if signing in with a credential from
  2983. * {@link firebase.auth.EmailAuthProvider.credential} and there is no user
  2984. * corresponding to the given email. </dd>
  2985. * <dt>auth/wrong-password</dt>
  2986. * <dd>Thrown if signing in with a credential from
  2987. * {@link firebase.auth.EmailAuthProvider.credential} and the password is
  2988. * invalid for the given email, or if the account corresponding to the email
  2989. * does not have a password set.</dd>
  2990. * <dt>auth/invalid-verification-code</dt>
  2991. * <dd>Thrown if the credential is a
  2992. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  2993. * code of the credential is not valid.</dd>
  2994. * <dt>auth/invalid-verification-id</dt>
  2995. * <dd>Thrown if the credential is a
  2996. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  2997. * ID of the credential is not valid.</dd>
  2998. * </dl>
  2999. *
  3000. * @example
  3001. * ```javascript
  3002. * firebase.auth().signInWithCredential(credential).catch(function(error) {
  3003. * // Handle Errors here.
  3004. * var errorCode = error.code;
  3005. * var errorMessage = error.message;
  3006. * // The email of the user's account used.
  3007. * var email = error.email;
  3008. * // The firebase.auth.AuthCredential type that was used.
  3009. * var credential = error.credential;
  3010. * if (errorCode === 'auth/account-exists-with-different-credential') {
  3011. * alert('Email already associated with another account.');
  3012. * // Handle account linking here, if using.
  3013. * } else {
  3014. * console.error(error);
  3015. * }
  3016. * });
  3017. * ```
  3018. *
  3019. * @param credential The auth credential.
  3020. */
  3021. signInWithCredential(
  3022. credential: firebase.auth.AuthCredential
  3023. ): Promise<firebase.auth.UserCredential>;
  3024. /**
  3025. * Asynchronously signs in using a custom token.
  3026. *
  3027. * Custom tokens are used to integrate Firebase Auth with existing auth systems,
  3028. * and must be generated by the auth backend.
  3029. *
  3030. * Fails with an error if the token is invalid, expired, or not accepted by the
  3031. * Firebase Auth service.
  3032. *
  3033. * <h4>Error Codes</h4>
  3034. * <dl>
  3035. * <dt>auth/custom-token-mismatch</dt>
  3036. * <dd>Thrown if the custom token is for a different Firebase App.</dd>
  3037. * <dt>auth/invalid-custom-token</dt>
  3038. * <dd>Thrown if the custom token format is incorrect.</dd>
  3039. * </dl>
  3040. *
  3041. * @example
  3042. * ```javascript
  3043. * firebase.auth().signInWithCustomToken(token).catch(function(error) {
  3044. * // Handle Errors here.
  3045. * var errorCode = error.code;
  3046. * var errorMessage = error.message;
  3047. * if (errorCode === 'auth/invalid-custom-token') {
  3048. * alert('The token you provided is not valid.');
  3049. * } else {
  3050. * console.error(error);
  3051. * }
  3052. * });
  3053. * ```
  3054. *
  3055. * @param token The custom token to sign in with.
  3056. */
  3057. signInWithCustomToken(token: string): Promise<firebase.auth.UserCredential>;
  3058. /**
  3059. * Asynchronously signs in using an email and password.
  3060. *
  3061. * Fails with an error if the email address and password do not match.
  3062. *
  3063. * Note: The user's password is NOT the password used to access the user's email
  3064. * account. The email address serves as a unique identifier for the user, and
  3065. * the password is used to access the user's account in your Firebase project.
  3066. *
  3067. * See also: {@link firebase.auth.Auth.createUserWithEmailAndPassword}.
  3068. *
  3069. * <h4>Error Codes</h4>
  3070. * <dl>
  3071. * <dt>auth/invalid-email</dt>
  3072. * <dd>Thrown if the email address is not valid.</dd>
  3073. * <dt>auth/user-disabled</dt>
  3074. * <dd>Thrown if the user corresponding to the given email has been
  3075. * disabled.</dd>
  3076. * <dt>auth/user-not-found</dt>
  3077. * <dd>Thrown if there is no user corresponding to the given email.</dd>
  3078. * <dt>auth/wrong-password</dt>
  3079. * <dd>Thrown if the password is invalid for the given email, or the account
  3080. * corresponding to the email does not have a password set.</dd>
  3081. * </dl>
  3082. *
  3083. * @example
  3084. * ```javascript
  3085. * firebase.auth().signInWithEmailAndPassword(email, password)
  3086. * .catch(function(error) {
  3087. * // Handle Errors here.
  3088. * var errorCode = error.code;
  3089. * var errorMessage = error.message;
  3090. * if (errorCode === 'auth/wrong-password') {
  3091. * alert('Wrong password.');
  3092. * } else {
  3093. * alert(errorMessage);
  3094. * }
  3095. * console.log(error);
  3096. * });
  3097. * ```
  3098. *
  3099. * @param email The users email address.
  3100. * @param password The users password.
  3101. */
  3102. signInWithEmailAndPassword(
  3103. email: string,
  3104. password: string
  3105. ): Promise<firebase.auth.UserCredential>;
  3106. /**
  3107. * Asynchronously signs in using a phone number. This method sends a code via
  3108. * SMS to the given phone number, and returns a
  3109. * {@link firebase.auth.ConfirmationResult}. After the user provides the code
  3110. * sent to their phone, call {@link firebase.auth.ConfirmationResult.confirm}
  3111. * with the code to sign the user in.
  3112. *
  3113. * For abuse prevention, this method also requires a
  3114. * {@link firebase.auth.ApplicationVerifier}. The Firebase Auth SDK includes
  3115. * a reCAPTCHA-based implementation, {@link firebase.auth.RecaptchaVerifier}.
  3116. *
  3117. * <h4>Error Codes</h4>
  3118. * <dl>
  3119. * <dt>auth/captcha-check-failed</dt>
  3120. * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if
  3121. * this method was called from a non-whitelisted domain.</dd>
  3122. * <dt>auth/invalid-phone-number</dt>
  3123. * <dd>Thrown if the phone number has an invalid format.</dd>
  3124. * <dt>auth/missing-phone-number</dt>
  3125. * <dd>Thrown if the phone number is missing.</dd>
  3126. * <dt>auth/quota-exceeded</dt>
  3127. * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd>
  3128. * <dt>auth/user-disabled</dt>
  3129. * <dd>Thrown if the user corresponding to the given phone number has been
  3130. * disabled.</dd>
  3131. * <dt>auth/operation-not-allowed</dt>
  3132. * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go
  3133. * to the Firebase Console for your project, in the Auth section and the
  3134. * <strong>Sign in Method</strong> tab and configure the provider.</dd>
  3135. * </dl>
  3136. *
  3137. * @example
  3138. * ```javascript
  3139. * // 'recaptcha-container' is the ID of an element in the DOM.
  3140. * var applicationVerifier = new firebase.auth.RecaptchaVerifier(
  3141. * 'recaptcha-container');
  3142. * firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
  3143. * .then(function(confirmationResult) {
  3144. * var verificationCode = window.prompt('Please enter the verification ' +
  3145. * 'code that was sent to your mobile device.');
  3146. * return confirmationResult.confirm(verificationCode);
  3147. * })
  3148. * .catch(function(error) {
  3149. * // Handle Errors here.
  3150. * });
  3151. * ```
  3152. *
  3153. * @param phoneNumber The user's phone number in E.164 format (e.g.
  3154. * +16505550101).
  3155. * @param applicationVerifier
  3156. */
  3157. signInWithPhoneNumber(
  3158. phoneNumber: string,
  3159. applicationVerifier: firebase.auth.ApplicationVerifier
  3160. ): Promise<firebase.auth.ConfirmationResult>;
  3161. /**
  3162. * Asynchronously signs in using an email and sign-in email link. If no link
  3163. * is passed, the link is inferred from the current URL.
  3164. *
  3165. * Fails with an error if the email address is invalid or OTP in email link
  3166. * expires.
  3167. *
  3168. * Note: Confirm the link is a sign-in email link before calling this method
  3169. * {@link firebase.auth.Auth.isSignInWithEmailLink}.
  3170. *
  3171. * <h4>Error Codes</h4>
  3172. * <dl>
  3173. * <dt>auth/expired-action-code</dt>
  3174. * <dd>Thrown if OTP in email link expires.</dd>
  3175. * <dt>auth/invalid-email</dt>
  3176. * <dd>Thrown if the email address is not valid.</dd>
  3177. * <dt>auth/user-disabled</dt>
  3178. * <dd>Thrown if the user corresponding to the given email has been
  3179. * disabled.</dd>
  3180. * </dl>
  3181. *
  3182. * @example
  3183. * ```javascript
  3184. * firebase.auth().signInWithEmailLink(email, emailLink)
  3185. * .catch(function(error) {
  3186. * // Some error occurred, you can inspect the code: error.code
  3187. * // Common errors could be invalid email and invalid or expired OTPs.
  3188. * });
  3189. * ```
  3190. *
  3191. * @param email The email account to sign in with.
  3192. * @param emailLink The optional link which contains the OTP needed
  3193. * to complete the sign in with email link. If not specified, the current
  3194. * URL is used instead.
  3195. */
  3196. signInWithEmailLink(
  3197. email: string,
  3198. emailLink?: string
  3199. ): Promise<firebase.auth.UserCredential>;
  3200. /**
  3201. * Authenticates a Firebase client using a popup-based OAuth authentication
  3202. * flow.
  3203. *
  3204. * If succeeds, returns the signed in user along with the provider's credential.
  3205. * If sign in was unsuccessful, returns an error object containing additional
  3206. * information about the error.
  3207. *
  3208. * <h4>Error Codes</h4>
  3209. * <dl>
  3210. * <dt>auth/account-exists-with-different-credential</dt>
  3211. * <dd>Thrown if there already exists an account with the email address
  3212. * asserted by the credential. Resolve this by calling
  3213. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail} with the error.email
  3214. * and then asking the user to sign in using one of the returned providers.
  3215. * Once the user is signed in, the original credential retrieved from the
  3216. * error.credential can be linked to the user with
  3217. * {@link firebase.User.linkWithCredential} to prevent the user from signing
  3218. * in again to the original provider via popup or redirect. If you are using
  3219. * redirects for sign in, save the credential in session storage and then
  3220. * retrieve on redirect and repopulate the credential using for example
  3221. * {@link firebase.auth.GoogleAuthProvider.credential} depending on the
  3222. * credential provider id and complete the link.</dd>
  3223. * <dt>auth/auth-domain-config-required</dt>
  3224. * <dd>Thrown if authDomain configuration is not provided when calling
  3225. * firebase.initializeApp(). Check Firebase Console for instructions on
  3226. * determining and passing that field.</dd>
  3227. * <dt>auth/cancelled-popup-request</dt>
  3228. * <dd>Thrown if successive popup operations are triggered. Only one popup
  3229. * request is allowed at one time. All the popups would fail with this error
  3230. * except for the last one.</dd>
  3231. * <dt>auth/operation-not-allowed</dt>
  3232. * <dd>Thrown if the type of account corresponding to the credential
  3233. * is not enabled. Enable the account type in the Firebase Console, under
  3234. * the Auth tab.</dd>
  3235. * <dt>auth/operation-not-supported-in-this-environment</dt>
  3236. * <dd>Thrown if this operation is not supported in the environment your
  3237. * application is running on. "location.protocol" must be http or https.
  3238. * </dd>
  3239. * <dt>auth/popup-blocked</dt>
  3240. * <dd>Thrown if the popup was blocked by the browser, typically when this
  3241. * operation is triggered outside of a click handler.</dd>
  3242. * <dt>auth/popup-closed-by-user</dt>
  3243. * <dd>Thrown if the popup window is closed by the user without completing the
  3244. * sign in to the provider.</dd>
  3245. * <dt>auth/unauthorized-domain</dt>
  3246. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  3247. * Firebase project. Edit the list of authorized domains from the Firebase
  3248. * console.</dd>
  3249. * </dl>
  3250. *
  3251. * @webonly
  3252. *
  3253. * @example
  3254. * ```javascript
  3255. * // Creates the provider object.
  3256. * var provider = new firebase.auth.FacebookAuthProvider();
  3257. * // You can add additional scopes to the provider:
  3258. * provider.addScope('email');
  3259. * provider.addScope('user_friends');
  3260. * // Sign in with popup:
  3261. * auth.signInWithPopup(provider).then(function(result) {
  3262. * // The firebase.User instance:
  3263. * var user = result.user;
  3264. * // The Facebook firebase.auth.AuthCredential containing the Facebook
  3265. * // access token:
  3266. * var credential = result.credential;
  3267. * }, function(error) {
  3268. * // The provider's account email, can be used in case of
  3269. * // auth/account-exists-with-different-credential to fetch the providers
  3270. * // linked to the email:
  3271. * var email = error.email;
  3272. * // The provider's credential:
  3273. * var credential = error.credential;
  3274. * // In case of auth/account-exists-with-different-credential error,
  3275. * // you can fetch the providers using this:
  3276. * if (error.code === 'auth/account-exists-with-different-credential') {
  3277. * auth.fetchSignInMethodsForEmail(email).then(function(providers) {
  3278. * // The returned 'providers' is a list of the available providers
  3279. * // linked to the email address. Please refer to the guide for a more
  3280. * // complete explanation on how to recover from this error.
  3281. * });
  3282. * }
  3283. * });
  3284. * ```
  3285. *
  3286. * @param provider The provider to authenticate.
  3287. * The provider has to be an OAuth provider. Non-OAuth providers like {@link
  3288. * firebase.auth.EmailAuthProvider} will throw an error.
  3289. */
  3290. signInWithPopup(
  3291. provider: firebase.auth.AuthProvider
  3292. ): Promise<firebase.auth.UserCredential>;
  3293. /**
  3294. * Authenticates a Firebase client using a full-page redirect flow. To handle
  3295. * the results and errors for this operation, refer to {@link
  3296. * firebase.auth.Auth.getRedirectResult}.
  3297. *
  3298. * <h4>Error Codes</h4>
  3299. * <dl>
  3300. * <dt>auth/auth-domain-config-required</dt>
  3301. * <dd>Thrown if authDomain configuration is not provided when calling
  3302. * firebase.initializeApp(). Check Firebase Console for instructions on
  3303. * determining and passing that field.</dd>
  3304. * <dt>auth/operation-not-supported-in-this-environment</dt>
  3305. * <dd>Thrown if this operation is not supported in the environment your
  3306. * application is running on. "location.protocol" must be http or https.
  3307. * </dd>
  3308. * <dt>auth/unauthorized-domain</dt>
  3309. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  3310. * Firebase project. Edit the list of authorized domains from the Firebase
  3311. * console.</dd>
  3312. * </dl>
  3313. *
  3314. * @webonly
  3315. *
  3316. * @param provider The provider to authenticate.
  3317. * The provider has to be an OAuth provider. Non-OAuth providers like {@link
  3318. * firebase.auth.EmailAuthProvider} will throw an error.
  3319. */
  3320. signInWithRedirect(provider: firebase.auth.AuthProvider): Promise<void>;
  3321. /**
  3322. * Signs out the current user.
  3323. */
  3324. signOut(): Promise<void>;
  3325. /**
  3326. * The current Auth instance's tenant ID. This is a readable/writable
  3327. * property. When you set the tenant ID of an Auth instance, all future
  3328. * sign-in/sign-up operations will pass this tenant ID and sign in or
  3329. * sign up users to the specified tenant project.
  3330. * When set to null, users are signed in to the parent project. By default,
  3331. * this is set to null.
  3332. *
  3333. * @example
  3334. * ```javascript
  3335. * // Set the tenant ID on Auth instance.
  3336. * firebase.auth().tenantId = TENANT_PROJECT_ID;
  3337. *
  3338. * // All future sign-in request now include tenant ID.
  3339. * firebase.auth().signInWithEmailAndPassword(email, password)
  3340. * .then(function(result) {
  3341. * // result.user.tenantId should be ‘TENANT_PROJECT_ID’.
  3342. * }).catch(function(error) {
  3343. * // Handle error.
  3344. * });
  3345. * ```
  3346. */
  3347. tenantId: string | null;
  3348. /**
  3349. * Asynchronously sets the provided user as `currentUser` on the current Auth
  3350. * instance. A new instance copy of the user provided will be made and set as
  3351. * `currentUser`.
  3352. *
  3353. * This will trigger {@link firebase.auth.Auth.onAuthStateChanged} and
  3354. * {@link firebase.auth.Auth.onIdTokenChanged} listeners like other sign in
  3355. * methods.
  3356. *
  3357. * The operation fails with an error if the user to be updated belongs to a
  3358. * different Firebase project.
  3359. *
  3360. * <h4>Error Codes</h4>
  3361. * <dl>
  3362. * <dt>auth/invalid-user-token</dt>
  3363. * <dd>Thrown if the user to be updated belongs to a diffent Firebase
  3364. * project.</dd>
  3365. * <dt>auth/user-token-expired</dt>
  3366. * <dd>Thrown if the token of the user to be updated is expired.</dd>
  3367. * <dt>auth/null-user</dt>
  3368. * <dd>Thrown if the user to be updated is null.</dd>
  3369. * <dt>auth/tenant-id-mismatch</dt>
  3370. * <dd>Thrown if the provided user's tenant ID does not match the
  3371. * underlying Auth instance's configured tenant ID</dd>
  3372. * </dl>
  3373. */
  3374. updateCurrentUser(user: firebase.User | null): Promise<void>;
  3375. /**
  3376. * Sets the current language to the default device/browser preference.
  3377. */
  3378. useDeviceLanguage(): void;
  3379. /**
  3380. * Modify this Auth instance to communicate with the Firebase Auth emulator. This must be
  3381. * called synchronously immediately following the first call to `firebase.auth()`. Do not use
  3382. * with production credentials as emulator traffic is not encrypted.
  3383. *
  3384. * @param url The URL at which the emulator is running (eg, 'http://localhost:9099')
  3385. */
  3386. useEmulator(url: string): void;
  3387. /**
  3388. * Checks a password reset code sent to the user by email or other out-of-band
  3389. * mechanism.
  3390. *
  3391. * Returns the user's email address if valid.
  3392. *
  3393. * <h4>Error Codes</h4>
  3394. * <dl>
  3395. * <dt>auth/expired-action-code</dt>
  3396. * <dd>Thrown if the password reset code has expired.</dd>
  3397. * <dt>auth/invalid-action-code</dt>
  3398. * <dd>Thrown if the password reset code is invalid. This can happen if the code
  3399. * is malformed or has already been used.</dd>
  3400. * <dt>auth/user-disabled</dt>
  3401. * <dd>Thrown if the user corresponding to the given password reset code has
  3402. * been disabled.</dd>
  3403. * <dt>auth/user-not-found</dt>
  3404. * <dd>Thrown if there is no user corresponding to the password reset code. This
  3405. * may have happened if the user was deleted between when the code was
  3406. * issued and when this method was called.</dd>
  3407. * </dl>
  3408. *
  3409. * @param code A verification code sent to the user.
  3410. */
  3411. verifyPasswordResetCode(code: string): Promise<string>;
  3412. }
  3413. /**
  3414. * Interface that represents the credentials returned by an auth provider.
  3415. * Implementations specify the details about each auth provider's credential
  3416. * requirements.
  3417. *
  3418. */
  3419. abstract class AuthCredential {
  3420. /**
  3421. * The authentication provider ID for the credential.
  3422. * For example, 'facebook.com', or 'google.com'.
  3423. */
  3424. providerId: string;
  3425. /**
  3426. * The authentication sign in method for the credential.
  3427. * For example, 'password', or 'emailLink. This corresponds to the sign-in
  3428. * method identifier as returned in
  3429. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  3430. */
  3431. signInMethod: string;
  3432. /**
  3433. * Returns a JSON-serializable representation of this object.
  3434. */
  3435. toJSON(): Object;
  3436. /**
  3437. * Static method to deserialize a JSON representation of an object into an
  3438. * {@link firebase.auth.AuthCredential}. Input can be either Object or the
  3439. * stringified representation of the object. When string is provided,
  3440. * JSON.parse would be called first. If the JSON input does not represent
  3441. * an`AuthCredential`, null is returned.
  3442. * @param json The plain object representation of an
  3443. * AuthCredential.
  3444. */
  3445. static fromJSON(json: Object | string): AuthCredential | null;
  3446. }
  3447. /**
  3448. * Interface that represents the OAuth credentials returned by an OAuth
  3449. * provider. Implementations specify the details about each auth provider's
  3450. * credential requirements.
  3451. *
  3452. */
  3453. class OAuthCredential extends AuthCredential {
  3454. private constructor();
  3455. /**
  3456. * The OAuth ID token associated with the credential if it belongs to an
  3457. * OIDC provider, such as `google.com`.
  3458. */
  3459. idToken?: string;
  3460. /**
  3461. * The OAuth access token associated with the credential if it belongs to
  3462. * an OAuth provider, such as `facebook.com`, `twitter.com`, etc.
  3463. */
  3464. accessToken?: string;
  3465. /**
  3466. * The OAuth access token secret associated with the credential if it
  3467. * belongs to an OAuth 1.0 provider, such as `twitter.com`.
  3468. */
  3469. secret?: string;
  3470. }
  3471. /**
  3472. * Interface that represents an auth provider.
  3473. */
  3474. interface AuthProvider {
  3475. providerId: string;
  3476. }
  3477. /**
  3478. * A result from a phone number sign-in, link, or reauthenticate call.
  3479. */
  3480. interface ConfirmationResult {
  3481. /**
  3482. * Finishes a phone number sign-in, link, or reauthentication, given the code
  3483. * that was sent to the user's mobile device.
  3484. *
  3485. * <h4>Error Codes</h4>
  3486. * <dl>
  3487. * <dt>auth/invalid-verification-code</dt>
  3488. * <dd>Thrown if the verification code is not valid.</dd>
  3489. * <dt>auth/missing-verification-code</dt>
  3490. * <dd>Thrown if the verification code is missing.</dd>
  3491. * </dl>
  3492. */
  3493. confirm(verificationCode: string): Promise<firebase.auth.UserCredential>;
  3494. /**
  3495. * The phone number authentication operation's verification ID. This can be used
  3496. * along with the verification code to initialize a phone auth credential.
  3497. */
  3498. verificationId: string;
  3499. }
  3500. /**
  3501. * Email and password auth provider implementation.
  3502. *
  3503. * To authenticate: {@link firebase.auth.Auth.createUserWithEmailAndPassword}
  3504. * and {@link firebase.auth.Auth.signInWithEmailAndPassword}.
  3505. */
  3506. class EmailAuthProvider extends EmailAuthProvider_Instance {
  3507. static PROVIDER_ID: string;
  3508. /**
  3509. * This corresponds to the sign-in method identifier as returned in
  3510. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  3511. */
  3512. static EMAIL_PASSWORD_SIGN_IN_METHOD: string;
  3513. /**
  3514. * This corresponds to the sign-in method identifier as returned in
  3515. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  3516. */
  3517. static EMAIL_LINK_SIGN_IN_METHOD: string;
  3518. /**
  3519. * @example
  3520. * ```javascript
  3521. * var cred = firebase.auth.EmailAuthProvider.credential(
  3522. * email,
  3523. * password
  3524. * );
  3525. * ```
  3526. *
  3527. * @param email Email address.
  3528. * @param password User account password.
  3529. * @return The auth provider credential.
  3530. */
  3531. static credential(
  3532. email: string,
  3533. password: string
  3534. ): firebase.auth.AuthCredential;
  3535. /**
  3536. * Initialize an `EmailAuthProvider` credential using an email and an email link
  3537. * after a sign in with email link operation.
  3538. *
  3539. * @example
  3540. * ```javascript
  3541. * var cred = firebase.auth.EmailAuthProvider.credentialWithLink(
  3542. * email,
  3543. * emailLink
  3544. * );
  3545. * ```
  3546. *
  3547. * @param email Email address.
  3548. * @param emailLink Sign-in email link.
  3549. * @return The auth provider credential.
  3550. */
  3551. static credentialWithLink(
  3552. email: string,
  3553. emailLink: string
  3554. ): firebase.auth.AuthCredential;
  3555. }
  3556. /**
  3557. * @hidden
  3558. */
  3559. class EmailAuthProvider_Instance implements firebase.auth.AuthProvider {
  3560. providerId: string;
  3561. }
  3562. /**
  3563. * An authentication error.
  3564. * For method-specific error codes, refer to the specific methods in the
  3565. * documentation. For common error codes, check the reference below. Use{@link
  3566. * firebase.auth.Error.code} to get the specific error code. For a detailed
  3567. * message, use {@link firebase.auth.Error.message}.
  3568. * Errors with the code <strong>auth/account-exists-with-different-credential
  3569. * </strong> will have the additional fields <strong>email</strong> and <strong>
  3570. * credential</strong> which are needed to provide a way to resolve these
  3571. * specific errors. Refer to {@link firebase.auth.Auth.signInWithPopup} for more
  3572. * information.
  3573. *
  3574. * <h4>Common Error Codes</h4>
  3575. * <dl>
  3576. * <dt>auth/app-deleted</dt>
  3577. * <dd>Thrown if the instance of FirebaseApp has been deleted.</dd>
  3578. * <dt>auth/app-not-authorized</dt>
  3579. * <dd>Thrown if the app identified by the domain where it's hosted, is not
  3580. * authorized to use Firebase Authentication with the provided API key.
  3581. * Review your key configuration in the Google API console.</dd>
  3582. * <dt>auth/argument-error</dt>
  3583. * <dd>Thrown if a method is called with incorrect arguments.</dd>
  3584. * <dt>auth/invalid-api-key</dt>
  3585. * <dd>Thrown if the provided API key is invalid. Please check that you have
  3586. * copied it correctly from the Firebase Console.</dd>
  3587. * <dt>auth/invalid-user-token</dt>
  3588. * <dd>Thrown if the user's credential is no longer valid. The user must sign in
  3589. * again.</dd>
  3590. * <dt>auth/invalid-tenant-id</dt>
  3591. * <dd>Thrown if the tenant ID provided is invalid.</dd>
  3592. * <dt>auth/network-request-failed</dt>
  3593. * <dd>Thrown if a network error (such as timeout, interrupted connection or
  3594. * unreachable host) has occurred.</dd>
  3595. * <dt>auth/operation-not-allowed</dt>
  3596. * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go
  3597. * to the Firebase Console for your project, in the Auth section and the
  3598. * <strong>Sign in Method</strong> tab and configure the provider.</dd>
  3599. * <dt>auth/requires-recent-login</dt>
  3600. * <dd>Thrown if the user's last sign-in time does not meet the security
  3601. * threshold. Use {@link firebase.User.reauthenticateWithCredential} to
  3602. * resolve. This does not apply if the user is anonymous.</dd>
  3603. * <dt>auth/too-many-requests</dt>
  3604. * <dd>Thrown if requests are blocked from a device due to unusual activity.
  3605. * Trying again after some delay would unblock.</dd>
  3606. * <dt>auth/unauthorized-domain</dt>
  3607. * <dd>Thrown if the app domain is not authorized for OAuth operations for your
  3608. * Firebase project. Edit the list of authorized domains from the Firebase
  3609. * console.</dd>
  3610. * <dt>auth/user-disabled</dt>
  3611. * <dd>Thrown if the user account has been disabled by an administrator.
  3612. * Accounts can be enabled or disabled in the Firebase Console, the Auth
  3613. * section and Users subsection.</dd>
  3614. * <dt>auth/user-token-expired</dt>
  3615. * <dd>Thrown if the user's credential has expired. This could also be thrown if
  3616. * a user has been deleted. Prompting the user to sign in again should
  3617. * resolve this for either case.</dd>
  3618. * <dt>auth/web-storage-unsupported</dt>
  3619. * <dd>Thrown if the browser does not support web storage or if the user
  3620. * disables them.</dd>
  3621. * </dl>
  3622. */
  3623. interface Error {
  3624. name: string;
  3625. /**
  3626. * Unique error code.
  3627. */
  3628. code: string;
  3629. /**
  3630. * Complete error message.
  3631. */
  3632. message: string;
  3633. }
  3634. /**
  3635. * The account conflict error.
  3636. * Refer to {@link firebase.auth.Auth.signInWithPopup} for more information.
  3637. *
  3638. * <h4>Common Error Codes</h4>
  3639. * <dl>
  3640. * <dt>auth/account-exists-with-different-credential</dt>
  3641. * <dd>Thrown if there already exists an account with the email address
  3642. * asserted by the credential. Resolve this by calling
  3643. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail} with the error.email
  3644. * and then asking the user to sign in using one of the returned providers.
  3645. * Once the user is signed in, the original credential retrieved from the
  3646. * error.credential can be linked to the user with
  3647. * {@link firebase.User.linkWithCredential} to prevent the user from signing
  3648. * in again to the original provider via popup or redirect. If you are using
  3649. * redirects for sign in, save the credential in session storage and then
  3650. * retrieve on redirect and repopulate the credential using for example
  3651. * {@link firebase.auth.GoogleAuthProvider.credential} depending on the
  3652. * credential provider id and complete the link.</dd>
  3653. * <dt>auth/credential-already-in-use</dt>
  3654. * <dd>Thrown if the account corresponding to the credential already exists
  3655. * among your users, or is already linked to a Firebase User.
  3656. * For example, this error could be thrown if you are upgrading an anonymous
  3657. * user to a Google user by linking a Google credential to it and the Google
  3658. * credential used is already associated with an existing Firebase Google
  3659. * user.
  3660. * The fields <code>error.email</code>, <code>error.phoneNumber</code>, and
  3661. * <code>error.credential</code> ({@link firebase.auth.AuthCredential})
  3662. * may be provided, depending on the type of credential. You can recover
  3663. * from this error by signing in with <code>error.credential</code> directly
  3664. * via {@link firebase.auth.Auth.signInWithCredential}.</dd>
  3665. * <dt>auth/email-already-in-use</dt>
  3666. * <dd>Thrown if the email corresponding to the credential already exists
  3667. * among your users. When thrown while linking a credential to an existing
  3668. * user, an <code>error.email</code> and <code>error.credential</code>
  3669. * ({@link firebase.auth.AuthCredential}) fields are also provided.
  3670. * You have to link the credential to the existing user with that email if
  3671. * you wish to continue signing in with that credential. To do so, call
  3672. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}, sign in to
  3673. * <code>error.email</code> via one of the providers returned and then
  3674. * {@link firebase.User.linkWithCredential} the original credential to that
  3675. * newly signed in user.</dd>
  3676. * </dl>
  3677. */
  3678. interface AuthError extends firebase.auth.Error {
  3679. /**
  3680. * The {@link firebase.auth.AuthCredential} that can be used to resolve the
  3681. * error.
  3682. */
  3683. credential?: firebase.auth.AuthCredential;
  3684. /**
  3685. * The email of the user's account used for sign-in/linking.
  3686. */
  3687. email?: string;
  3688. /**
  3689. * The phone number of the user's account used for sign-in/linking.
  3690. */
  3691. phoneNumber?: string;
  3692. /**
  3693. * The tenant ID being used for sign-in/linking. If you use
  3694. * {@link firebase.auth.Auth.signInWithRedirect} to sign in, you have to
  3695. * set the tenant ID on Auth instanace again as the tenant ID is not
  3696. * persisted after redirection.
  3697. */
  3698. tenantId?: string;
  3699. }
  3700. /**
  3701. * The error thrown when the user needs to provide a second factor to sign in
  3702. * successfully.
  3703. * The error code for this error is <code>auth/multi-factor-auth-required</code>.
  3704. * This error provides a {@link firebase.auth.MultiFactorResolver} object,
  3705. * which you can use to get the second sign-in factor from the user.
  3706. *
  3707. * @example
  3708. * ```javascript
  3709. * firebase.auth().signInWithEmailAndPassword()
  3710. * .then(function(result) {
  3711. * // User signed in. No 2nd factor challenge is needed.
  3712. * })
  3713. * .catch(function(error) {
  3714. * if (error.code == 'auth/multi-factor-auth-required') {
  3715. * var resolver = error.resolver;
  3716. * var multiFactorHints = resolver.hints;
  3717. * } else {
  3718. * // Handle other errors.
  3719. * }
  3720. * });
  3721. *
  3722. * resolver.resolveSignIn(multiFactorAssertion)
  3723. * .then(function(userCredential) {
  3724. * // User signed in.
  3725. * });
  3726. * ```
  3727. */
  3728. interface MultiFactorError extends firebase.auth.AuthError {
  3729. /**
  3730. * The multi-factor resolver to complete second factor sign-in.
  3731. */
  3732. resolver: firebase.auth.MultiFactorResolver;
  3733. }
  3734. /**
  3735. * Facebook auth provider.
  3736. *
  3737. * @example
  3738. * ```javascript
  3739. * // Sign in using a redirect.
  3740. * firebase.auth().getRedirectResult().then(function(result) {
  3741. * if (result.credential) {
  3742. * // This gives you a Google Access Token.
  3743. * var token = result.credential.accessToken;
  3744. * }
  3745. * var user = result.user;
  3746. * })
  3747. * // Start a sign in process for an unauthenticated user.
  3748. * var provider = new firebase.auth.FacebookAuthProvider();
  3749. * provider.addScope('user_birthday');
  3750. * firebase.auth().signInWithRedirect(provider);
  3751. * ```
  3752. *
  3753. * @example
  3754. * ```javascript
  3755. * // Sign in using a popup.
  3756. * var provider = new firebase.auth.FacebookAuthProvider();
  3757. * provider.addScope('user_birthday');
  3758. * firebase.auth().signInWithPopup(provider).then(function(result) {
  3759. * // This gives you a Facebook Access Token.
  3760. * var token = result.credential.accessToken;
  3761. * // The signed-in user info.
  3762. * var user = result.user;
  3763. * });
  3764. * ```
  3765. *
  3766. * @see {@link firebase.auth.Auth.onAuthStateChanged} to receive sign in state
  3767. * changes.
  3768. */
  3769. class FacebookAuthProvider extends FacebookAuthProvider_Instance {
  3770. static PROVIDER_ID: string;
  3771. /**
  3772. * This corresponds to the sign-in method identifier as returned in
  3773. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  3774. */
  3775. static FACEBOOK_SIGN_IN_METHOD: string;
  3776. /**
  3777. * @example
  3778. * ```javascript
  3779. * var cred = firebase.auth.FacebookAuthProvider.credential(
  3780. * // `event` from the Facebook auth.authResponseChange callback.
  3781. * event.authResponse.accessToken
  3782. * );
  3783. * ```
  3784. *
  3785. * @param token Facebook access token.
  3786. */
  3787. static credential(token: string): firebase.auth.OAuthCredential;
  3788. }
  3789. /**
  3790. * @hidden
  3791. */
  3792. class FacebookAuthProvider_Instance implements firebase.auth.AuthProvider {
  3793. /**
  3794. * @param scope Facebook OAuth scope.
  3795. * @return The provider instance itself.
  3796. */
  3797. addScope(scope: string): firebase.auth.AuthProvider;
  3798. providerId: string;
  3799. /**
  3800. * Sets the OAuth custom parameters to pass in a Facebook OAuth request for
  3801. * popup and redirect sign-in operations.
  3802. * Valid parameters include 'auth_type', 'display' and 'locale'.
  3803. * For a detailed list, check the
  3804. * {@link https://goo.gl/pve4fo Facebook}
  3805. * documentation.
  3806. * Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri',
  3807. * 'scope', 'response_type' and 'state' are not allowed and will be ignored.
  3808. * @param customOAuthParameters The custom OAuth parameters to pass
  3809. * in the OAuth request.
  3810. * @return The provider instance itself.
  3811. */
  3812. setCustomParameters(
  3813. customOAuthParameters: Object
  3814. ): firebase.auth.AuthProvider;
  3815. }
  3816. /**
  3817. * GitHub auth provider.
  3818. *
  3819. * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect
  3820. * directly, or use the signInWithPopup handler:
  3821. *
  3822. * @example
  3823. * ```javascript
  3824. * // Using a redirect.
  3825. * firebase.auth().getRedirectResult().then(function(result) {
  3826. * if (result.credential) {
  3827. * // This gives you a GitHub Access Token.
  3828. * var token = result.credential.accessToken;
  3829. * }
  3830. * var user = result.user;
  3831. * }).catch(function(error) {
  3832. * // Handle Errors here.
  3833. * var errorCode = error.code;
  3834. * var errorMessage = error.message;
  3835. * // The email of the user's account used.
  3836. * var email = error.email;
  3837. * // The firebase.auth.AuthCredential type that was used.
  3838. * var credential = error.credential;
  3839. * if (errorCode === 'auth/account-exists-with-different-credential') {
  3840. * alert('You have signed up with a different provider for that email.');
  3841. * // Handle linking here if your app allows it.
  3842. * } else {
  3843. * console.error(error);
  3844. * }
  3845. * });
  3846. *
  3847. * // Start a sign in process for an unauthenticated user.
  3848. * var provider = new firebase.auth.GithubAuthProvider();
  3849. * provider.addScope('repo');
  3850. * firebase.auth().signInWithRedirect(provider);
  3851. * ```
  3852. *
  3853. * @example
  3854. * ```javascript
  3855. * // With popup.
  3856. * var provider = new firebase.auth.GithubAuthProvider();
  3857. * provider.addScope('repo');
  3858. * firebase.auth().signInWithPopup(provider).then(function(result) {
  3859. * // This gives you a GitHub Access Token.
  3860. * var token = result.credential.accessToken;
  3861. * // The signed-in user info.
  3862. * var user = result.user;
  3863. * }).catch(function(error) {
  3864. * // Handle Errors here.
  3865. * var errorCode = error.code;
  3866. * var errorMessage = error.message;
  3867. * // The email of the user's account used.
  3868. * var email = error.email;
  3869. * // The firebase.auth.AuthCredential type that was used.
  3870. * var credential = error.credential;
  3871. * if (errorCode === 'auth/account-exists-with-different-credential') {
  3872. * alert('You have signed up with a different provider for that email.');
  3873. * // Handle linking here if your app allows it.
  3874. * } else {
  3875. * console.error(error);
  3876. * }
  3877. * });
  3878. * ```
  3879. *
  3880. * @see {@link firebase.auth.Auth.onAuthStateChanged} to receive sign in state
  3881. * changes.
  3882. */
  3883. class GithubAuthProvider extends GithubAuthProvider_Instance {
  3884. static PROVIDER_ID: string;
  3885. /**
  3886. * This corresponds to the sign-in method identifier as returned in
  3887. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  3888. */
  3889. static GITHUB_SIGN_IN_METHOD: string;
  3890. /**
  3891. * @example
  3892. * ```javascript
  3893. * var cred = firebase.auth.GithubAuthProvider.credential(
  3894. * // `event` from the Github auth.authResponseChange callback.
  3895. * event.authResponse.accessToken
  3896. * );
  3897. * ```
  3898. *
  3899. * @param token Github access token.
  3900. * @return {!firebase.auth.OAuthCredential} The auth provider credential.
  3901. */
  3902. static credential(token: string): firebase.auth.OAuthCredential;
  3903. }
  3904. /**
  3905. * @hidden
  3906. */
  3907. class GithubAuthProvider_Instance implements firebase.auth.AuthProvider {
  3908. /**
  3909. * @param scope Github OAuth scope.
  3910. * @return The provider instance itself.
  3911. */
  3912. addScope(scope: string): firebase.auth.AuthProvider;
  3913. providerId: string;
  3914. /**
  3915. * Sets the OAuth custom parameters to pass in a GitHub OAuth request for popup
  3916. * and redirect sign-in operations.
  3917. * Valid parameters include 'allow_signup'.
  3918. * For a detailed list, check the
  3919. * {@link https://developer.github.com/v3/oauth/ GitHub} documentation.
  3920. * Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri',
  3921. * 'scope', 'response_type' and 'state' are not allowed and will be ignored.
  3922. * @param customOAuthParameters The custom OAuth parameters to pass
  3923. * in the OAuth request.
  3924. * @return The provider instance itself.
  3925. */
  3926. setCustomParameters(
  3927. customOAuthParameters: Object
  3928. ): firebase.auth.AuthProvider;
  3929. }
  3930. /**
  3931. * Google auth provider.
  3932. *
  3933. * @example
  3934. * ```javascript
  3935. * // Using a redirect.
  3936. * firebase.auth().getRedirectResult().then(function(result) {
  3937. * if (result.credential) {
  3938. * // This gives you a Google Access Token.
  3939. * var token = result.credential.accessToken;
  3940. * }
  3941. * var user = result.user;
  3942. * });
  3943. *
  3944. * // Start a sign in process for an unauthenticated user.
  3945. * var provider = new firebase.auth.GoogleAuthProvider();
  3946. * provider.addScope('profile');
  3947. * provider.addScope('email');
  3948. * firebase.auth().signInWithRedirect(provider);
  3949. * ```
  3950. *
  3951. * @example
  3952. * ```javascript
  3953. * // Using a popup.
  3954. * var provider = new firebase.auth.GoogleAuthProvider();
  3955. * provider.addScope('profile');
  3956. * provider.addScope('email');
  3957. * firebase.auth().signInWithPopup(provider).then(function(result) {
  3958. * // This gives you a Google Access Token.
  3959. * var token = result.credential.accessToken;
  3960. * // The signed-in user info.
  3961. * var user = result.user;
  3962. * });
  3963. * ```
  3964. *
  3965. * @see {@link firebase.auth.Auth.onAuthStateChanged} to receive sign in state
  3966. * changes.
  3967. */
  3968. class GoogleAuthProvider extends GoogleAuthProvider_Instance {
  3969. static PROVIDER_ID: string;
  3970. /**
  3971. * This corresponds to the sign-in method identifier as returned in
  3972. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  3973. */
  3974. static GOOGLE_SIGN_IN_METHOD: string;
  3975. /**
  3976. * Creates a credential for Google. At least one of ID token and access token
  3977. * is required.
  3978. *
  3979. * @example
  3980. * ```javascript
  3981. * // \`googleUser\` from the onsuccess Google Sign In callback.
  3982. * var credential = firebase.auth.GoogleAuthProvider.credential(
  3983. googleUser.getAuthResponse().id_token);
  3984. * firebase.auth().signInWithCredential(credential)
  3985. * ```
  3986. * @param idToken Google ID token.
  3987. * @param accessToken Google access token.
  3988. * @return The auth provider credential.
  3989. */
  3990. static credential(
  3991. idToken?: string | null,
  3992. accessToken?: string | null
  3993. ): firebase.auth.OAuthCredential;
  3994. }
  3995. /**
  3996. * @hidden
  3997. */
  3998. class GoogleAuthProvider_Instance implements firebase.auth.AuthProvider {
  3999. /**
  4000. * @param scope Google OAuth scope.
  4001. * @return The provider instance itself.
  4002. */
  4003. addScope(scope: string): firebase.auth.AuthProvider;
  4004. providerId: string;
  4005. /**
  4006. * Sets the OAuth custom parameters to pass in a Google OAuth request for popup
  4007. * and redirect sign-in operations.
  4008. * Valid parameters include 'hd', 'hl', 'include_granted_scopes', 'login_hint'
  4009. * and 'prompt'.
  4010. * For a detailed list, check the
  4011. * {@link https://goo.gl/Xo01Jm Google}
  4012. * documentation.
  4013. * Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri',
  4014. * 'scope', 'response_type' and 'state' are not allowed and will be ignored.
  4015. * @param customOAuthParameters The custom OAuth parameters to pass
  4016. * in the OAuth request.
  4017. * @return The provider instance itself.
  4018. */
  4019. setCustomParameters(
  4020. customOAuthParameters: Object
  4021. ): firebase.auth.AuthProvider;
  4022. }
  4023. /**
  4024. * Generic OAuth provider.
  4025. *
  4026. * @example
  4027. * ```javascript
  4028. * // Using a redirect.
  4029. * firebase.auth().getRedirectResult().then(function(result) {
  4030. * if (result.credential) {
  4031. * // This gives you the OAuth Access Token for that provider.
  4032. * var token = result.credential.accessToken;
  4033. * }
  4034. * var user = result.user;
  4035. * });
  4036. *
  4037. * // Start a sign in process for an unauthenticated user.
  4038. * var provider = new firebase.auth.OAuthProvider('google.com');
  4039. * provider.addScope('profile');
  4040. * provider.addScope('email');
  4041. * firebase.auth().signInWithRedirect(provider);
  4042. * ```
  4043. * @example
  4044. * ```javascript
  4045. * // Using a popup.
  4046. * var provider = new firebase.auth.OAuthProvider('google.com');
  4047. * provider.addScope('profile');
  4048. * provider.addScope('email');
  4049. * firebase.auth().signInWithPopup(provider).then(function(result) {
  4050. * // This gives you the OAuth Access Token for that provider.
  4051. * var token = result.credential.accessToken;
  4052. * // The signed-in user info.
  4053. * var user = result.user;
  4054. * });
  4055. * ```
  4056. *
  4057. * @see {@link firebase.auth.Auth.onAuthStateChanged} to receive sign in state
  4058. * changes.
  4059. * @param providerId The associated provider ID, such as `github.com`.
  4060. */
  4061. class OAuthProvider implements firebase.auth.AuthProvider {
  4062. constructor(providerId: string);
  4063. providerId: string;
  4064. /**
  4065. * @param scope Provider OAuth scope to add.
  4066. */
  4067. addScope(scope: string): firebase.auth.AuthProvider;
  4068. /**
  4069. * Creates a Firebase credential from a generic OAuth provider's access token or
  4070. * ID token. The raw nonce is required when an ID token with a nonce field is
  4071. * provided. The SHA-256 hash of the raw nonce must match the nonce field in
  4072. * the ID token.
  4073. *
  4074. * @example
  4075. * ```javascript
  4076. * // `googleUser` from the onsuccess Google Sign In callback.
  4077. * // Initialize a generate OAuth provider with a `google.com` providerId.
  4078. * var provider = new firebase.auth.OAuthProvider('google.com');
  4079. * var credential = provider.credential({
  4080. * idToken: googleUser.getAuthResponse().id_token,
  4081. * });
  4082. * firebase.auth().signInWithCredential(credential)
  4083. * ```
  4084. *
  4085. * @param optionsOrIdToken Either the options object containing
  4086. * the ID token, access token and raw nonce or the ID token string.
  4087. * @param accessToken The OAuth access token.
  4088. */
  4089. credential(
  4090. optionsOrIdToken: firebase.auth.OAuthCredentialOptions | string | null,
  4091. accessToken?: string
  4092. ): firebase.auth.OAuthCredential;
  4093. /**
  4094. * Sets the OAuth custom parameters to pass in an OAuth request for popup
  4095. * and redirect sign-in operations.
  4096. * For a detailed list, check the
  4097. * reserved required OAuth 2.0 parameters such as `client_id`, `redirect_uri`,
  4098. * `scope`, `response_type` and `state` are not allowed and will be ignored.
  4099. * @param customOAuthParameters The custom OAuth parameters to pass
  4100. * in the OAuth request.
  4101. */
  4102. setCustomParameters(
  4103. customOAuthParameters: Object
  4104. ): firebase.auth.AuthProvider;
  4105. }
  4106. class SAMLAuthProvider implements firebase.auth.AuthProvider {
  4107. constructor(providerId: string);
  4108. providerId: string;
  4109. }
  4110. /**
  4111. * Interface representing ID token result obtained from
  4112. * {@link firebase.User.getIdTokenResult}. It contains the ID token JWT string
  4113. * and other helper properties for getting different data associated with the
  4114. * token as well as all the decoded payload claims.
  4115. *
  4116. * Note that these claims are not to be trusted as they are parsed client side.
  4117. * Only server side verification can guarantee the integrity of the token
  4118. * claims.
  4119. */
  4120. interface IdTokenResult {
  4121. /**
  4122. * The Firebase Auth ID token JWT string.
  4123. */
  4124. token: string;
  4125. /**
  4126. * The ID token expiration time formatted as a UTC string.
  4127. */
  4128. expirationTime: string;
  4129. /**
  4130. * The authentication time formatted as a UTC string. This is the time the
  4131. * user authenticated (signed in) and not the time the token was refreshed.
  4132. */
  4133. authTime: string;
  4134. /**
  4135. * The ID token issued at time formatted as a UTC string.
  4136. */
  4137. issuedAtTime: string;
  4138. /**
  4139. * The sign-in provider through which the ID token was obtained (anonymous,
  4140. * custom, phone, password, etc). Note, this does not map to provider IDs.
  4141. */
  4142. signInProvider: string | null;
  4143. /**
  4144. * The type of second factor associated with this session, provided the user
  4145. * was multi-factor authenticated (eg. phone, etc).
  4146. */
  4147. signInSecondFactor: string | null;
  4148. /**
  4149. * The entire payload claims of the ID token including the standard reserved
  4150. * claims as well as the custom claims.
  4151. */
  4152. claims: {
  4153. [key: string]: any;
  4154. };
  4155. }
  4156. /**
  4157. * Defines the options for initializing an
  4158. * {@link firebase.auth.OAuthCredential}. For ID tokens with nonce claim,
  4159. * the raw nonce has to also be provided.
  4160. */
  4161. interface OAuthCredentialOptions {
  4162. /**
  4163. * The OAuth ID token used to initialize the OAuthCredential.
  4164. */
  4165. idToken?: string;
  4166. /**
  4167. * The OAuth access token used to initialize the OAuthCredential.
  4168. */
  4169. accessToken?: string;
  4170. /**
  4171. * The raw nonce associated with the ID token. It is required when an ID token
  4172. * with a nonce field is provided. The SHA-256 hash of the raw nonce must match
  4173. * the nonce field in the ID token.
  4174. */
  4175. rawNonce?: string;
  4176. }
  4177. /**
  4178. * The base class for asserting ownership of a second factor. This is used to
  4179. * facilitate enrollment of a second factor on an existing user
  4180. * or sign-in of a user who already verified the first factor.
  4181. *
  4182. */
  4183. abstract class MultiFactorAssertion {
  4184. /**
  4185. * The identifier of the second factor.
  4186. */
  4187. factorId: string;
  4188. }
  4189. /**
  4190. * The class for asserting ownership of a phone second factor.
  4191. */
  4192. class PhoneMultiFactorAssertion extends firebase.auth.MultiFactorAssertion {
  4193. private constructor();
  4194. }
  4195. /**
  4196. * The class used to initialize {@link firebase.auth.PhoneMultiFactorAssertion}.
  4197. */
  4198. class PhoneMultiFactorGenerator {
  4199. private constructor();
  4200. /**
  4201. * The identifier of the phone second factor: `phone`.
  4202. */
  4203. static FACTOR_ID: string;
  4204. /**
  4205. * Initializes the {@link firebase.auth.PhoneMultiFactorAssertion} to confirm ownership
  4206. * of the phone second factor.
  4207. */
  4208. static assertion(
  4209. phoneAuthCredential: firebase.auth.PhoneAuthCredential
  4210. ): firebase.auth.PhoneMultiFactorAssertion;
  4211. }
  4212. /**
  4213. * A structure containing the information of a second factor entity.
  4214. */
  4215. interface MultiFactorInfo {
  4216. /**
  4217. * The multi-factor enrollment ID.
  4218. */
  4219. uid: string;
  4220. /**
  4221. * The user friendly name of the current second factor.
  4222. */
  4223. displayName?: string | null;
  4224. /**
  4225. * The enrollment date of the second factor formatted as a UTC string.
  4226. */
  4227. enrollmentTime: string;
  4228. /**
  4229. * The identifier of the second factor.
  4230. */
  4231. factorId: string;
  4232. }
  4233. /**
  4234. * The subclass of the MultiFactorInfo interface for phone number second factors.
  4235. * The factorId of this second factor is
  4236. * {@link firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID}.
  4237. */
  4238. interface PhoneMultiFactorInfo extends firebase.auth.MultiFactorInfo {
  4239. /**
  4240. * The phone number associated with the current second factor.
  4241. */
  4242. phoneNumber: string;
  4243. }
  4244. /**
  4245. * The information required to verify the ownership of a phone number. The
  4246. * information that's required depends on whether you are doing single-factor
  4247. * sign-in, multi-factor enrollment or multi-factor sign-in.
  4248. */
  4249. type PhoneInfoOptions =
  4250. | firebase.auth.PhoneSingleFactorInfoOptions
  4251. | firebase.auth.PhoneMultiFactorEnrollInfoOptions
  4252. | firebase.auth.PhoneMultiFactorSignInInfoOptions;
  4253. /**
  4254. * The phone info options for single-factor sign-in. Only phone number is
  4255. * required.
  4256. */
  4257. interface PhoneSingleFactorInfoOptions {
  4258. phoneNumber: string;
  4259. }
  4260. /**
  4261. * The phone info options for multi-factor enrollment. Phone number and
  4262. * multi-factor session are required.
  4263. */
  4264. interface PhoneMultiFactorEnrollInfoOptions {
  4265. phoneNumber: string;
  4266. session: firebase.auth.MultiFactorSession;
  4267. }
  4268. /**
  4269. * The phone info options for multi-factor sign-in. Either multi-factor hint or
  4270. * multi-factor UID and multi-factor session are required.
  4271. */
  4272. interface PhoneMultiFactorSignInInfoOptions {
  4273. multiFactorHint?: firebase.auth.MultiFactorInfo;
  4274. multiFactorUid?: string;
  4275. session: firebase.auth.MultiFactorSession;
  4276. }
  4277. /**
  4278. * The class used to facilitate recovery from
  4279. * {@link firebase.auth.MultiFactorError} when a user needs to provide a second
  4280. * factor to sign in.
  4281. *
  4282. * @example
  4283. * ```javascript
  4284. * firebase.auth().signInWithEmailAndPassword()
  4285. * .then(function(result) {
  4286. * // User signed in. No 2nd factor challenge is needed.
  4287. * })
  4288. * .catch(function(error) {
  4289. * if (error.code == 'auth/multi-factor-auth-required') {
  4290. * var resolver = error.resolver;
  4291. * // Show UI to let user select second factor.
  4292. * var multiFactorHints = resolver.hints;
  4293. * } else {
  4294. * // Handle other errors.
  4295. * }
  4296. * });
  4297. *
  4298. * // The enrolled second factors that can be used to complete
  4299. * // sign-in are returned in the `MultiFactorResolver.hints` list.
  4300. * // UI needs to be presented to allow the user to select a second factor
  4301. * // from that list.
  4302. *
  4303. * var selectedHint = // ; selected from multiFactorHints
  4304. * var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
  4305. * var phoneInfoOptions = {
  4306. * multiFactorHint: selectedHint,
  4307. * session: resolver.session
  4308. * };
  4309. * phoneAuthProvider.verifyPhoneNumber(
  4310. * phoneInfoOptions,
  4311. * appVerifier
  4312. * ).then(function(verificationId) {
  4313. * // store verificationID and show UI to let user enter verification code.
  4314. * });
  4315. *
  4316. * // UI to enter verification code and continue.
  4317. * // Continue button click handler
  4318. * var phoneAuthCredential =
  4319. * firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
  4320. * var multiFactorAssertion =
  4321. * firebase.auth.PhoneMultiFactorGenerator.assertion(phoneAuthCredential);
  4322. * resolver.resolveSignIn(multiFactorAssertion)
  4323. * .then(function(userCredential) {
  4324. * // User signed in.
  4325. * });
  4326. * ```
  4327. */
  4328. class MultiFactorResolver {
  4329. private constructor();
  4330. /**
  4331. * The Auth instance used to sign in with the first factor.
  4332. */
  4333. auth: firebase.auth.Auth;
  4334. /**
  4335. * The session identifier for the current sign-in flow, which can be used
  4336. * to complete the second factor sign-in.
  4337. */
  4338. session: firebase.auth.MultiFactorSession;
  4339. /**
  4340. * The list of hints for the second factors needed to complete the sign-in
  4341. * for the current session.
  4342. */
  4343. hints: firebase.auth.MultiFactorInfo[];
  4344. /**
  4345. * A helper function to help users complete sign in with a second factor
  4346. * using an {@link firebase.auth.MultiFactorAssertion} confirming the user
  4347. * successfully completed the second factor challenge.
  4348. *
  4349. * <h4>Error Codes</h4>
  4350. * <dl>
  4351. * <dt>auth/invalid-verification-code</dt>
  4352. * <dd>Thrown if the verification code is not valid.</dd>
  4353. * <dt>auth/missing-verification-code</dt>
  4354. * <dd>Thrown if the verification code is missing.</dd>
  4355. * <dt>auth/invalid-verification-id</dt>
  4356. * <dd>Thrown if the credential is a
  4357. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  4358. * ID of the credential is not valid.</dd>
  4359. * <dt>auth/missing-verification-id</dt>
  4360. * <dd>Thrown if the verification ID is missing.</dd>
  4361. * <dt>auth/code-expired</dt>
  4362. * <dd>Thrown if the verification code has expired.</dd>
  4363. * <dt>auth/invalid-multi-factor-session</dt>
  4364. * <dd>Thrown if the request does not contain a valid proof of first factor
  4365. * successful sign-in.</dd>
  4366. * <dt>auth/missing-multi-factor-session</dt>
  4367. * <dd>Thrown if The request is missing proof of first factor successful
  4368. * sign-in.</dd>
  4369. * </dl>
  4370. *
  4371. * @param assertion The multi-factor assertion to resolve sign-in with.
  4372. * @return The promise that resolves with the user credential object.
  4373. */
  4374. resolveSignIn(
  4375. assertion: firebase.auth.MultiFactorAssertion
  4376. ): Promise<firebase.auth.UserCredential>;
  4377. }
  4378. /**
  4379. * The multi-factor session object used for enrolling a second factor on a
  4380. * user or helping sign in an enrolled user with a second factor.
  4381. */
  4382. class MultiFactorSession {
  4383. private constructor();
  4384. }
  4385. /**
  4386. * Classes that represents the Phone Auth credentials returned by a
  4387. * {@link firebase.auth.PhoneAuthProvider}.
  4388. *
  4389. */
  4390. class PhoneAuthCredential extends AuthCredential {
  4391. private constructor();
  4392. }
  4393. /**
  4394. * Phone number auth provider.
  4395. *
  4396. * @example
  4397. * ```javascript
  4398. * // 'recaptcha-container' is the ID of an element in the DOM.
  4399. * var applicationVerifier = new firebase.auth.RecaptchaVerifier(
  4400. * 'recaptcha-container');
  4401. * var provider = new firebase.auth.PhoneAuthProvider();
  4402. * provider.verifyPhoneNumber('+16505550101', applicationVerifier)
  4403. * .then(function(verificationId) {
  4404. * var verificationCode = window.prompt('Please enter the verification ' +
  4405. * 'code that was sent to your mobile device.');
  4406. * return firebase.auth.PhoneAuthProvider.credential(verificationId,
  4407. * verificationCode);
  4408. * })
  4409. * .then(function(phoneCredential) {
  4410. * return firebase.auth().signInWithCredential(phoneCredential);
  4411. * });
  4412. * ```
  4413. * @param auth The Firebase Auth instance in which
  4414. * sign-ins should occur. Uses the default Auth instance if unspecified.
  4415. */
  4416. class PhoneAuthProvider extends PhoneAuthProvider_Instance {
  4417. static PROVIDER_ID: string;
  4418. /**
  4419. * This corresponds to the sign-in method identifier as returned in
  4420. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  4421. */
  4422. static PHONE_SIGN_IN_METHOD: string;
  4423. /**
  4424. * Creates a phone auth credential, given the verification ID from
  4425. * {@link firebase.auth.PhoneAuthProvider.verifyPhoneNumber} and the code
  4426. * that was sent to the user's mobile device.
  4427. *
  4428. * <h4>Error Codes</h4>
  4429. * <dl>
  4430. * <dt>auth/missing-verification-code</dt>
  4431. * <dd>Thrown if the verification code is missing.</dd>
  4432. * <dt>auth/missing-verification-id</dt>
  4433. * <dd>Thrown if the verification ID is missing.</dd>
  4434. * </dl>
  4435. *
  4436. * @param verificationId The verification ID returned from
  4437. * {@link firebase.auth.PhoneAuthProvider.verifyPhoneNumber}.
  4438. * @param verificationCode The verification code sent to the user's
  4439. * mobile device.
  4440. * @return The auth provider credential.
  4441. */
  4442. static credential(
  4443. verificationId: string,
  4444. verificationCode: string
  4445. ): firebase.auth.AuthCredential;
  4446. }
  4447. /**
  4448. * @hidden
  4449. */
  4450. class PhoneAuthProvider_Instance implements firebase.auth.AuthProvider {
  4451. constructor(auth?: firebase.auth.Auth | null);
  4452. providerId: string;
  4453. /**
  4454. * Starts a phone number authentication flow by sending a verification code to
  4455. * the given phone number. Returns an ID that can be passed to
  4456. * {@link firebase.auth.PhoneAuthProvider.credential} to identify this flow.
  4457. *
  4458. * For abuse prevention, this method also requires a
  4459. * {@link firebase.auth.ApplicationVerifier}. The Firebase Auth SDK includes
  4460. * a reCAPTCHA-based implementation, {@link firebase.auth.RecaptchaVerifier}.
  4461. *
  4462. * <h4>Error Codes</h4>
  4463. * <dl>
  4464. * <dt>auth/captcha-check-failed</dt>
  4465. * <dd>Thrown if the reCAPTCHA response token was invalid, expired, or if
  4466. * this method was called from a non-whitelisted domain.</dd>
  4467. * <dt>auth/invalid-phone-number</dt>
  4468. * <dd>Thrown if the phone number has an invalid format.</dd>
  4469. * <dt>auth/missing-phone-number</dt>
  4470. * <dd>Thrown if the phone number is missing.</dd>
  4471. * <dt>auth/quota-exceeded</dt>
  4472. * <dd>Thrown if the SMS quota for the Firebase project has been exceeded.</dd>
  4473. * <dt>auth/user-disabled</dt>
  4474. * <dd>Thrown if the user corresponding to the given phone number has been
  4475. * disabled.</dd>
  4476. * <dt>auth/maximum-second-factor-count-exceeded</dt>
  4477. * <dd>Thrown if The maximum allowed number of second factors on a user
  4478. * has been exceeded.</dd>
  4479. * <dt>auth/second-factor-already-in-use</dt>
  4480. * <dd>Thrown if the second factor is already enrolled on this account.</dd>
  4481. * <dt>auth/unsupported-first-factor</dt>
  4482. * <dd>Thrown if the first factor being used to sign in is not supported.</dd>
  4483. * <dt>auth/unverified-email</dt>
  4484. * <dd>Thrown if the email of the account is not verified.</dd>
  4485. * </dl>
  4486. *
  4487. * @param phoneInfoOptions The user's {@link firebase.auth.PhoneInfoOptions}.
  4488. * The phone number should be in E.164 format (e.g. +16505550101).
  4489. * @param applicationVerifier
  4490. * @return A Promise for the verification ID.
  4491. */
  4492. verifyPhoneNumber(
  4493. phoneInfoOptions: firebase.auth.PhoneInfoOptions | string,
  4494. applicationVerifier: firebase.auth.ApplicationVerifier
  4495. ): Promise<string>;
  4496. }
  4497. /**
  4498. * An {@link https://www.google.com/recaptcha/ reCAPTCHA}-based application
  4499. * verifier.
  4500. *
  4501. * @webonly
  4502. *
  4503. * @param container The reCAPTCHA container parameter. This
  4504. * has different meaning depending on whether the reCAPTCHA is hidden or
  4505. * visible. For a visible reCAPTCHA the container must be empty. If a string
  4506. * is used, it has to correspond to an element ID. The corresponding element
  4507. * must also must be in the DOM at the time of initialization.
  4508. * @param parameters The optional reCAPTCHA parameters. Check the
  4509. * reCAPTCHA docs for a comprehensive list. All parameters are accepted
  4510. * except for the sitekey. Firebase Auth backend provisions a reCAPTCHA for
  4511. * each project and will configure this upon rendering. For an invisible
  4512. * reCAPTCHA, a size key must have the value 'invisible'.
  4513. * @param app The corresponding Firebase app. If none is
  4514. * provided, the default Firebase App instance is used. A Firebase App
  4515. * instance must be initialized with an API key, otherwise an error will be
  4516. * thrown.
  4517. */
  4518. class RecaptchaVerifier extends RecaptchaVerifier_Instance {}
  4519. /**
  4520. * @webonly
  4521. * @hidden
  4522. */
  4523. class RecaptchaVerifier_Instance
  4524. implements firebase.auth.ApplicationVerifier
  4525. {
  4526. constructor(
  4527. container: any | string,
  4528. parameters?: Object | null,
  4529. app?: firebase.app.App | null
  4530. );
  4531. /**
  4532. * Clears the reCAPTCHA widget from the page and destroys the current instance.
  4533. */
  4534. clear(): void;
  4535. /**
  4536. * Renders the reCAPTCHA widget on the page.
  4537. * @return A Promise that resolves with the
  4538. * reCAPTCHA widget ID.
  4539. */
  4540. render(): Promise<number>;
  4541. /**
  4542. * The application verifier type. For a reCAPTCHA verifier, this is 'recaptcha'.
  4543. */
  4544. type: string;
  4545. /**
  4546. * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA
  4547. * token.
  4548. * @return A Promise for the reCAPTCHA token.
  4549. */
  4550. verify(): Promise<string>;
  4551. }
  4552. /**
  4553. * Twitter auth provider.
  4554. *
  4555. * @example
  4556. * ```javascript
  4557. * // Using a redirect.
  4558. * firebase.auth().getRedirectResult().then(function(result) {
  4559. * if (result.credential) {
  4560. * // For accessing the Twitter API.
  4561. * var token = result.credential.accessToken;
  4562. * var secret = result.credential.secret;
  4563. * }
  4564. * var user = result.user;
  4565. * });
  4566. *
  4567. * // Start a sign in process for an unauthenticated user.
  4568. * var provider = new firebase.auth.TwitterAuthProvider();
  4569. * firebase.auth().signInWithRedirect(provider);
  4570. * ```
  4571. * @example
  4572. * ```javascript
  4573. * // Using a popup.
  4574. * var provider = new firebase.auth.TwitterAuthProvider();
  4575. * firebase.auth().signInWithPopup(provider).then(function(result) {
  4576. * // For accessing the Twitter API.
  4577. * var token = result.credential.accessToken;
  4578. * var secret = result.credential.secret;
  4579. * // The signed-in user info.
  4580. * var user = result.user;
  4581. * });
  4582. * ```
  4583. *
  4584. * @see {@link firebase.auth.Auth.onAuthStateChanged} to receive sign in state
  4585. * changes.
  4586. */
  4587. class TwitterAuthProvider extends TwitterAuthProvider_Instance {
  4588. static PROVIDER_ID: string;
  4589. /**
  4590. * This corresponds to the sign-in method identifier as returned in
  4591. * {@link firebase.auth.Auth.fetchSignInMethodsForEmail}.
  4592. *
  4593. */
  4594. static TWITTER_SIGN_IN_METHOD: string;
  4595. /**
  4596. * @param token Twitter access token.
  4597. * @param secret Twitter secret.
  4598. * @return The auth provider credential.
  4599. */
  4600. static credential(
  4601. token: string,
  4602. secret: string
  4603. ): firebase.auth.OAuthCredential;
  4604. }
  4605. /**
  4606. * @hidden
  4607. */
  4608. class TwitterAuthProvider_Instance implements firebase.auth.AuthProvider {
  4609. providerId: string;
  4610. /**
  4611. * Sets the OAuth custom parameters to pass in a Twitter OAuth request for popup
  4612. * and redirect sign-in operations.
  4613. * Valid parameters include 'lang'.
  4614. * Reserved required OAuth 1.0 parameters such as 'oauth_consumer_key',
  4615. * 'oauth_token', 'oauth_signature', etc are not allowed and will be ignored.
  4616. * @param customOAuthParameters The custom OAuth parameters to pass
  4617. * in the OAuth request.
  4618. * @return The provider instance itself.
  4619. */
  4620. setCustomParameters(
  4621. customOAuthParameters: Object
  4622. ): firebase.auth.AuthProvider;
  4623. }
  4624. /**
  4625. * A structure containing a User, an AuthCredential, the operationType, and
  4626. * any additional user information that was returned from the identity provider.
  4627. * operationType could be 'signIn' for a sign-in operation, 'link' for a linking
  4628. * operation and 'reauthenticate' for a reauthentication operation.
  4629. */
  4630. type UserCredential = {
  4631. additionalUserInfo?: firebase.auth.AdditionalUserInfo | null;
  4632. credential: firebase.auth.AuthCredential | null;
  4633. operationType?: string | null;
  4634. user: firebase.User | null;
  4635. };
  4636. /**
  4637. * Interface representing a user's metadata.
  4638. */
  4639. interface UserMetadata {
  4640. creationTime?: string;
  4641. lastSignInTime?: string;
  4642. }
  4643. }
  4644. /**
  4645. * @webonly
  4646. */
  4647. declare namespace firebase.analytics {
  4648. /**
  4649. * The Firebase Analytics service interface.
  4650. *
  4651. * Do not call this constructor directly. Instead, use
  4652. * {@link firebase.analytics `firebase.analytics()`}.
  4653. */
  4654. export interface Analytics {
  4655. /**
  4656. * The {@link firebase.app.App app} associated with the `Analytics` service
  4657. * instance.
  4658. *
  4659. * @example
  4660. * ```javascript
  4661. * var app = analytics.app;
  4662. * ```
  4663. */
  4664. app: firebase.app.App;
  4665. /**
  4666. * Sends analytics event with given `eventParams`. This method
  4667. * automatically associates this logged event with this Firebase web
  4668. * app instance on this device.
  4669. * List of recommended event parameters can be found in
  4670. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4671. * | the GA4 reference documentation}.
  4672. */
  4673. logEvent(
  4674. eventName: 'add_payment_info',
  4675. eventParams?: {
  4676. coupon?: EventParams['coupon'];
  4677. currency?: EventParams['currency'];
  4678. items?: EventParams['items'];
  4679. payment_type?: EventParams['payment_type'];
  4680. value?: EventParams['value'];
  4681. [key: string]: any;
  4682. },
  4683. options?: firebase.analytics.AnalyticsCallOptions
  4684. ): void;
  4685. /**
  4686. * Sends analytics event with given `eventParams`. This method
  4687. * automatically associates this logged event with this Firebase web
  4688. * app instance on this device.
  4689. * List of recommended event parameters can be found in
  4690. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4691. * | the GA4 reference documentation}.
  4692. */
  4693. logEvent(
  4694. eventName: 'add_shipping_info',
  4695. eventParams?: {
  4696. coupon?: EventParams['coupon'];
  4697. currency?: EventParams['currency'];
  4698. items?: EventParams['items'];
  4699. shipping_tier?: EventParams['shipping_tier'];
  4700. value?: EventParams['value'];
  4701. [key: string]: any;
  4702. },
  4703. options?: firebase.analytics.AnalyticsCallOptions
  4704. ): void;
  4705. /**
  4706. * Sends analytics event with given `eventParams`. This method
  4707. * automatically associates this logged event with this Firebase web
  4708. * app instance on this device.
  4709. * List of recommended event parameters can be found in
  4710. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4711. * | the GA4 reference documentation}.
  4712. */
  4713. logEvent(
  4714. eventName: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart',
  4715. eventParams?: {
  4716. currency?: EventParams['currency'];
  4717. value?: EventParams['value'];
  4718. items?: EventParams['items'];
  4719. [key: string]: any;
  4720. },
  4721. options?: firebase.analytics.AnalyticsCallOptions
  4722. ): void;
  4723. /**
  4724. * Sends analytics event with given `eventParams`. This method
  4725. * automatically associates this logged event with this Firebase web
  4726. * app instance on this device.
  4727. * List of recommended event parameters can be found in
  4728. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4729. * | the GA4 reference documentation}.
  4730. */
  4731. logEvent(
  4732. eventName: 'begin_checkout',
  4733. eventParams?: {
  4734. currency?: EventParams['currency'];
  4735. coupon?: EventParams['coupon'];
  4736. value?: EventParams['value'];
  4737. items?: EventParams['items'];
  4738. [key: string]: any;
  4739. },
  4740. options?: firebase.analytics.AnalyticsCallOptions
  4741. ): void;
  4742. /**
  4743. * Sends analytics event with given `eventParams`. This method
  4744. * automatically associates this logged event with this Firebase web
  4745. * app instance on this device.
  4746. * List of recommended event parameters can be found in
  4747. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4748. * | the GA4 reference documentation}.
  4749. */
  4750. logEvent(
  4751. eventName: 'checkout_progress',
  4752. eventParams?: {
  4753. currency?: EventParams['currency'];
  4754. coupon?: EventParams['coupon'];
  4755. value?: EventParams['value'];
  4756. items?: EventParams['items'];
  4757. checkout_step?: EventParams['checkout_step'];
  4758. checkout_option?: EventParams['checkout_option'];
  4759. [key: string]: any;
  4760. },
  4761. options?: firebase.analytics.AnalyticsCallOptions
  4762. ): void;
  4763. /**
  4764. * Sends analytics event with given `eventParams`. This method
  4765. * automatically associates this logged event with this Firebase web
  4766. * app instance on this device.
  4767. * See
  4768. * {@link https://developers.google.com/analytics/devguides/collection/ga4/exceptions
  4769. * | Measure exceptions}.
  4770. */
  4771. logEvent(
  4772. eventName: 'exception',
  4773. eventParams?: {
  4774. description?: EventParams['description'];
  4775. fatal?: EventParams['fatal'];
  4776. [key: string]: any;
  4777. },
  4778. options?: firebase.analytics.AnalyticsCallOptions
  4779. ): void;
  4780. /**
  4781. * Sends analytics event with given `eventParams`. This method
  4782. * automatically associates this logged event with this Firebase web
  4783. * app instance on this device.
  4784. * List of recommended event parameters can be found in
  4785. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4786. * | the GA4 reference documentation}.
  4787. */
  4788. logEvent(
  4789. eventName: 'generate_lead',
  4790. eventParams?: {
  4791. value?: EventParams['value'];
  4792. currency?: EventParams['currency'];
  4793. [key: string]: any;
  4794. },
  4795. options?: firebase.analytics.AnalyticsCallOptions
  4796. ): void;
  4797. /**
  4798. * Sends analytics event with given `eventParams`. This method
  4799. * automatically associates this logged event with this Firebase web
  4800. * app instance on this device.
  4801. * List of recommended event parameters can be found in
  4802. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4803. * | the GA4 reference documentation}.
  4804. */
  4805. logEvent(
  4806. eventName: 'login',
  4807. eventParams?: {
  4808. method?: EventParams['method'];
  4809. [key: string]: any;
  4810. },
  4811. options?: firebase.analytics.AnalyticsCallOptions
  4812. ): void;
  4813. /**
  4814. * Sends analytics event with given `eventParams`. This method
  4815. * automatically associates this logged event with this Firebase web
  4816. * app instance on this device.
  4817. * See
  4818. * {@link https://developers.google.com/analytics/devguides/collection/ga4/page-view
  4819. * | Page views}.
  4820. */
  4821. logEvent(
  4822. eventName: 'page_view',
  4823. eventParams?: {
  4824. page_title?: string;
  4825. page_location?: string;
  4826. page_path?: string;
  4827. [key: string]: any;
  4828. },
  4829. options?: firebase.analytics.AnalyticsCallOptions
  4830. ): void;
  4831. /**
  4832. * Sends analytics event with given `eventParams`. This method
  4833. * automatically associates this logged event with this Firebase web
  4834. * app instance on this device.
  4835. * List of recommended event parameters can be found in
  4836. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4837. * | the GA4 reference documentation}.
  4838. */
  4839. logEvent(
  4840. eventName: 'purchase' | 'refund',
  4841. eventParams?: {
  4842. value?: EventParams['value'];
  4843. currency?: EventParams['currency'];
  4844. transaction_id: EventParams['transaction_id'];
  4845. tax?: EventParams['tax'];
  4846. shipping?: EventParams['shipping'];
  4847. items?: EventParams['items'];
  4848. coupon?: EventParams['coupon'];
  4849. affiliation?: EventParams['affiliation'];
  4850. [key: string]: any;
  4851. },
  4852. options?: firebase.analytics.AnalyticsCallOptions
  4853. ): void;
  4854. /**
  4855. * Sends analytics event with given `eventParams`. This method
  4856. * automatically associates this logged event with this Firebase web
  4857. * app instance on this device.
  4858. * See {@link https://firebase.google.com/docs/analytics/screenviews
  4859. * | Track Screenviews}.
  4860. */
  4861. logEvent(
  4862. eventName: 'screen_view',
  4863. eventParams?: {
  4864. firebase_screen: EventParams['firebase_screen'];
  4865. firebase_screen_class: EventParams['firebase_screen_class'];
  4866. [key: string]: any;
  4867. },
  4868. options?: firebase.analytics.AnalyticsCallOptions
  4869. ): void;
  4870. /**
  4871. * Sends analytics event with given `eventParams`. This method
  4872. * automatically associates this logged event with this Firebase web
  4873. * app instance on this device.
  4874. * List of recommended event parameters can be found in
  4875. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4876. * | the GA4 reference documentation}.
  4877. */
  4878. logEvent(
  4879. eventName: 'search' | 'view_search_results',
  4880. eventParams?: {
  4881. search_term?: EventParams['search_term'];
  4882. [key: string]: any;
  4883. },
  4884. options?: firebase.analytics.AnalyticsCallOptions
  4885. ): void;
  4886. /**
  4887. * Sends analytics event with given `eventParams`. This method
  4888. * automatically associates this logged event with this Firebase web
  4889. * app instance on this device.
  4890. * List of recommended event parameters can be found in
  4891. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4892. * | the GA4 reference documentation}.
  4893. */
  4894. logEvent(
  4895. eventName: 'select_content',
  4896. eventParams?: {
  4897. content_type?: EventParams['content_type'];
  4898. item_id?: EventParams['item_id'];
  4899. [key: string]: any;
  4900. },
  4901. options?: firebase.analytics.AnalyticsCallOptions
  4902. ): void;
  4903. /**
  4904. * Sends analytics event with given `eventParams`. This method
  4905. * automatically associates this logged event with this Firebase web
  4906. * app instance on this device.
  4907. * List of recommended event parameters can be found in
  4908. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4909. * | the GA4 reference documentation}.
  4910. */
  4911. logEvent(
  4912. eventName: 'select_item',
  4913. eventParams?: {
  4914. items?: EventParams['items'];
  4915. item_list_name?: EventParams['item_list_name'];
  4916. item_list_id?: EventParams['item_list_id'];
  4917. [key: string]: any;
  4918. },
  4919. options?: firebase.analytics.AnalyticsCallOptions
  4920. ): void;
  4921. /**
  4922. * Sends analytics event with given `eventParams`. This method
  4923. * automatically associates this logged event with this Firebase web
  4924. * app instance on this device.
  4925. * List of recommended event parameters can be found in
  4926. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4927. * | the GA4 reference documentation}.
  4928. */
  4929. logEvent(
  4930. eventName: 'select_promotion' | 'view_promotion',
  4931. eventParams?: {
  4932. items?: EventParams['items'];
  4933. promotion_id?: EventParams['promotion_id'];
  4934. promotion_name?: EventParams['promotion_name'];
  4935. [key: string]: any;
  4936. },
  4937. options?: firebase.analytics.AnalyticsCallOptions
  4938. ): void;
  4939. /**
  4940. * Sends analytics event with given `eventParams`. This method
  4941. * automatically associates this logged event with this Firebase web
  4942. * app instance on this device.
  4943. * List of recommended event parameters can be found in
  4944. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4945. * | the GA4 reference documentation}.
  4946. */
  4947. logEvent(
  4948. eventName: 'set_checkout_option',
  4949. eventParams?: {
  4950. checkout_step?: EventParams['checkout_step'];
  4951. checkout_option?: EventParams['checkout_option'];
  4952. [key: string]: any;
  4953. },
  4954. options?: firebase.analytics.AnalyticsCallOptions
  4955. ): void;
  4956. /**
  4957. * Sends analytics event with given `eventParams`. This method
  4958. * automatically associates this logged event with this Firebase web
  4959. * app instance on this device.
  4960. * List of recommended event parameters can be found in
  4961. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4962. * | the GA4 reference documentation}.
  4963. */
  4964. logEvent(
  4965. eventName: 'share',
  4966. eventParams?: {
  4967. method?: EventParams['method'];
  4968. content_type?: EventParams['content_type'];
  4969. item_id?: EventParams['item_id'];
  4970. [key: string]: any;
  4971. },
  4972. options?: firebase.analytics.AnalyticsCallOptions
  4973. ): void;
  4974. /**
  4975. * Sends analytics event with given `eventParams`. This method
  4976. * automatically associates this logged event with this Firebase web
  4977. * app instance on this device.
  4978. * List of recommended event parameters can be found in
  4979. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4980. * | the GA4 reference documentation}.
  4981. */
  4982. logEvent(
  4983. eventName: 'sign_up',
  4984. eventParams?: {
  4985. method?: EventParams['method'];
  4986. [key: string]: any;
  4987. },
  4988. options?: firebase.analytics.AnalyticsCallOptions
  4989. ): void;
  4990. /**
  4991. * Sends analytics event with given `eventParams`. This method
  4992. * automatically associates this logged event with this Firebase web
  4993. * app instance on this device.
  4994. * List of recommended event parameters can be found in
  4995. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  4996. * | the GA4 reference documentation}.
  4997. */
  4998. logEvent(
  4999. eventName: 'timing_complete',
  5000. eventParams?: {
  5001. name: string;
  5002. value: number;
  5003. event_category?: string;
  5004. event_label?: string;
  5005. [key: string]: any;
  5006. },
  5007. options?: firebase.analytics.AnalyticsCallOptions
  5008. ): void;
  5009. /**
  5010. * Sends analytics event with given `eventParams`. This method
  5011. * automatically associates this logged event with this Firebase web
  5012. * app instance on this device.
  5013. * List of recommended event parameters can be found in
  5014. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  5015. * | the GA4 reference documentation}.
  5016. */
  5017. logEvent(
  5018. eventName: 'view_cart' | 'view_item',
  5019. eventParams?: {
  5020. currency?: EventParams['currency'];
  5021. items?: EventParams['items'];
  5022. value?: EventParams['value'];
  5023. [key: string]: any;
  5024. },
  5025. options?: firebase.analytics.AnalyticsCallOptions
  5026. ): void;
  5027. /**
  5028. * Sends analytics event with given `eventParams`. This method
  5029. * automatically associates this logged event with this Firebase web
  5030. * app instance on this device.
  5031. * List of recommended event parameters can be found in
  5032. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  5033. * | the GA4 reference documentation}.
  5034. */
  5035. logEvent(
  5036. eventName: 'view_item_list',
  5037. eventParams?: {
  5038. items?: EventParams['items'];
  5039. item_list_name?: EventParams['item_list_name'];
  5040. item_list_id?: EventParams['item_list_id'];
  5041. [key: string]: any;
  5042. },
  5043. options?: firebase.analytics.AnalyticsCallOptions
  5044. ): void;
  5045. /**
  5046. * Sends analytics event with given `eventParams`. This method
  5047. * automatically associates this logged event with this Firebase web
  5048. * app instance on this device.
  5049. * List of recommended event parameters can be found in
  5050. * {@link https://developers.google.com/gtagjs/reference/ga4-events
  5051. * | the GA4 reference documentation}.
  5052. */
  5053. logEvent<T extends string>(
  5054. eventName: CustomEventName<T>,
  5055. eventParams?: { [key: string]: any },
  5056. options?: firebase.analytics.AnalyticsCallOptions
  5057. ): void;
  5058. /**
  5059. * Use gtag 'config' command to set 'screen_name'.
  5060. *
  5061. * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.
  5062. * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.
  5063. */
  5064. setCurrentScreen(
  5065. screenName: string,
  5066. options?: firebase.analytics.AnalyticsCallOptions
  5067. ): void;
  5068. /**
  5069. * Use gtag 'config' command to set 'user_id'.
  5070. */
  5071. setUserId(
  5072. id: string,
  5073. options?: firebase.analytics.AnalyticsCallOptions
  5074. ): void;
  5075. /**
  5076. * Use gtag 'config' command to set all params specified.
  5077. */
  5078. setUserProperties(
  5079. properties: firebase.analytics.CustomParams,
  5080. options?: firebase.analytics.AnalyticsCallOptions
  5081. ): void;
  5082. /**
  5083. * Sets whether analytics collection is enabled for this app on this device.
  5084. * window['ga-disable-analyticsId'] = true;
  5085. */
  5086. setAnalyticsCollectionEnabled(enabled: boolean): void;
  5087. }
  5088. export type CustomEventName<T> = T extends EventNameString ? never : T;
  5089. /**
  5090. * Additional options that can be passed to Firebase Analytics method
  5091. * calls such as `logEvent`, `setCurrentScreen`, etc.
  5092. */
  5093. export interface AnalyticsCallOptions {
  5094. /**
  5095. * If true, this config or event call applies globally to all
  5096. * analytics properties on the page.
  5097. */
  5098. global: boolean;
  5099. }
  5100. /**
  5101. * Specifies custom options for your Firebase Analytics instance.
  5102. * You must set these before initializing `firebase.analytics()`.
  5103. */
  5104. export interface SettingsOptions {
  5105. /** Sets custom name for `gtag` function. */
  5106. gtagName?: string;
  5107. /** Sets custom name for `dataLayer` array used by gtag. */
  5108. dataLayerName?: string;
  5109. }
  5110. /**
  5111. * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.
  5112. * Intended to be used if `gtag.js` script has been installed on
  5113. * this page independently of Firebase Analytics, and is using non-default
  5114. * names for either the `gtag` function or for `dataLayer`.
  5115. * Must be called before calling `firebase.analytics()` or it won't
  5116. * have any effect.
  5117. */
  5118. export function settings(settings: firebase.analytics.SettingsOptions): void;
  5119. /**
  5120. * Standard gtag.js control parameters.
  5121. * For more information, see
  5122. * {@link https://developers.google.com/gtagjs/reference/parameter
  5123. * the gtag.js documentation on parameters}.
  5124. */
  5125. export interface ControlParams {
  5126. groups?: string | string[];
  5127. send_to?: string | string[];
  5128. event_callback?: () => void;
  5129. event_timeout?: number;
  5130. }
  5131. /**
  5132. * Standard gtag.js event parameters.
  5133. * For more information, see
  5134. * {@link https://developers.google.com/gtagjs/reference/parameter
  5135. * the gtag.js documentation on parameters}.
  5136. */
  5137. export interface EventParams {
  5138. checkout_option?: string;
  5139. checkout_step?: number;
  5140. item_id?: string;
  5141. content_type?: string;
  5142. coupon?: string;
  5143. currency?: string;
  5144. description?: string;
  5145. fatal?: boolean;
  5146. items?: Item[];
  5147. method?: string;
  5148. number?: string;
  5149. promotions?: Promotion[];
  5150. screen_name?: string;
  5151. /**
  5152. * Firebase-specific. Use to log a `screen_name` to Firebase Analytics.
  5153. */
  5154. firebase_screen?: string;
  5155. /**
  5156. * Firebase-specific. Use to log a `screen_class` to Firebase Analytics.
  5157. */
  5158. firebase_screen_class?: string;
  5159. search_term?: string;
  5160. shipping?: Currency;
  5161. tax?: Currency;
  5162. transaction_id?: string;
  5163. value?: number;
  5164. event_label?: string;
  5165. event_category: string;
  5166. shipping_tier?: string;
  5167. item_list_id?: string;
  5168. item_list_name?: string;
  5169. promotion_id?: string;
  5170. promotion_name?: string;
  5171. payment_type?: string;
  5172. affiliation?: string;
  5173. }
  5174. /**
  5175. * Any custom params the user may pass to gtag.js.
  5176. */
  5177. export interface CustomParams {
  5178. [key: string]: any;
  5179. }
  5180. /**
  5181. * Type for standard gtag.js event names. `logEvent` also accepts any
  5182. * custom string and interprets it as a custom event name.
  5183. */
  5184. export type EventNameString =
  5185. | 'add_payment_info'
  5186. | 'add_shipping_info'
  5187. | 'add_to_cart'
  5188. | 'add_to_wishlist'
  5189. | 'begin_checkout'
  5190. | 'checkout_progress'
  5191. | 'exception'
  5192. | 'generate_lead'
  5193. | 'login'
  5194. | 'page_view'
  5195. | 'purchase'
  5196. | 'refund'
  5197. | 'remove_from_cart'
  5198. | 'screen_view'
  5199. | 'search'
  5200. | 'select_content'
  5201. | 'select_item'
  5202. | 'select_promotion'
  5203. | 'set_checkout_option'
  5204. | 'share'
  5205. | 'sign_up'
  5206. | 'timing_complete'
  5207. | 'view_cart'
  5208. | 'view_item'
  5209. | 'view_item_list'
  5210. | 'view_promotion'
  5211. | 'view_search_results';
  5212. /**
  5213. * Enum of standard gtag.js event names provided for convenient
  5214. * developer usage. `logEvent` will also accept any custom string
  5215. * and interpret it as a custom event name.
  5216. */
  5217. export enum EventName {
  5218. ADD_PAYMENT_INFO = 'add_payment_info',
  5219. ADD_SHIPPING_INFO = 'add_shipping_info',
  5220. ADD_TO_CART = 'add_to_cart',
  5221. ADD_TO_WISHLIST = 'add_to_wishlist',
  5222. BEGIN_CHECKOUT = 'begin_checkout',
  5223. /** @deprecated */
  5224. CHECKOUT_PROGRESS = 'checkout_progress',
  5225. EXCEPTION = 'exception',
  5226. GENERATE_LEAD = 'generate_lead',
  5227. LOGIN = 'login',
  5228. PAGE_VIEW = 'page_view',
  5229. PURCHASE = 'purchase',
  5230. REFUND = 'refund',
  5231. REMOVE_FROM_CART = 'remove_from_cart',
  5232. SCREEN_VIEW = 'screen_view',
  5233. SEARCH = 'search',
  5234. SELECT_CONTENT = 'select_content',
  5235. SELECT_ITEM = 'select_item',
  5236. SELECT_PROMOTION = 'select_promotion',
  5237. /** @deprecated */
  5238. SET_CHECKOUT_OPTION = 'set_checkout_option',
  5239. SHARE = 'share',
  5240. SIGN_UP = 'sign_up',
  5241. TIMING_COMPLETE = 'timing_complete',
  5242. VIEW_CART = 'view_cart',
  5243. VIEW_ITEM = 'view_item',
  5244. VIEW_ITEM_LIST = 'view_item_list',
  5245. VIEW_PROMOTION = 'view_promotion',
  5246. VIEW_SEARCH_RESULTS = 'view_search_results'
  5247. }
  5248. export type Currency = string | number;
  5249. export interface Item {
  5250. item_id?: string;
  5251. item_name?: string;
  5252. item_brand?: string;
  5253. item_category?: string;
  5254. item_category2?: string;
  5255. item_category3?: string;
  5256. item_category4?: string;
  5257. item_category5?: string;
  5258. item_variant?: string;
  5259. price?: Currency;
  5260. quantity?: number;
  5261. index?: number;
  5262. coupon?: string;
  5263. item_list_name?: string;
  5264. item_list_id?: string;
  5265. discount?: Currency;
  5266. affiliation?: string;
  5267. creative_name?: string;
  5268. creative_slot?: string;
  5269. promotion_id?: string;
  5270. promotion_name?: string;
  5271. location_id?: string;
  5272. /** @deprecated Use item_brand instead. */
  5273. brand?: string;
  5274. /** @deprecated Use item_category instead. */
  5275. category?: string;
  5276. /** @deprecated Use item_id instead. */
  5277. id?: string;
  5278. /** @deprecated Use item_name instead. */
  5279. name?: string;
  5280. }
  5281. /** @deprecated Use Item instead. */
  5282. export interface Promotion {
  5283. creative_name?: string;
  5284. creative_slot?: string;
  5285. id?: string;
  5286. name?: string;
  5287. }
  5288. /**
  5289. * An async function that returns true if current browser context supports initialization of analytics module
  5290. * (`firebase.analytics()`).
  5291. *
  5292. * Returns false otherwise.
  5293. *
  5294. *
  5295. */
  5296. function isSupported(): Promise<boolean>;
  5297. }
  5298. declare namespace firebase.auth.Auth {
  5299. type Persistence = string;
  5300. /**
  5301. * An enumeration of the possible persistence mechanism types.
  5302. */
  5303. var Persistence: {
  5304. /**
  5305. * Indicates that the state will be persisted even when the browser window is
  5306. * closed or the activity is destroyed in react-native.
  5307. */
  5308. LOCAL: Persistence;
  5309. /**
  5310. * Indicates that the state will only be stored in memory and will be cleared
  5311. * when the window or activity is refreshed.
  5312. */
  5313. NONE: Persistence;
  5314. /**
  5315. * Indicates that the state will only persist in current session/tab, relevant
  5316. * to web only, and will be cleared when the tab is closed.
  5317. */
  5318. SESSION: Persistence;
  5319. };
  5320. }
  5321. declare namespace firebase.User {
  5322. /**
  5323. * This is the interface that defines the multi-factor related properties and
  5324. * operations pertaining to a {@link firebase.User}.
  5325. */
  5326. interface MultiFactorUser {
  5327. /**
  5328. * Returns a list of the user's enrolled second factors.
  5329. */
  5330. enrolledFactors: firebase.auth.MultiFactorInfo[];
  5331. /**
  5332. * Enrolls a second factor as identified by the
  5333. * {@link firebase.auth.MultiFactorAssertion} for the current user.
  5334. * On resolution, the user tokens are updated to reflect the change in the
  5335. * JWT payload.
  5336. * Accepts an additional display name parameter used to identify the second
  5337. * factor to the end user.
  5338. * Recent re-authentication is required for this operation to succeed.
  5339. * On successful enrollment, existing Firebase sessions (refresh tokens) are
  5340. * revoked. When a new factor is enrolled, an email notification is sent
  5341. * to the users email.
  5342. *
  5343. * <h4>Error Codes</h4>
  5344. * <dl>
  5345. * <dt>auth/invalid-verification-code</dt>
  5346. * <dd>Thrown if the verification code is not valid.</dd>
  5347. * <dt>auth/missing-verification-code</dt>
  5348. * <dd>Thrown if the verification code is missing.</dd>
  5349. * <dt>auth/invalid-verification-id</dt>
  5350. * <dd>Thrown if the credential is a
  5351. * {@link firebase.auth.PhoneAuthProvider.credential} and the verification
  5352. * ID of the credential is not valid.</dd>
  5353. * <dt>auth/missing-verification-id</dt>
  5354. * <dd>Thrown if the verification ID is missing.</dd>
  5355. * <dt>auth/code-expired</dt>
  5356. * <dd>Thrown if the verification code has expired.</dd>
  5357. * <dt>auth/maximum-second-factor-count-exceeded</dt>
  5358. * <dd>Thrown if The maximum allowed number of second factors on a user
  5359. * has been exceeded.</dd>
  5360. * <dt>auth/second-factor-already-in-use</dt>
  5361. * <dd>Thrown if the second factor is already enrolled on this account.</dd>
  5362. * <dt>auth/unsupported-first-factor</dt>
  5363. * <dd>Thrown if the first factor being used to sign in is not supported.</dd>
  5364. * <dt>auth/unverified-email</dt>
  5365. * <dd>Thrown if the email of the account is not verified.</dd>
  5366. * <dt>auth/requires-recent-login</dt>
  5367. * <dd>Thrown if the user's last sign-in time does not meet the security
  5368. * threshold. Use {@link firebase.User.reauthenticateWithCredential} to
  5369. * resolve.</dd>
  5370. * </dl>
  5371. *
  5372. * @example
  5373. * ```javascript
  5374. * firebase.auth().currentUser.multiFactor.getSession()
  5375. * .then(function(multiFactorSession) {
  5376. * // Send verification code
  5377. * var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
  5378. * var phoneInfoOptions = {
  5379. * phoneNumber: phoneNumber,
  5380. * session: multiFactorSession
  5381. * };
  5382. * return phoneAuthProvider.verifyPhoneNumber(
  5383. * phoneInfoOptions, appVerifier);
  5384. * }).then(function(verificationId) {
  5385. * // Store verificationID and show UI to let user enter verification code.
  5386. * });
  5387. *
  5388. * var phoneAuthCredential =
  5389. * firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
  5390. * var multiFactorAssertion =
  5391. * firebase.auth.PhoneMultiFactorGenerator.assertion(phoneAuthCredential);
  5392. * firebase.auth().currentUser.multiFactor.enroll(multiFactorAssertion)
  5393. * .then(function() {
  5394. * // Second factor enrolled.
  5395. * });
  5396. * ```
  5397. *
  5398. * @param assertion The multi-factor assertion to enroll with.
  5399. * @param displayName The display name of the second factor.
  5400. */
  5401. enroll(
  5402. assertion: firebase.auth.MultiFactorAssertion,
  5403. displayName?: string | null
  5404. ): Promise<void>;
  5405. /**
  5406. * Returns the session identifier for a second factor enrollment operation.
  5407. * This is used to identify the current user trying to enroll a second factor.
  5408. * @return The promise that resolves with the
  5409. * {@link firebase.auth.MultiFactorSession}.
  5410. *
  5411. * <h4>Error Codes</h4>
  5412. * <dl>
  5413. * <dt>auth/user-token-expired</dt>
  5414. * <dd>Thrown if the token of the user is expired.</dd>
  5415. * </dl>
  5416. */
  5417. getSession(): Promise<firebase.auth.MultiFactorSession>;
  5418. /**
  5419. * Unenrolls the specified second factor. To specify the factor to remove, pass
  5420. * a {@link firebase.auth.MultiFactorInfo} object
  5421. * (retrieved from <code>enrolledFactors()</code>)
  5422. * or the factor's UID string.
  5423. * Sessions are not revoked when the account is downgraded. An email
  5424. * notification is likely to be sent to the user notifying them of the change.
  5425. * Recent re-authentication is required for this operation to succeed.
  5426. * When an existing factor is unenrolled, an email notification is sent to the
  5427. * users email.
  5428. *
  5429. * <h4>Error Codes</h4>
  5430. * <dl>
  5431. * <dt>auth/multi-factor-info-not-found</dt>
  5432. * <dd>Thrown if the user does not have a second factor matching the
  5433. * identifier provided.</dd>
  5434. * <dt>auth/requires-recent-login</dt>
  5435. * <dd>Thrown if the user's last sign-in time does not meet the security
  5436. * threshold. Use {@link firebase.User.reauthenticateWithCredential} to
  5437. * resolve.</dd>
  5438. * </dl>
  5439. *
  5440. * @example
  5441. * ```javascript
  5442. * var options = firebase.auth().currentUser.multiFactor.enrolledFactors;
  5443. * // Present user the option to unenroll.
  5444. * return firebase.auth().currentUser.multiFactor.unenroll(options[i])
  5445. * .then(function() {
  5446. * // User successfully unenrolled selected factor.
  5447. * }).catch(function(error) {
  5448. * // Handler error.
  5449. * });
  5450. * ```
  5451. *
  5452. * @param option The multi-factor option to unenroll.
  5453. */
  5454. unenroll(option: firebase.auth.MultiFactorInfo | string): Promise<void>;
  5455. }
  5456. }
  5457. declare namespace firebase.auth.ActionCodeInfo {
  5458. type Operation = string;
  5459. /**
  5460. * An enumeration of the possible email action types.
  5461. */
  5462. var Operation: {
  5463. /**
  5464. * The email link sign-in action.
  5465. */
  5466. EMAIL_SIGNIN: Operation;
  5467. /**
  5468. * The password reset action.
  5469. */
  5470. PASSWORD_RESET: Operation;
  5471. /**
  5472. * The email revocation action.
  5473. */
  5474. RECOVER_EMAIL: Operation;
  5475. /**
  5476. * The revert second factor addition email action.
  5477. */
  5478. REVERT_SECOND_FACTOR_ADDITION: Operation;
  5479. /**
  5480. * The verify and update email action.
  5481. */
  5482. VERIFY_AND_CHANGE_EMAIL: Operation;
  5483. /**
  5484. * The email verification action.
  5485. */
  5486. VERIFY_EMAIL: Operation;
  5487. };
  5488. }
  5489. declare namespace firebase.database {
  5490. /**
  5491. * A `DataSnapshot` contains data from a Database location.
  5492. *
  5493. * Any time you read data from the Database, you receive the data as a
  5494. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  5495. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  5496. * JavaScript object by calling the `val()` method. Alternatively, you can
  5497. * traverse into the snapshot by calling `child()` to return child snapshots
  5498. * (which you could then call `val()` on).
  5499. *
  5500. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  5501. * a Database location. It cannot be modified and will never change (to modify
  5502. * data, you always call the `set()` method on a `Reference` directly).
  5503. *
  5504. */
  5505. interface DataSnapshot {
  5506. /**
  5507. * Gets another `DataSnapshot` for the location at the specified relative path.
  5508. *
  5509. * Passing a relative path to the `child()` method of a DataSnapshot returns
  5510. * another `DataSnapshot` for the location at the specified relative path. The
  5511. * relative path can either be a simple child name (for example, "ada") or a
  5512. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  5513. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  5514. * whose value is `null`) is returned.
  5515. *
  5516. * @example
  5517. * ```javascript
  5518. * // Assume we have the following data in the Database:
  5519. * {
  5520. * "name": {
  5521. * "first": "Ada",
  5522. * "last": "Lovelace"
  5523. * }
  5524. * }
  5525. *
  5526. * // Test for the existence of certain keys within a DataSnapshot
  5527. * var ref = firebase.database().ref("users/ada");
  5528. * ref.once("value")
  5529. * .then(function(snapshot) {
  5530. * var name = snapshot.child("name").val(); // {first:"Ada",last:"Lovelace"}
  5531. * var firstName = snapshot.child("name/first").val(); // "Ada"
  5532. * var lastName = snapshot.child("name").child("last").val(); // "Lovelace"
  5533. * var age = snapshot.child("age").val(); // null
  5534. * });
  5535. * ```
  5536. *
  5537. * @param path A relative path to the location of child data.
  5538. */
  5539. child(path: string): firebase.database.DataSnapshot;
  5540. /**
  5541. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  5542. * efficient than using `snapshot.val() !== null`.
  5543. *
  5544. * @example
  5545. * ```javascript
  5546. * // Assume we have the following data in the Database:
  5547. * {
  5548. * "name": {
  5549. * "first": "Ada",
  5550. * "last": "Lovelace"
  5551. * }
  5552. * }
  5553. *
  5554. * // Test for the existence of certain keys within a DataSnapshot
  5555. * var ref = firebase.database().ref("users/ada");
  5556. * ref.once("value")
  5557. * .then(function(snapshot) {
  5558. * var a = snapshot.exists(); // true
  5559. * var b = snapshot.child("name").exists(); // true
  5560. * var c = snapshot.child("name/first").exists(); // true
  5561. * var d = snapshot.child("name/middle").exists(); // false
  5562. * });
  5563. * ```
  5564. */
  5565. exists(): boolean;
  5566. /**
  5567. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  5568. *
  5569. * The `exportVal()` method is similar to `val()`, except priority information
  5570. * is included (if available), making it suitable for backing up your data.
  5571. *
  5572. * @return The DataSnapshot's contents as a JavaScript value (Object,
  5573. * Array, string, number, boolean, or `null`).
  5574. */
  5575. exportVal(): any;
  5576. /**
  5577. * Enumerates the top-level children in the `DataSnapshot`.
  5578. *
  5579. * Because of the way JavaScript objects work, the ordering of data in the
  5580. * JavaScript object returned by `val()` is not guaranteed to match the ordering
  5581. * on the server nor the ordering of `child_added` events. That is where
  5582. * `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
  5583. * will be iterated in their query order.
  5584. *
  5585. * If no explicit `orderBy*()` method is used, results are returned
  5586. * ordered by key (unless priorities are used, in which case, results are
  5587. * returned by priority).
  5588. *
  5589. * @example
  5590. * ```javascript
  5591. * // Assume we have the following data in the Database:
  5592. * {
  5593. * "users": {
  5594. * "ada": {
  5595. * "first": "Ada",
  5596. * "last": "Lovelace"
  5597. * },
  5598. * "alan": {
  5599. * "first": "Alan",
  5600. * "last": "Turing"
  5601. * }
  5602. * }
  5603. * }
  5604. *
  5605. * // Loop through users in order with the forEach() method. The callback
  5606. * // provided to forEach() will be called synchronously with a DataSnapshot
  5607. * // for each child:
  5608. * var query = firebase.database().ref("users").orderByKey();
  5609. * query.once("value")
  5610. * .then(function(snapshot) {
  5611. * snapshot.forEach(function(childSnapshot) {
  5612. * // key will be "ada" the first time and "alan" the second time
  5613. * var key = childSnapshot.key;
  5614. * // childData will be the actual contents of the child
  5615. * var childData = childSnapshot.val();
  5616. * });
  5617. * });
  5618. * ```
  5619. *
  5620. * @example
  5621. * ```javascript
  5622. * // You can cancel the enumeration at any point by having your callback
  5623. * // function return true. For example, the following code sample will only
  5624. * // fire the callback function one time:
  5625. * var query = firebase.database().ref("users").orderByKey();
  5626. * query.once("value")
  5627. * .then(function(snapshot) {
  5628. * snapshot.forEach(function(childSnapshot) {
  5629. * var key = childSnapshot.key; // "ada"
  5630. *
  5631. * // Cancel enumeration
  5632. * return true;
  5633. * });
  5634. * });
  5635. * ```
  5636. *
  5637. * @param action A function
  5638. * that will be called for each child DataSnapshot. The callback can return
  5639. * true to cancel further enumeration.
  5640. * @return true if enumeration was canceled due to your callback
  5641. * returning true.
  5642. */
  5643. forEach(
  5644. action: (a: firebase.database.DataSnapshot) => boolean | void
  5645. ): boolean;
  5646. /**
  5647. * Gets the priority value of the data in this `DataSnapshot`.
  5648. *
  5649. * Applications need not use priority but can order collections by
  5650. * ordinary properties (see
  5651. * {@link
  5652. * https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
  5653. * Sorting and filtering data}).
  5654. */
  5655. getPriority(): string | number | null;
  5656. /**
  5657. * Returns true if the specified child path has (non-null) data.
  5658. *
  5659. * @example
  5660. * ```javascript
  5661. * // Assume we have the following data in the Database:
  5662. * {
  5663. * "name": {
  5664. * "first": "Ada",
  5665. * "last": "Lovelace"
  5666. * }
  5667. * }
  5668. *
  5669. * // Determine which child keys in DataSnapshot have data.
  5670. * var ref = firebase.database().ref("users/ada");
  5671. * ref.once("value")
  5672. * .then(function(snapshot) {
  5673. * var hasName = snapshot.hasChild("name"); // true
  5674. * var hasAge = snapshot.hasChild("age"); // false
  5675. * });
  5676. * ```
  5677. *
  5678. * @param path A relative path to the location of a potential child.
  5679. * @return `true` if data exists at the specified child path; else
  5680. * `false`.
  5681. */
  5682. hasChild(path: string): boolean;
  5683. /**
  5684. * Returns whether or not the `DataSnapshot` has any non-`null` child
  5685. * properties.
  5686. *
  5687. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  5688. * children. If it does, you can enumerate them using `forEach()`. If it
  5689. * doesn't, then either this snapshot contains a primitive value (which can be
  5690. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  5691. * `null`).
  5692. *
  5693. * @example
  5694. * ```javascript
  5695. * // Assume we have the following data in the Database:
  5696. * {
  5697. * "name": {
  5698. * "first": "Ada",
  5699. * "last": "Lovelace"
  5700. * }
  5701. * }
  5702. *
  5703. * var ref = firebase.database().ref("users/ada");
  5704. * ref.once("value")
  5705. * .then(function(snapshot) {
  5706. * var a = snapshot.hasChildren(); // true
  5707. * var b = snapshot.child("name").hasChildren(); // true
  5708. * var c = snapshot.child("name/first").hasChildren(); // false
  5709. * });
  5710. * ```
  5711. *
  5712. * @return true if this snapshot has any children; else false.
  5713. */
  5714. hasChildren(): boolean;
  5715. /**
  5716. * The key (last part of the path) of the location of this `DataSnapshot`.
  5717. *
  5718. * The last token in a Database location is considered its key. For example,
  5719. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  5720. * `DataSnapshot` will return the key for the location that generated it.
  5721. * However, accessing the key on the root URL of a Database will return `null`.
  5722. *
  5723. * @example
  5724. * ```javascript
  5725. * // Assume we have the following data in the Database:
  5726. * {
  5727. * "name": {
  5728. * "first": "Ada",
  5729. * "last": "Lovelace"
  5730. * }
  5731. * }
  5732. *
  5733. * var ref = firebase.database().ref("users/ada");
  5734. * ref.once("value")
  5735. * .then(function(snapshot) {
  5736. * var key = snapshot.key; // "ada"
  5737. * var childKey = snapshot.child("name/last").key; // "last"
  5738. * });
  5739. * ```
  5740. *
  5741. * @example
  5742. * ```javascript
  5743. * var rootRef = firebase.database().ref();
  5744. * rootRef.once("value")
  5745. * .then(function(snapshot) {
  5746. * var key = snapshot.key; // null
  5747. * var childKey = snapshot.child("users/ada").key; // "ada"
  5748. * });
  5749. * ```
  5750. */
  5751. key: string | null;
  5752. /**
  5753. * Returns the number of child properties of this `DataSnapshot`.
  5754. *
  5755. * @example
  5756. * ```javascript
  5757. * // Assume we have the following data in the Database:
  5758. * {
  5759. * "name": {
  5760. * "first": "Ada",
  5761. * "last": "Lovelace"
  5762. * }
  5763. * }
  5764. *
  5765. * var ref = firebase.database().ref("users/ada");
  5766. * ref.once("value")
  5767. * .then(function(snapshot) {
  5768. * var a = snapshot.numChildren(); // 1 ("name")
  5769. * var b = snapshot.child("name").numChildren(); // 2 ("first", "last")
  5770. * var c = snapshot.child("name/first").numChildren(); // 0
  5771. * });
  5772. * ```
  5773. */
  5774. numChildren(): number;
  5775. /**
  5776. * Extracts a JavaScript value from a `DataSnapshot`.
  5777. *
  5778. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  5779. * scalar type (string, number, or boolean), an array, or an object. It may also
  5780. * return null, indicating that the `DataSnapshot` is empty (contains no data).
  5781. *
  5782. * @example
  5783. * ```javascript
  5784. * // Write and then read back a string from the Database.
  5785. * ref.set("hello")
  5786. * .then(function() {
  5787. * return ref.once("value");
  5788. * })
  5789. * .then(function(snapshot) {
  5790. * var data = snapshot.val(); // data === "hello"
  5791. * });
  5792. * ```
  5793. *
  5794. * @example
  5795. * ```javascript
  5796. * // Write and then read back a JavaScript object from the Database.
  5797. * ref.set({ name: "Ada", age: 36 })
  5798. * .then(function() {
  5799. * return ref.once("value");
  5800. * })
  5801. * .then(function(snapshot) {
  5802. * var data = snapshot.val();
  5803. * // data is { "name": "Ada", "age": 36 }
  5804. * // data.name === "Ada"
  5805. * // data.age === 36
  5806. * });
  5807. * ```
  5808. *
  5809. * @return The DataSnapshot's contents as a JavaScript value (Object,
  5810. * Array, string, number, boolean, or `null`).
  5811. */
  5812. val(): any;
  5813. /**
  5814. * The `Reference` for the location that generated this `DataSnapshot`.
  5815. */
  5816. ref: firebase.database.Reference;
  5817. /**
  5818. * Returns a JSON-serializable representation of this object.
  5819. */
  5820. toJSON(): Object | null;
  5821. }
  5822. /**
  5823. * The Firebase Database service interface.
  5824. *
  5825. * Do not call this constructor directly. Instead, use
  5826. * {@link firebase.database `firebase.database()`}.
  5827. *
  5828. * See
  5829. * {@link
  5830. * https://firebase.google.com/docs/database/web/start/
  5831. * Installation &amp; Setup in JavaScript}
  5832. * for a full guide on how to use the Firebase Database service.
  5833. */
  5834. interface Database {
  5835. /**
  5836. * The {@link firebase.app.App app} associated with the `Database` service
  5837. * instance.
  5838. *
  5839. * @example
  5840. * ```javascript
  5841. * var app = database.app;
  5842. * ```
  5843. */
  5844. app: firebase.app.App;
  5845. /**
  5846. * Additional methods for debugging and special cases.
  5847. *
  5848. */
  5849. INTERNAL: {
  5850. /**
  5851. * Force the use of WebSockets instead of long polling.
  5852. */
  5853. forceWebSockets: () => void;
  5854. /**
  5855. * Force the use of long polling instead of WebSockets. This will be ignored if the WebSocket protocol is used in `databaseURL`.
  5856. */
  5857. forceLongPolling: () => void;
  5858. };
  5859. /**
  5860. * Modify this instance to communicate with the Realtime Database emulator.
  5861. *
  5862. * <p>Note: This method must be called before performing any other operation.
  5863. *
  5864. * @param host the emulator host (ex: localhost)
  5865. * @param port the emulator port (ex: 8080)
  5866. * @param options.mockUserToken the mock auth token to use for unit testing Security Rules
  5867. */
  5868. useEmulator(
  5869. host: string,
  5870. port: number,
  5871. options?: {
  5872. mockUserToken?: EmulatorMockTokenOptions | string;
  5873. }
  5874. ): void;
  5875. /**
  5876. * Disconnects from the server (all Database operations will be completed
  5877. * offline).
  5878. *
  5879. * The client automatically maintains a persistent connection to the Database
  5880. * server, which will remain active indefinitely and reconnect when
  5881. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  5882. * to control the client connection in cases where a persistent connection is
  5883. * undesirable.
  5884. *
  5885. * While offline, the client will no longer receive data updates from the
  5886. * Database. However, all Database operations performed locally will continue to
  5887. * immediately fire events, allowing your application to continue behaving
  5888. * normally. Additionally, each operation performed locally will automatically
  5889. * be queued and retried upon reconnection to the Database server.
  5890. *
  5891. * To reconnect to the Database and begin receiving remote events, see
  5892. * `goOnline()`.
  5893. *
  5894. * @example
  5895. * ```javascript
  5896. * firebase.database().goOffline();
  5897. * ```
  5898. */
  5899. goOffline(): any;
  5900. /**
  5901. * Reconnects to the server and synchronizes the offline Database state
  5902. * with the server state.
  5903. *
  5904. * This method should be used after disabling the active connection with
  5905. * `goOffline()`. Once reconnected, the client will transmit the proper data
  5906. * and fire the appropriate events so that your client "catches up"
  5907. * automatically.
  5908. *
  5909. * @example
  5910. * ```javascript
  5911. * firebase.database().goOnline();
  5912. * ```
  5913. */
  5914. goOnline(): any;
  5915. /**
  5916. * Returns a `Reference` representing the location in the Database
  5917. * corresponding to the provided path. If no path is provided, the `Reference`
  5918. * will point to the root of the Database.
  5919. *
  5920. * @example
  5921. * ```javascript
  5922. * // Get a reference to the root of the Database
  5923. * var rootRef = firebase.database().ref();
  5924. * ```
  5925. *
  5926. * @example
  5927. * ```javascript
  5928. * // Get a reference to the /users/ada node
  5929. * var adaRef = firebase.database().ref("users/ada");
  5930. * // The above is shorthand for the following operations:
  5931. * //var rootRef = firebase.database().ref();
  5932. * //var adaRef = rootRef.child("users/ada");
  5933. * ```
  5934. *
  5935. * @param path Optional path representing the location the returned
  5936. * `Reference` will point. If not provided, the returned `Reference` will
  5937. * point to the root of the Database.
  5938. * @return If a path is provided, a `Reference`
  5939. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  5940. * root of the Database.
  5941. */
  5942. ref(path?: string): firebase.database.Reference;
  5943. /**
  5944. * Returns a `Reference` representing the location in the Database
  5945. * corresponding to the provided Firebase URL.
  5946. *
  5947. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  5948. * has a different domain than the current `Database` instance.
  5949. *
  5950. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  5951. * and are not applied to the returned `Reference`.
  5952. *
  5953. * @example
  5954. * ```javascript
  5955. * // Get a reference to the root of the Database
  5956. * var rootRef = firebase.database().ref("https://<DATABASE_NAME>.firebaseio.com");
  5957. * ```
  5958. *
  5959. * @example
  5960. * ```javascript
  5961. * // Get a reference to the /users/ada node
  5962. * var adaRef = firebase.database().ref("https://<DATABASE_NAME>.firebaseio.com/users/ada");
  5963. * ```
  5964. *
  5965. * @param url The Firebase URL at which the returned `Reference` will
  5966. * point.
  5967. * @return A `Reference` pointing to the provided
  5968. * Firebase URL.
  5969. */
  5970. refFromURL(url: string): firebase.database.Reference;
  5971. }
  5972. /**
  5973. * The `onDisconnect` class allows you to write or clear data when your client
  5974. * disconnects from the Database server. These updates occur whether your
  5975. * client disconnects cleanly or not, so you can rely on them to clean up data
  5976. * even if a connection is dropped or a client crashes.
  5977. *
  5978. * The `onDisconnect` class is most commonly used to manage presence in
  5979. * applications where it is useful to detect how many clients are connected and
  5980. * when other clients disconnect. See
  5981. * {@link
  5982. * https://firebase.google.com/docs/database/web/offline-capabilities
  5983. * Enabling Offline Capabilities in JavaScript} for more information.
  5984. *
  5985. * To avoid problems when a connection is dropped before the requests can be
  5986. * transferred to the Database server, these functions should be called before
  5987. * writing any data.
  5988. *
  5989. * Note that `onDisconnect` operations are only triggered once. If you want an
  5990. * operation to occur each time a disconnect occurs, you'll need to re-establish
  5991. * the `onDisconnect` operations each time you reconnect.
  5992. */
  5993. interface OnDisconnect {
  5994. /**
  5995. * Cancels all previously queued `onDisconnect()` set or update events for this
  5996. * location and all children.
  5997. *
  5998. * If a write has been queued for this location via a `set()` or `update()` at a
  5999. * parent location, the write at this location will be canceled, though writes
  6000. * to sibling locations will still occur.
  6001. *
  6002. * @example
  6003. * ```javascript
  6004. * var ref = firebase.database().ref("onlineState");
  6005. * ref.onDisconnect().set(false);
  6006. * // ... sometime later
  6007. * ref.onDisconnect().cancel();
  6008. * ```
  6009. *
  6010. * @param onComplete An optional callback function that will
  6011. * be called when synchronization to the server has completed. The callback
  6012. * will be passed a single parameter: null for success, or an Error object
  6013. * indicating a failure.
  6014. * @return Resolves when synchronization to the server
  6015. * is complete.
  6016. */
  6017. cancel(onComplete?: (a: Error | null) => any): Promise<any>;
  6018. /**
  6019. * Ensures the data at this location is deleted when the client is disconnected
  6020. * (due to closing the browser, navigating to a new page, or network issues).
  6021. *
  6022. * @param onComplete An optional callback function that will
  6023. * be called when synchronization to the server has completed. The callback
  6024. * will be passed a single parameter: null for success, or an Error object
  6025. * indicating a failure.
  6026. * @return Resolves when synchronization to the server
  6027. * is complete.
  6028. */
  6029. remove(onComplete?: (a: Error | null) => any): Promise<any>;
  6030. /**
  6031. * Ensures the data at this location is set to the specified value when the
  6032. * client is disconnected (due to closing the browser, navigating to a new page,
  6033. * or network issues).
  6034. *
  6035. * `set()` is especially useful for implementing "presence" systems, where a
  6036. * value should be changed or cleared when a user disconnects so that they
  6037. * appear "offline" to other users. See
  6038. * {@link
  6039. * https://firebase.google.com/docs/database/web/offline-capabilities
  6040. * Enabling Offline Capabilities in JavaScript} for more information.
  6041. *
  6042. * Note that `onDisconnect` operations are only triggered once. If you want an
  6043. * operation to occur each time a disconnect occurs, you'll need to re-establish
  6044. * the `onDisconnect` operations each time.
  6045. *
  6046. * @example
  6047. * ```javascript
  6048. * var ref = firebase.database().ref("users/ada/status");
  6049. * ref.onDisconnect().set("I disconnected!");
  6050. * ```
  6051. *
  6052. * @param value The value to be written to this location on
  6053. * disconnect (can be an object, array, string, number, boolean, or null).
  6054. * @param onComplete An optional callback function that
  6055. * will be called when synchronization to the Database server has completed.
  6056. * The callback will be passed a single parameter: null for success, or an
  6057. * `Error` object indicating a failure.
  6058. * @return Resolves when synchronization to the
  6059. * Database is complete.
  6060. */
  6061. set(value: any, onComplete?: (a: Error | null) => any): Promise<any>;
  6062. /**
  6063. * Ensures the data at this location is set to the specified value and priority
  6064. * when the client is disconnected (due to closing the browser, navigating to a
  6065. * new page, or network issues).
  6066. */
  6067. setWithPriority(
  6068. value: any,
  6069. priority: number | string | null,
  6070. onComplete?: (a: Error | null) => any
  6071. ): Promise<any>;
  6072. /**
  6073. * Writes multiple values at this location when the client is disconnected (due
  6074. * to closing the browser, navigating to a new page, or network issues).
  6075. *
  6076. * The `values` argument contains multiple property-value pairs that will be
  6077. * written to the Database together. Each child property can either be a simple
  6078. * property (for example, "name") or a relative path (for example, "name/first")
  6079. * from the current location to the data to update.
  6080. *
  6081. * As opposed to the `set()` method, `update()` can be use to selectively update
  6082. * only the referenced properties at the current location (instead of replacing
  6083. * all the child properties at the current location).
  6084. *
  6085. * See more examples using the connected version of
  6086. * {@link firebase.database.Reference.update `update()`}.
  6087. *
  6088. * @example
  6089. * ```javascript
  6090. * var ref = firebase.database().ref("users/ada");
  6091. * ref.update({
  6092. * onlineState: true,
  6093. * status: "I'm online."
  6094. * });
  6095. * ref.onDisconnect().update({
  6096. * onlineState: false,
  6097. * status: "I'm offline."
  6098. * });
  6099. * ```
  6100. *
  6101. * @param values Object containing multiple values.
  6102. * @param onComplete An optional callback function that will
  6103. * be called when synchronization to the server has completed. The
  6104. * callback will be passed a single parameter: null for success, or an Error
  6105. * object indicating a failure.
  6106. * @return Resolves when synchronization to the
  6107. * Database is complete.
  6108. */
  6109. update(values: Object, onComplete?: (a: Error | null) => any): Promise<any>;
  6110. }
  6111. type EventType =
  6112. | 'value'
  6113. | 'child_added'
  6114. | 'child_changed'
  6115. | 'child_moved'
  6116. | 'child_removed';
  6117. /**
  6118. * A `Query` sorts and filters the data at a Database location so only a subset
  6119. * of the child data is included. This can be used to order a collection of
  6120. * data by some attribute (for example, height of dinosaurs) as well as to
  6121. * restrict a large list of items (for example, chat messages) down to a number
  6122. * suitable for synchronizing to the client. Queries are created by chaining
  6123. * together one or more of the filter methods defined here.
  6124. *
  6125. * Just as with a `Reference`, you can receive data from a `Query` by using the
  6126. * `on()` method. You will only receive events and `DataSnapshot`s for the
  6127. * subset of the data that matches your query.
  6128. *
  6129. * Read our documentation on
  6130. * {@link
  6131. * https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
  6132. * Sorting and filtering data} for more information.
  6133. */
  6134. interface Query {
  6135. /**
  6136. * Creates a `Query` with the specified ending point.
  6137. *
  6138. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  6139. * allows you to choose arbitrary starting and ending points for your queries.
  6140. *
  6141. * The ending point is inclusive, so children with exactly the specified value
  6142. * will be included in the query. The optional key argument can be used to
  6143. * further limit the range of the query. If it is specified, then children that
  6144. * have exactly the specified value must also have a key name less than or equal
  6145. * to the specified key.
  6146. *
  6147. * You can read more about `endAt()` in
  6148. * {@link
  6149. * https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
  6150. * Filtering data}.
  6151. *
  6152. * @example
  6153. * ```javascript
  6154. * // Find all dinosaurs whose names come before Pterodactyl lexicographically.
  6155. * // Include Pterodactyl in the result.
  6156. * var ref = firebase.database().ref("dinosaurs");
  6157. * ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
  6158. * console.log(snapshot.key);
  6159. * });
  6160. * ```
  6161. *
  6162. * @param value The value to end at. The argument
  6163. * type depends on which `orderBy*()` function was used in this query.
  6164. * Specify a value that matches the `orderBy*()` type. When used in
  6165. * combination with `orderByKey()`, the value must be a string.
  6166. * @param key The child key to end at, among the children with the
  6167. * previously specified priority. This argument is only allowed if ordering by
  6168. * child, value, or priority.
  6169. */
  6170. endAt(
  6171. value: number | string | boolean | null,
  6172. key?: string
  6173. ): firebase.database.Query;
  6174. /**
  6175. * Creates a `Query` with the specified ending point (exclusive).
  6176. *
  6177. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  6178. * allows you to choose arbitrary starting and ending points for your queries.
  6179. *
  6180. * The ending point is exclusive. If only a value is provided, children
  6181. * with a value less than the specified value will be included in the query.
  6182. * If a key is specified, then children must have a value lesss than or equal
  6183. * to the specified value and a a key name less than the specified key.
  6184. *
  6185. * @example
  6186. * ```javascript
  6187. * // Find all dinosaurs whose names come before Pterodactyl lexicographically.
  6188. * // Do not include Pterodactyl in the result.
  6189. * var ref = firebase.database().ref("dinosaurs");
  6190. * ref.orderByKey().endBefore("pterodactyl").on("child_added", function(snapshot) {
  6191. * console.log(snapshot.key);
  6192. * });
  6193. *
  6194. * @param value The value to end before. The argument
  6195. * type depends on which `orderBy*()` function was used in this query.
  6196. * Specify a value that matches the `orderBy*()` type. When used in
  6197. * combination with `orderByKey()`, the value must be a string.
  6198. * @param key The child key to end before, among the children with the
  6199. * previously specified priority. This argument is only allowed if ordering by
  6200. * child, value, or priority.
  6201. */
  6202. endBefore(
  6203. value: number | string | boolean | null,
  6204. key?: string
  6205. ): firebase.database.Query;
  6206. /**
  6207. * Creates a `Query` that includes children that match the specified value.
  6208. *
  6209. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  6210. * allows you to choose arbitrary starting and ending points for your queries.
  6211. *
  6212. * The optional key argument can be used to further limit the range of the
  6213. * query. If it is specified, then children that have exactly the specified
  6214. * value must also have exactly the specified key as their key name. This can be
  6215. * used to filter result sets with many matches for the same value.
  6216. *
  6217. * You can read more about `equalTo()` in
  6218. * {@link
  6219. * https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
  6220. * Filtering data}.
  6221. *
  6222. * @example
  6223. * ```javascript
  6224. * // Find all dinosaurs whose height is exactly 25 meters.
  6225. * var ref = firebase.database().ref("dinosaurs");
  6226. * ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
  6227. * console.log(snapshot.key);
  6228. * });
  6229. * ```
  6230. *
  6231. * @param value The value to match for. The
  6232. * argument type depends on which `orderBy*()` function was used in this
  6233. * query. Specify a value that matches the `orderBy*()` type. When used in
  6234. * combination with `orderByKey()`, the value must be a string.
  6235. * @param key The child key to start at, among the children with the
  6236. * previously specified priority. This argument is only allowed if ordering by
  6237. * child, value, or priority.
  6238. */
  6239. equalTo(
  6240. value: number | string | boolean | null,
  6241. key?: string
  6242. ): firebase.database.Query;
  6243. /**
  6244. * Returns whether or not the current and provided queries represent the same
  6245. * location, have the same query parameters, and are from the same instance of
  6246. * `firebase.app.App`.
  6247. *
  6248. * Two `Reference` objects are equivalent if they represent the same location
  6249. * and are from the same instance of `firebase.app.App`.
  6250. *
  6251. * Two `Query` objects are equivalent if they represent the same location, have
  6252. * the same query parameters, and are from the same instance of
  6253. * `firebase.app.App`. Equivalent queries share the same sort order, limits, and
  6254. * starting and ending points.
  6255. *
  6256. * @example
  6257. * ```javascript
  6258. * var rootRef = firebase.database.ref();
  6259. * var usersRef = rootRef.child("users");
  6260. *
  6261. * usersRef.isEqual(rootRef); // false
  6262. * usersRef.isEqual(rootRef.child("users")); // true
  6263. * usersRef.parent.isEqual(rootRef); // true
  6264. * ```
  6265. *
  6266. * @example
  6267. * ```javascript
  6268. * var rootRef = firebase.database.ref();
  6269. * var usersRef = rootRef.child("users");
  6270. * var usersQuery = usersRef.limitToLast(10);
  6271. *
  6272. * usersQuery.isEqual(usersRef); // false
  6273. * usersQuery.isEqual(usersRef.limitToLast(10)); // true
  6274. * usersQuery.isEqual(rootRef.limitToLast(10)); // false
  6275. * usersQuery.isEqual(usersRef.orderByKey().limitToLast(10)); // false
  6276. * ```
  6277. *
  6278. * @param other The query to compare against.
  6279. * @return Whether or not the current and provided queries are
  6280. * equivalent.
  6281. */
  6282. isEqual(other: firebase.database.Query | null): boolean;
  6283. /**
  6284. * Generates a new `Query` limited to the first specific number of children.
  6285. *
  6286. * The `limitToFirst()` method is used to set a maximum number of children to be
  6287. * synced for a given callback. If we set a limit of 100, we will initially only
  6288. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  6289. * stored in our Database, a `child_added` event will fire for each message.
  6290. * However, if we have over 100 messages, we will only receive a `child_added`
  6291. * event for the first 100 ordered messages. As items change, we will receive
  6292. * `child_removed` events for each item that drops out of the active list so
  6293. * that the total number stays at 100.
  6294. *
  6295. * You can read more about `limitToFirst()` in
  6296. * {@link
  6297. * https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
  6298. * Filtering data}.
  6299. *
  6300. * @example
  6301. * ```javascript
  6302. * // Find the two shortest dinosaurs.
  6303. * var ref = firebase.database().ref("dinosaurs");
  6304. * ref.orderByChild("height").limitToFirst(2).on("child_added", function(snapshot) {
  6305. * // This will be called exactly two times (unless there are less than two
  6306. * // dinosaurs in the Database).
  6307. *
  6308. * // It will also get fired again if one of the first two dinosaurs is
  6309. * // removed from the data set, as a new dinosaur will now be the second
  6310. * // shortest.
  6311. * console.log(snapshot.key);
  6312. * });
  6313. * ```
  6314. *
  6315. * @param limit The maximum number of nodes to include in this query.
  6316. */
  6317. limitToFirst(limit: number): firebase.database.Query;
  6318. /**
  6319. * Generates a new `Query` object limited to the last specific number of
  6320. * children.
  6321. *
  6322. * The `limitToLast()` method is used to set a maximum number of children to be
  6323. * synced for a given callback. If we set a limit of 100, we will initially only
  6324. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  6325. * stored in our Database, a `child_added` event will fire for each message.
  6326. * However, if we have over 100 messages, we will only receive a `child_added`
  6327. * event for the last 100 ordered messages. As items change, we will receive
  6328. * `child_removed` events for each item that drops out of the active list so
  6329. * that the total number stays at 100.
  6330. *
  6331. * You can read more about `limitToLast()` in
  6332. * {@link
  6333. * https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
  6334. * Filtering data}.
  6335. *
  6336. * @example
  6337. * ```javascript
  6338. * // Find the two heaviest dinosaurs.
  6339. * var ref = firebase.database().ref("dinosaurs");
  6340. * ref.orderByChild("weight").limitToLast(2).on("child_added", function(snapshot) {
  6341. * // This callback will be triggered exactly two times, unless there are
  6342. * // fewer than two dinosaurs stored in the Database. It will also get fired
  6343. * // for every new, heavier dinosaur that gets added to the data set.
  6344. * console.log(snapshot.key);
  6345. * });
  6346. * ```
  6347. *
  6348. * @param limit The maximum number of nodes to include in this query.
  6349. */
  6350. limitToLast(limit: number): firebase.database.Query;
  6351. /**
  6352. * Detaches a callback previously attached with `on()`.
  6353. *
  6354. * Detach a callback previously attached with `on()`. Note that if `on()` was
  6355. * called multiple times with the same eventType and callback, the callback
  6356. * will be called multiple times for each event, and `off()` must be called
  6357. * multiple times to remove the callback. Calling `off()` on a parent listener
  6358. * will not automatically remove listeners registered on child nodes, `off()`
  6359. * must also be called on any child listeners to remove the callback.
  6360. *
  6361. * If a callback is not specified, all callbacks for the specified eventType
  6362. * will be removed. Similarly, if no eventType is specified, all callbacks
  6363. * for the `Reference` will be removed.
  6364. *
  6365. * @example
  6366. * ```javascript
  6367. * var onValueChange = function(dataSnapshot) { ... };
  6368. * ref.on('value', onValueChange);
  6369. * ref.child('meta-data').on('child_added', onChildAdded);
  6370. * // Sometime later...
  6371. * ref.off('value', onValueChange);
  6372. *
  6373. * // You must also call off() for any child listeners on ref
  6374. * // to cancel those callbacks
  6375. * ref.child('meta-data').off('child_added', onValueAdded);
  6376. * ```
  6377. *
  6378. * @example
  6379. * ```javascript
  6380. * // Or you can save a line of code by using an inline function
  6381. * // and on()'s return value.
  6382. * var onValueChange = ref.on('value', function(dataSnapshot) { ... });
  6383. * // Sometime later...
  6384. * ref.off('value', onValueChange);
  6385. * ```
  6386. *
  6387. * @param eventType One of the following strings: "value",
  6388. * "child_added", "child_changed", "child_removed", or "child_moved." If
  6389. * omitted, all callbacks for the `Reference` will be removed.
  6390. * @param callback The callback function that was passed to `on()` or
  6391. * `undefined` to remove all callbacks.
  6392. * @param context The context that was passed to `on()`.
  6393. */
  6394. off(
  6395. eventType?: EventType,
  6396. callback?: (a: firebase.database.DataSnapshot, b?: string | null) => any,
  6397. context?: Object | null
  6398. ): void;
  6399. /**
  6400. * Gets the most up-to-date result for this query.
  6401. *
  6402. * @return A promise which resolves to the resulting DataSnapshot if
  6403. * a value is available, or rejects if the client is unable to return
  6404. * a value (e.g., if the server is unreachable and there is nothing
  6405. * cached).
  6406. */
  6407. get(): Promise<DataSnapshot>;
  6408. /**
  6409. * Listens for data changes at a particular location.
  6410. *
  6411. * This is the primary way to read data from a Database. Your callback
  6412. * will be triggered for the initial data and again whenever the data changes.
  6413. * Use `off( )` to stop receiving updates. See
  6414. * {@link https://firebase.google.com/docs/database/web/retrieve-data
  6415. * Retrieve Data on the Web}
  6416. * for more details.
  6417. *
  6418. * <h4>value event</h4>
  6419. *
  6420. * This event will trigger once with the initial data stored at this location,
  6421. * and then trigger again each time the data changes. The `DataSnapshot` passed
  6422. * to the callback will be for the location at which `on()` was called. It
  6423. * won't trigger until the entire contents has been synchronized. If the
  6424. * location has no data, it will be triggered with an empty `DataSnapshot`
  6425. * (`val()` will return `null`).
  6426. *
  6427. * <h4>child_added event</h4>
  6428. *
  6429. * This event will be triggered once for each initial child at this location,
  6430. * and it will be triggered again every time a new child is added. The
  6431. * `DataSnapshot` passed into the callback will reflect the data for the
  6432. * relevant child. For ordering purposes, it is passed a second argument which
  6433. * is a string containing the key of the previous sibling child by sort order,
  6434. * or `null` if it is the first child.
  6435. *
  6436. * <h4>child_removed event</h4>
  6437. *
  6438. * This event will be triggered once every time a child is removed. The
  6439. * `DataSnapshot` passed into the callback will be the old data for the child
  6440. * that was removed. A child will get removed when either:
  6441. *
  6442. * - a client explicitly calls `remove()` on that child or one of its ancestors
  6443. * - a client calls `set(null)` on that child or one of its ancestors
  6444. * - that child has all of its children removed
  6445. * - there is a query in effect which now filters out the child (because it's
  6446. * sort order changed or the max limit was hit)
  6447. *
  6448. * <h4>child_changed event</h4>
  6449. *
  6450. * This event will be triggered when the data stored in a child (or any of its
  6451. * descendants) changes. Note that a single `child_changed` event may represent
  6452. * multiple changes to the child. The `DataSnapshot` passed to the callback will
  6453. * contain the new child contents. For ordering purposes, the callback is also
  6454. * passed a second argument which is a string containing the key of the previous
  6455. * sibling child by sort order, or `null` if it is the first child.
  6456. *
  6457. * <h4>child_moved event</h4>
  6458. *
  6459. * This event will be triggered when a child's sort order changes such that its
  6460. * position relative to its siblings changes. The `DataSnapshot` passed to the
  6461. * callback will be for the data of the child that has moved. It is also passed
  6462. * a second argument which is a string containing the key of the previous
  6463. * sibling child by sort order, or `null` if it is the first child.
  6464. *
  6465. * @example **Handle a new value:**
  6466. * ```javascript
  6467. * ref.on('value', function(dataSnapshot) {
  6468. * ...
  6469. * });
  6470. * ```
  6471. *
  6472. * @example **Handle a new child:**
  6473. * ```javascript
  6474. * ref.on('child_added', function(childSnapshot, prevChildKey) {
  6475. * ...
  6476. * });
  6477. * ```
  6478. *
  6479. * @example **Handle child removal:**
  6480. * ```javascript
  6481. * ref.on('child_removed', function(oldChildSnapshot) {
  6482. * ...
  6483. * });
  6484. * ```
  6485. *
  6486. * @example **Handle child data changes:**
  6487. * ```javascript
  6488. * ref.on('child_changed', function(childSnapshot, prevChildKey) {
  6489. * ...
  6490. * });
  6491. * ```
  6492. *
  6493. * @example **Handle child ordering changes:**
  6494. * ```javascript
  6495. * ref.on('child_moved', function(childSnapshot, prevChildKey) {
  6496. * ...
  6497. * });
  6498. * ```
  6499. *
  6500. * @param eventType One of the following strings: "value",
  6501. * "child_added", "child_changed", "child_removed", or "child_moved."
  6502. * @param callback A
  6503. * callback that fires when the specified event occurs. The callback will be
  6504. * passed a DataSnapshot. For ordering purposes, "child_added",
  6505. * "child_changed", and "child_moved" will also be passed a string containing
  6506. * the key of the previous child, by sort order, or `null` if it is the
  6507. * first child.
  6508. * @param cancelCallbackOrContext An optional
  6509. * callback that will be notified if your event subscription is ever canceled
  6510. * because your client does not have permission to read this data (or it had
  6511. * permission but has now lost it). This callback will be passed an `Error`
  6512. * object indicating why the failure occurred.
  6513. * @param context If provided, this object will be used as `this`
  6514. * when calling your callback(s).
  6515. * @return The provided
  6516. * callback function is returned unmodified. This is just for convenience if
  6517. * you want to pass an inline function to `on()` but store the callback
  6518. * function for later passing to `off()`.
  6519. */
  6520. on(
  6521. eventType: EventType,
  6522. callback: (a: firebase.database.DataSnapshot, b?: string | null) => any,
  6523. cancelCallbackOrContext?: ((a: Error) => any) | Object | null,
  6524. context?: Object | null
  6525. ): (a: firebase.database.DataSnapshot | null, b?: string | null) => any;
  6526. /**
  6527. * Listens for exactly one event of the specified event type, and then stops
  6528. * listening.
  6529. *
  6530. * This is equivalent to calling {@link firebase.database.Query.on `on()`}, and
  6531. * then calling {@link firebase.database.Query.off `off()`} inside the callback
  6532. * function. See {@link firebase.database.Query.on `on()`} for details on the
  6533. * event types.
  6534. *
  6535. * @example
  6536. * ```javascript
  6537. * // Basic usage of .once() to read the data located at ref.
  6538. * ref.once('value')
  6539. * .then(function(dataSnapshot) {
  6540. * // handle read data.
  6541. * });
  6542. * ```
  6543. *
  6544. * @param eventType One of the following strings: "value",
  6545. * "child_added", "child_changed", "child_removed", or "child_moved."
  6546. * @param successCallback A
  6547. * callback that fires when the specified event occurs. The callback will be
  6548. * passed a DataSnapshot. For ordering purposes, "child_added",
  6549. * "child_changed", and "child_moved" will also be passed a string containing
  6550. * the key of the previous child by sort order, or `null` if it is the
  6551. * first child.
  6552. * @param failureCallbackOrContext An optional
  6553. * callback that will be notified if your client does not have permission to
  6554. * read the data. This callback will be passed an `Error` object indicating
  6555. * why the failure occurred.
  6556. * @param context If provided, this object will be used as `this`
  6557. * when calling your callback(s).
  6558. */
  6559. once(
  6560. eventType: EventType,
  6561. successCallback?: (
  6562. a: firebase.database.DataSnapshot,
  6563. b?: string | null
  6564. ) => any,
  6565. failureCallbackOrContext?: ((a: Error) => void) | Object | null,
  6566. context?: Object | null
  6567. ): Promise<firebase.database.DataSnapshot>;
  6568. /**
  6569. * Generates a new `Query` object ordered by the specified child key.
  6570. *
  6571. * Queries can only order by one key at a time. Calling `orderByChild()`
  6572. * multiple times on the same query is an error.
  6573. *
  6574. * Firebase queries allow you to order your data by any child key on the fly.
  6575. * However, if you know in advance what your indexes will be, you can define
  6576. * them via the .indexOn rule in your Security Rules for better performance. See
  6577. * the {@link https://firebase.google.com/docs/database/security/indexing-data
  6578. * .indexOn} rule for more information.
  6579. *
  6580. * You can read more about `orderByChild()` in
  6581. * {@link
  6582. * https://firebase.google.com/docs/database/web/lists-of-data#sort_data
  6583. * Sort data}.
  6584. *
  6585. * @example
  6586. * ```javascript
  6587. * var ref = firebase.database().ref("dinosaurs");
  6588. * ref.orderByChild("height").on("child_added", function(snapshot) {
  6589. * console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
  6590. * });
  6591. * ```
  6592. */
  6593. orderByChild(path: string): firebase.database.Query;
  6594. /**
  6595. * Generates a new `Query` object ordered by key.
  6596. *
  6597. * Sorts the results of a query by their (ascending) key values.
  6598. *
  6599. * You can read more about `orderByKey()` in
  6600. * {@link
  6601. * https://firebase.google.com/docs/database/web/lists-of-data#sort_data
  6602. * Sort data}.
  6603. *
  6604. * @example
  6605. * ```javascript
  6606. * var ref = firebase.database().ref("dinosaurs");
  6607. * ref.orderByKey().on("child_added", function(snapshot) {
  6608. * console.log(snapshot.key);
  6609. * });
  6610. * ```
  6611. */
  6612. orderByKey(): firebase.database.Query;
  6613. /**
  6614. * Generates a new `Query` object ordered by priority.
  6615. *
  6616. * Applications need not use priority but can order collections by
  6617. * ordinary properties (see
  6618. * {@link
  6619. * https://firebase.google.com/docs/database/web/lists-of-data#sort_data
  6620. * Sort data} for alternatives to priority.
  6621. */
  6622. orderByPriority(): firebase.database.Query;
  6623. /**
  6624. * Generates a new `Query` object ordered by value.
  6625. *
  6626. * If the children of a query are all scalar values (string, number, or
  6627. * boolean), you can order the results by their (ascending) values.
  6628. *
  6629. * You can read more about `orderByValue()` in
  6630. * {@link
  6631. * https://firebase.google.com/docs/database/web/lists-of-data#sort_data
  6632. * Sort data}.
  6633. *
  6634. * @example
  6635. * ```javascript
  6636. * var scoresRef = firebase.database().ref("scores");
  6637. * scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
  6638. * snapshot.forEach(function(data) {
  6639. * console.log("The " + data.key + " score is " + data.val());
  6640. * });
  6641. * });
  6642. * ```
  6643. */
  6644. orderByValue(): firebase.database.Query;
  6645. /**
  6646. * Returns a `Reference` to the `Query`'s location.
  6647. */
  6648. ref: firebase.database.Reference;
  6649. /**
  6650. * Creates a `Query` with the specified starting point.
  6651. *
  6652. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  6653. * allows you to choose arbitrary starting and ending points for your queries.
  6654. *
  6655. * The starting point is inclusive, so children with exactly the specified value
  6656. * will be included in the query. The optional key argument can be used to
  6657. * further limit the range of the query. If it is specified, then children that
  6658. * have exactly the specified value must also have a key name greater than or
  6659. * equal to the specified key.
  6660. *
  6661. * You can read more about `startAt()` in
  6662. * {@link
  6663. * https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
  6664. * Filtering data}.
  6665. *
  6666. * @example
  6667. * ```javascript
  6668. * // Find all dinosaurs that are at least three meters tall.
  6669. * var ref = firebase.database().ref("dinosaurs");
  6670. * ref.orderByChild("height").startAt(3).on("child_added", function(snapshot) {
  6671. * console.log(snapshot.key)
  6672. * });
  6673. * ```
  6674. *
  6675. * @param value The value to start at. The argument
  6676. * type depends on which `orderBy*()` function was used in this query.
  6677. * Specify a value that matches the `orderBy*()` type. When used in
  6678. * combination with `orderByKey()`, the value must be a string.
  6679. * @param key The child key to start at. This argument is only allowed
  6680. * if ordering by child, value, or priority.
  6681. */
  6682. startAt(
  6683. value: number | string | boolean | null,
  6684. key?: string
  6685. ): firebase.database.Query;
  6686. /**
  6687. * Creates a `Query` with the specified starting point (exclusive).
  6688. *
  6689. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  6690. * allows you to choose arbitrary starting and ending points for your queries.
  6691. *
  6692. * The starting point is exclusive. If only a value is provided, children
  6693. * with a value greater than the specified value will be included in the query.
  6694. * If a key is specified, then children must have a value greater than or equal
  6695. * to the specified value and a a key name greater than the specified key.
  6696. *
  6697. * @example
  6698. * ```javascript
  6699. * // Find all dinosaurs that are more than three meters tall.
  6700. * var ref = firebase.database().ref("dinosaurs");
  6701. * ref.orderByChild("height").startAfter(3).on("child_added", function(snapshot) {
  6702. * console.log(snapshot.key)
  6703. * });
  6704. * ```
  6705. *
  6706. * @param value The value to start after. The argument
  6707. * type depends on which `orderBy*()` function was used in this query.
  6708. * Specify a value that matches the `orderBy*()` type. When used in
  6709. * combination with `orderByKey()`, the value must be a string.
  6710. * @param key The child key to start after. This argument is only allowed
  6711. * if ordering by child, value, or priority.
  6712. */
  6713. startAfter(
  6714. value: number | string | boolean | null,
  6715. key?: string
  6716. ): firebase.database.Query;
  6717. /**
  6718. * Returns a JSON-serializable representation of this object.
  6719. *
  6720. * @return A JSON-serializable representation of this object.
  6721. */
  6722. toJSON(): Object;
  6723. /**
  6724. * Gets the absolute URL for this location.
  6725. *
  6726. * The `toString()` method returns a URL that is ready to be put into a browser,
  6727. * curl command, or a `firebase.database().refFromURL()` call. Since all of
  6728. * those expect the URL to be url-encoded, `toString()` returns an encoded URL.
  6729. *
  6730. * Append '.json' to the returned URL when typed into a browser to download
  6731. * JSON-formatted data. If the location is secured (that is, not publicly
  6732. * readable), you will get a permission-denied error.
  6733. *
  6734. * @example
  6735. * ```javascript
  6736. * // Calling toString() on a root Firebase reference returns the URL where its
  6737. * // data is stored within the Database:
  6738. * var rootRef = firebase.database().ref();
  6739. * var rootUrl = rootRef.toString();
  6740. * // rootUrl === "https://sample-app.firebaseio.com/".
  6741. *
  6742. * // Calling toString() at a deeper Firebase reference returns the URL of that
  6743. * // deep path within the Database:
  6744. * var adaRef = rootRef.child('users/ada');
  6745. * var adaURL = adaRef.toString();
  6746. * // adaURL === "https://sample-app.firebaseio.com/users/ada".
  6747. * ```
  6748. *
  6749. * @return The absolute URL for this location.
  6750. */
  6751. toString(): string;
  6752. }
  6753. /**
  6754. * A `Reference` represents a specific location in your Database and can be used
  6755. * for reading or writing data to that Database location.
  6756. *
  6757. * You can reference the root or child location in your Database by calling
  6758. * `firebase.database().ref()` or `firebase.database().ref("child/path")`.
  6759. *
  6760. * Writing is done with the `set()` method and reading can be done with the
  6761. * `on()` method. See
  6762. * {@link
  6763. * https://firebase.google.com/docs/database/web/read-and-write
  6764. * Read and Write Data on the Web}
  6765. */
  6766. interface Reference extends firebase.database.Query {
  6767. /**
  6768. * Gets a `Reference` for the location at the specified relative path.
  6769. *
  6770. * The relative path can either be a simple child name (for example, "ada") or
  6771. * a deeper slash-separated path (for example, "ada/name/first").
  6772. *
  6773. * @example
  6774. * ```javascript
  6775. * var usersRef = firebase.database().ref('users');
  6776. * var adaRef = usersRef.child('ada');
  6777. * var adaFirstNameRef = adaRef.child('name/first');
  6778. * var path = adaFirstNameRef.toString();
  6779. * // path is now 'https://sample-app.firebaseio.com/users/ada/name/first'
  6780. * ```
  6781. *
  6782. * @param path A relative path from this location to the desired child
  6783. * location.
  6784. * @return The specified child location.
  6785. */
  6786. child(path: string): firebase.database.Reference;
  6787. /**
  6788. * The last part of the `Reference`'s path.
  6789. *
  6790. * For example, `"ada"` is the key for
  6791. * `https://<DATABASE_NAME>.firebaseio.com/users/ada`.
  6792. *
  6793. * The key of a root `Reference` is `null`.
  6794. *
  6795. * @example
  6796. * ```javascript
  6797. * // The key of a root reference is null
  6798. * var rootRef = firebase.database().ref();
  6799. * var key = rootRef.key; // key === null
  6800. * ```
  6801. *
  6802. * @example
  6803. * ```javascript
  6804. * // The key of any non-root reference is the last token in the path
  6805. * var adaRef = firebase.database().ref("users/ada");
  6806. * var key = adaRef.key; // key === "ada"
  6807. * key = adaRef.child("name/last").key; // key === "last"
  6808. * ```
  6809. */
  6810. key: string | null;
  6811. /**
  6812. * Returns an `OnDisconnect` object - see
  6813. * {@link
  6814. * https://firebase.google.com/docs/database/web/offline-capabilities
  6815. * Enabling Offline Capabilities in JavaScript} for more information on how
  6816. * to use it.
  6817. */
  6818. onDisconnect(): firebase.database.OnDisconnect;
  6819. /**
  6820. * The parent location of a `Reference`.
  6821. *
  6822. * The parent of a root `Reference` is `null`.
  6823. *
  6824. * @example
  6825. * ```javascript
  6826. * // The parent of a root reference is null
  6827. * var rootRef = firebase.database().ref();
  6828. * parent = rootRef.parent; // parent === null
  6829. * ```
  6830. *
  6831. * @example
  6832. * ```javascript
  6833. * // The parent of any non-root reference is the parent location
  6834. * var usersRef = firebase.database().ref("users");
  6835. * var adaRef = firebase.database().ref("users/ada");
  6836. * // usersRef and adaRef.parent represent the same location
  6837. * ```
  6838. */
  6839. parent: firebase.database.Reference | null;
  6840. /**
  6841. * Generates a new child location using a unique key and returns its
  6842. * `Reference`.
  6843. *
  6844. * This is the most common pattern for adding data to a collection of items.
  6845. *
  6846. * If you provide a value to `push()`, the value is written to the
  6847. * generated location. If you don't pass a value, nothing is written to the
  6848. * database and the child remains empty (but you can use the `Reference`
  6849. * elsewhere).
  6850. *
  6851. * The unique keys generated by `push()` are ordered by the current time, so the
  6852. * resulting list of items is chronologically sorted. The keys are also
  6853. * designed to be unguessable (they contain 72 random bits of entropy).
  6854. *
  6855. *
  6856. * See
  6857. * {@link
  6858. * https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data
  6859. * Append to a list of data}
  6860. * </br>See
  6861. * {@link
  6862. * https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html
  6863. * The 2^120 Ways to Ensure Unique Identifiers}
  6864. *
  6865. * @example
  6866. * ```javascript
  6867. * var messageListRef = firebase.database().ref('message_list');
  6868. * var newMessageRef = messageListRef.push();
  6869. * newMessageRef.set({
  6870. * 'user_id': 'ada',
  6871. * 'text': 'The Analytical Engine weaves algebraical patterns just as the Jacquard loom weaves flowers and leaves.'
  6872. * });
  6873. * // We've appended a new message to the message_list location.
  6874. * var path = newMessageRef.toString();
  6875. * // path will be something like
  6876. * // 'https://sample-app.firebaseio.com/message_list/-IKo28nwJLH0Nc5XeFmj'
  6877. * ```
  6878. *
  6879. * @param value Optional value to be written at the generated location.
  6880. * @param onComplete Callback called when write to server is
  6881. * complete.
  6882. * @return Combined `Promise` and `Reference`; resolves when write is complete, but can be
  6883. * used immediately as the `Reference` to the child location.
  6884. */
  6885. push(
  6886. value?: any,
  6887. onComplete?: (a: Error | null) => any
  6888. ): firebase.database.ThenableReference;
  6889. /**
  6890. * Removes the data at this Database location.
  6891. *
  6892. * Any data at child locations will also be deleted.
  6893. *
  6894. * The effect of the remove will be visible immediately and the corresponding
  6895. * event 'value' will be triggered. Synchronization of the remove to the
  6896. * Firebase servers will also be started, and the returned Promise will resolve
  6897. * when complete. If provided, the onComplete callback will be called
  6898. * asynchronously after synchronization has finished.
  6899. *
  6900. * @example
  6901. * ```javascript
  6902. * var adaRef = firebase.database().ref('users/ada');
  6903. * adaRef.remove()
  6904. * .then(function() {
  6905. * console.log("Remove succeeded.")
  6906. * })
  6907. * .catch(function(error) {
  6908. * console.log("Remove failed: " + error.message)
  6909. * });
  6910. * ```
  6911. *
  6912. * @param onComplete Callback called when write to server is
  6913. * complete.
  6914. * @return Resolves when remove on server is complete.
  6915. */
  6916. remove(onComplete?: (a: Error | null) => void): Promise<void>;
  6917. /**
  6918. * The root `Reference` of the Database.
  6919. *
  6920. * @example
  6921. * ```javascript
  6922. * // The root of a root reference is itself
  6923. * var rootRef = firebase.database().ref();
  6924. * // rootRef and rootRef.root represent the same location
  6925. * ```
  6926. *
  6927. * @example
  6928. * ```javascript
  6929. * // The root of any non-root reference is the root location
  6930. * var adaRef = firebase.database().ref("users/ada");
  6931. * // rootRef and adaRef.root represent the same location
  6932. * ```
  6933. */
  6934. root: firebase.database.Reference;
  6935. /**
  6936. * Writes data to this Database location.
  6937. *
  6938. * This will overwrite any data at this location and all child locations.
  6939. *
  6940. * The effect of the write will be visible immediately, and the corresponding
  6941. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  6942. * the data to the Firebase servers will also be started, and the returned
  6943. * Promise will resolve when complete. If provided, the `onComplete` callback
  6944. * will be called asynchronously after synchronization has finished.
  6945. *
  6946. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  6947. * all data at this location and all child locations will be deleted.
  6948. *
  6949. * `set()` will remove any priority stored at this location, so if priority is
  6950. * meant to be preserved, you need to use `setWithPriority()` instead.
  6951. *
  6952. * Note that modifying data with `set()` will cancel any pending transactions
  6953. * at that location, so extreme care should be taken if mixing `set()` and
  6954. * `transaction()` to modify the same data.
  6955. *
  6956. * A single `set()` will generate a single "value" event at the location where
  6957. * the `set()` was performed.
  6958. *
  6959. * @example
  6960. * ```javascript
  6961. * var adaNameRef = firebase.database().ref('users/ada/name');
  6962. * adaNameRef.child('first').set('Ada');
  6963. * adaNameRef.child('last').set('Lovelace');
  6964. * // We've written 'Ada' to the Database location storing Ada's first name,
  6965. * // and 'Lovelace' to the location storing her last name.
  6966. * ```
  6967. *
  6968. * @example
  6969. * ```javascript
  6970. * adaNameRef.set({ first: 'Ada', last: 'Lovelace' });
  6971. * // Exact same effect as the previous example, except we've written
  6972. * // Ada's first and last name simultaneously.
  6973. * ```
  6974. *
  6975. * @example
  6976. * ```javascript
  6977. * adaNameRef.set({ first: 'Ada', last: 'Lovelace' })
  6978. * .then(function() {
  6979. * console.log('Synchronization succeeded');
  6980. * })
  6981. * .catch(function(error) {
  6982. * console.log('Synchronization failed');
  6983. * });
  6984. * // Same as the previous example, except we will also log a message
  6985. * // when the data has finished synchronizing.
  6986. * ```
  6987. *
  6988. * @param value The value to be written (string, number, boolean, object,
  6989. * array, or null).
  6990. * @param onComplete Callback called when write to server is
  6991. * complete.
  6992. * @return Resolves when write to server is complete.
  6993. */
  6994. set(value: any, onComplete?: (a: Error | null) => void): Promise<void>;
  6995. /**
  6996. * Sets a priority for the data at this Database location.
  6997. *
  6998. * Applications need not use priority but can order collections by
  6999. * ordinary properties (see
  7000. * {@link
  7001. * https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
  7002. * Sorting and filtering data}).
  7003. */
  7004. setPriority(
  7005. priority: string | number | null,
  7006. onComplete: (a: Error | null) => void
  7007. ): Promise<void>;
  7008. /**
  7009. * Writes data the Database location. Like `set()` but also specifies the
  7010. * priority for that data.
  7011. *
  7012. * Applications need not use priority but can order collections by
  7013. * ordinary properties (see
  7014. * {@link
  7015. * https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
  7016. * Sorting and filtering data}).
  7017. */
  7018. setWithPriority(
  7019. newVal: any,
  7020. newPriority: string | number | null,
  7021. onComplete?: (a: Error | null) => void
  7022. ): Promise<void>;
  7023. /**
  7024. * Atomically modifies the data at this location.
  7025. *
  7026. * Atomically modify the data at this location. Unlike a normal `set()`, which
  7027. * just overwrites the data regardless of its previous value, `transaction()` is
  7028. * used to modify the existing value to a new value, ensuring there are no
  7029. * conflicts with other clients writing to the same location at the same time.
  7030. *
  7031. * To accomplish this, you pass `transaction()` an update function which is used
  7032. * to transform the current value into a new value. If another client writes to
  7033. * the location before your new value is successfully written, your update
  7034. * function will be called again with the new current value, and the write will
  7035. * be retried. This will happen repeatedly until your write succeeds without
  7036. * conflict or you abort the transaction by not returning a value from your
  7037. * update function.
  7038. *
  7039. * Note: Modifying data with `set()` will cancel any pending transactions at
  7040. * that location, so extreme care should be taken if mixing `set()` and
  7041. * `transaction()` to update the same data.
  7042. *
  7043. * Note: When using transactions with Security and Firebase Rules in place, be
  7044. * aware that a client needs `.read` access in addition to `.write` access in
  7045. * order to perform a transaction. This is because the client-side nature of
  7046. * transactions requires the client to read the data in order to transactionally
  7047. * update it.
  7048. *
  7049. * @example
  7050. * ```javascript
  7051. * // Increment Ada's rank by 1.
  7052. * var adaRankRef = firebase.database().ref('users/ada/rank');
  7053. * adaRankRef.transaction(function(currentRank) {
  7054. * // If users/ada/rank has never been set, currentRank will be `null`.
  7055. * return currentRank + 1;
  7056. * });
  7057. * ```
  7058. *
  7059. * @example
  7060. * ```javascript
  7061. * // Try to create a user for ada, but only if the user id 'ada' isn't
  7062. * // already taken
  7063. * var adaRef = firebase.database().ref('users/ada');
  7064. * adaRef.transaction(function(currentData) {
  7065. * if (currentData === null) {
  7066. * return { name: { first: 'Ada', last: 'Lovelace' } };
  7067. * } else {
  7068. * console.log('User ada already exists.');
  7069. * return; // Abort the transaction.
  7070. * }
  7071. * }, function(error, committed, snapshot) {
  7072. * if (error) {
  7073. * console.log('Transaction failed abnormally!', error);
  7074. * } else if (!committed) {
  7075. * console.log('We aborted the transaction (because ada already exists).');
  7076. * } else {
  7077. * console.log('User ada added!');
  7078. * }
  7079. * console.log("Ada's data: ", snapshot.val());
  7080. * });
  7081. * ```
  7082. *
  7083. * @param transactionUpdate A developer-supplied function which
  7084. * will be passed the current data stored at this location (as a JavaScript
  7085. * object). The function should return the new value it would like written (as
  7086. * a JavaScript object). If `undefined` is returned (i.e. you return with no
  7087. * arguments) the transaction will be aborted and the data at this location
  7088. * will not be modified.
  7089. * @param onComplete A callback
  7090. * function that will be called when the transaction completes. The callback
  7091. * is passed three arguments: a possibly-null `Error`, a `boolean` indicating
  7092. * whether the transaction was committed, and a `DataSnapshot` indicating the
  7093. * final result. If the transaction failed abnormally, the first argument will
  7094. * be an `Error` object indicating the failure cause. If the transaction
  7095. * finished normally, but no data was committed because no data was returned
  7096. * from `transactionUpdate`, then second argument will be false. If the
  7097. * transaction completed and committed data to Firebase, the second argument
  7098. * will be true. Regardless, the third argument will be a `DataSnapshot`
  7099. * containing the resulting data in this location.
  7100. * @param applyLocally By default, events are raised each time the
  7101. * transaction update function runs. So if it is run multiple times, you may
  7102. * see intermediate states. You can set this to false to suppress these
  7103. * intermediate states and instead wait until the transaction has completed
  7104. * before events are raised.
  7105. * @return Returns a Promise that can optionally be used instead of the onComplete
  7106. * callback to handle success and failure.
  7107. */
  7108. transaction(
  7109. transactionUpdate: (a: any) => any,
  7110. onComplete?: (
  7111. a: Error | null,
  7112. b: boolean,
  7113. c: firebase.database.DataSnapshot | null
  7114. ) => void,
  7115. applyLocally?: boolean
  7116. ): Promise<TransactionResult>;
  7117. /**
  7118. * Writes multiple values to the Database at once.
  7119. *
  7120. * The `values` argument contains multiple property-value pairs that will be
  7121. * written to the Database together. Each child property can either be a simple
  7122. * property (for example, "name") or a relative path (for example,
  7123. * "name/first") from the current location to the data to update.
  7124. *
  7125. * As opposed to the `set()` method, `update()` can be use to selectively update
  7126. * only the referenced properties at the current location (instead of replacing
  7127. * all the child properties at the current location).
  7128. *
  7129. * The effect of the write will be visible immediately, and the corresponding
  7130. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  7131. * the data to the Firebase servers will also be started, and the returned
  7132. * Promise will resolve when complete. If provided, the `onComplete` callback
  7133. * will be called asynchronously after synchronization has finished.
  7134. *
  7135. * A single `update()` will generate a single "value" event at the location
  7136. * where the `update()` was performed, regardless of how many children were
  7137. * modified.
  7138. *
  7139. * Note that modifying data with `update()` will cancel any pending
  7140. * transactions at that location, so extreme care should be taken if mixing
  7141. * `update()` and `transaction()` to modify the same data.
  7142. *
  7143. * Passing `null` to `update()` will remove the data at this location.
  7144. *
  7145. * See
  7146. * {@link
  7147. * https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html
  7148. * Introducing multi-location updates and more}.
  7149. *
  7150. * @example
  7151. * ```javascript
  7152. * var adaNameRef = firebase.database().ref('users/ada/name');
  7153. * // Modify the 'first' and 'last' properties, but leave other data at
  7154. * // adaNameRef unchanged.
  7155. * adaNameRef.update({ first: 'Ada', last: 'Lovelace' });
  7156. * ```
  7157. *
  7158. * @param values Object containing multiple values.
  7159. * @param onComplete Callback called when write to server is
  7160. * complete.
  7161. * @return Resolves when update on server is complete.
  7162. */
  7163. update(
  7164. values: Object,
  7165. onComplete?: (a: Error | null) => void
  7166. ): Promise<void>;
  7167. }
  7168. interface TransactionResult {
  7169. /**
  7170. * Whether the transaction was successfully committed.
  7171. */
  7172. committed: boolean;
  7173. /**
  7174. * The resulting data snapshot.
  7175. */
  7176. snapshot: DataSnapshot;
  7177. }
  7178. interface ThenableReference
  7179. extends firebase.database.Reference,
  7180. Pick<Promise<Reference>, 'then' | 'catch'> {}
  7181. /**
  7182. * Logs debugging information to the console.
  7183. *
  7184. * @example
  7185. * ```javascript
  7186. * // Enable logging
  7187. * firebase.database.enableLogging(true);
  7188. * ```
  7189. *
  7190. * @example
  7191. * ```javascript
  7192. * // Disable logging
  7193. * firebase.database.enableLogging(false);
  7194. * ```
  7195. *
  7196. * @example
  7197. * ```javascript
  7198. * // Enable logging across page refreshes
  7199. * firebase.database.enableLogging(true, true);
  7200. * ```
  7201. *
  7202. * @example
  7203. * ```javascript
  7204. * // Provide custom logger which prefixes log statements with "[FIREBASE]"
  7205. * firebase.database.enableLogging(function(message) {
  7206. * console.log("[FIREBASE]", message);
  7207. * });
  7208. * ```
  7209. *
  7210. * @param logger Enables logging if `true`;
  7211. * disables logging if `false`. You can also provide a custom logger function
  7212. * to control how things get logged.
  7213. * @param persistent Remembers the logging state between page
  7214. * refreshes if `true`.
  7215. */
  7216. function enableLogging(
  7217. logger?: boolean | ((a: string) => any),
  7218. persistent?: boolean
  7219. ): any;
  7220. export type EmulatorMockTokenOptions = firebase.EmulatorMockTokenOptions;
  7221. }
  7222. declare namespace firebase.database.ServerValue {
  7223. /**
  7224. * A placeholder value for auto-populating the current timestamp (time
  7225. * since the Unix epoch, in milliseconds) as determined by the Firebase
  7226. * servers.
  7227. *
  7228. * @example
  7229. * ```javascript
  7230. * var sessionsRef = firebase.database().ref("sessions");
  7231. * sessionsRef.push({
  7232. * startedAt: firebase.database.ServerValue.TIMESTAMP
  7233. * });
  7234. * ```
  7235. */
  7236. var TIMESTAMP: Object;
  7237. /**
  7238. * Returns a placeholder value that can be used to atomically increment the
  7239. * current database value by the provided delta.
  7240. *
  7241. * @param delta the amount to modify the current value atomically.
  7242. * @return a placeholder value for modifying data atomically server-side.
  7243. */
  7244. function increment(delta: number): Object;
  7245. }
  7246. /**
  7247. * @webonly
  7248. */
  7249. declare namespace firebase.messaging {
  7250. /**
  7251. * The Firebase Messaging service interface.
  7252. *
  7253. * Do not call this constructor directly. Instead, use
  7254. * {@link firebase.messaging `firebase.messaging()`}.
  7255. *
  7256. * See {@link https://firebase.google.com/docs/cloud-messaging/js/client
  7257. * Set Up a JavaScript Firebase Cloud Messaging Client App} for a full guide on how to use the
  7258. * Firebase Messaging service.
  7259. *
  7260. */
  7261. interface Messaging {
  7262. /**
  7263. * Deletes the registration token associated with this messaging instance and unsubscribes the
  7264. * messaging instance from the push subscription.
  7265. *
  7266. * @return The promise resolves when the token has been successfully deleted.
  7267. */
  7268. deleteToken(): Promise<boolean>;
  7269. /**
  7270. * Subscribes the messaging instance to push notifications. Returns an FCM registration token
  7271. * that can be used to send push messages to that messaging instance.
  7272. *
  7273. * If a notification permission isn't already granted, this method asks the user for permission.
  7274. * The returned promise rejects if the user does not allow the app to show notifications.
  7275. *
  7276. * @param options.vapidKey The public server key provided to push services. It is used to
  7277. * authenticate the push subscribers to receive push messages only from sending servers that
  7278. * hold the corresponding private key. If it is not provided, a default VAPID key is used. Note
  7279. * that some push services (Chrome Push Service) require a non-default VAPID key. Therefore, it
  7280. * is recommended to generate and import a VAPID key for your project with
  7281. * {@link https://firebase.google.com/docs/cloud-messaging/js/client#configure_web_credentials_with_fcm Configure Web Credentials with FCM}.
  7282. * See
  7283. * {@link https://developers.google.com/web/fundamentals/push-notifications/web-push-protocol The Web Push Protocol}
  7284. * for details on web push services.}
  7285. *
  7286. * @param options.serviceWorkerRegistration The service worker registration for receiving push
  7287. * messaging. If the registration is not provided explicitly, you need to have a
  7288. * `firebase-messaging-sw.js` at your root location. See
  7289. * {@link https://firebase.google.com/docs/cloud-messaging/js/client#retrieve-the-current-registration-token Retrieve the current registration token}
  7290. * for more details.
  7291. *
  7292. * @return The promise resolves with an FCM registration token.
  7293. *
  7294. */
  7295. getToken(options?: {
  7296. vapidKey?: string;
  7297. serviceWorkerRegistration?: ServiceWorkerRegistration;
  7298. }): Promise<string>;
  7299. /**
  7300. * When a push message is received and the user is currently on a page for your origin, the
  7301. * message is passed to the page and an `onMessage()` event is dispatched with the payload of
  7302. * the push message.
  7303. *
  7304. * @param
  7305. * nextOrObserver This function, or observer object with `next` defined,
  7306. * is called when a message is received and the user is currently viewing your page.
  7307. * @return To stop listening for messages execute this returned function.
  7308. */
  7309. onMessage(
  7310. nextOrObserver: firebase.NextFn<any> | firebase.Observer<any>
  7311. ): firebase.Unsubscribe;
  7312. /**
  7313. * Called when a message is received while the app is in the background. An app is considered to
  7314. * be in the background if no active window is displayed.
  7315. *
  7316. * @param
  7317. * nextOrObserver This function, or observer object with `next` defined,
  7318. * is called when a message is received and the app is currently in the background.
  7319. *
  7320. * @return To stop listening for messages execute this returned function
  7321. */
  7322. onBackgroundMessage(
  7323. nextOrObserver:
  7324. | firebase.NextFn<MessagePayload>
  7325. | firebase.Observer<MessagePayload>
  7326. ): firebase.Unsubscribe;
  7327. }
  7328. /**
  7329. * Message payload that contains the notification payload that is represented with
  7330. * {@link firebase.messaging.NotificationPayload} and the data payload that contains an arbitrary
  7331. * number of key-value pairs sent by developers through the
  7332. * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification Send API}
  7333. */
  7334. export interface MessagePayload {
  7335. /**
  7336. * See {@link firebase.messaging.NotificationPayload}.
  7337. */
  7338. notification?: NotificationPayload;
  7339. /**
  7340. * Arbitrary key/value pairs.
  7341. */
  7342. data?: { [key: string]: string };
  7343. /**
  7344. * See {@link firebase.messaging.FcmOptions}.
  7345. */
  7346. fcmOptions?: FcmOptions;
  7347. /**
  7348. * The sender of this message.
  7349. */
  7350. from: string;
  7351. /**
  7352. * The collapse key of this message. See
  7353. * {@link https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages
  7354. * Collapsible and non-collapsible messages}.
  7355. */
  7356. collapseKey: string;
  7357. }
  7358. /**
  7359. * Options for features provided by the FCM SDK for Web. See
  7360. * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions
  7361. * WebpushFcmOptions}.
  7362. */
  7363. export interface FcmOptions {
  7364. /**
  7365. * The link to open when the user clicks on the notification. For all URL values, HTTPS is
  7366. * required. For example, by setting this value to your app's URL, a notification click event
  7367. * will put your app in focus for the user.
  7368. */
  7369. link?: string;
  7370. /**
  7371. * Label associated with the message's analytics data. See
  7372. * {@link https://firebase.google.com/docs/cloud-messaging/understand-delivery#adding-analytics-labels-to-messages
  7373. * Adding analytics labels}.
  7374. */
  7375. analyticsLabel?: string;
  7376. }
  7377. /**
  7378. * Parameters that define how a push notification is displayed to users.
  7379. */
  7380. export interface NotificationPayload {
  7381. /**
  7382. * The title of a notification.
  7383. */
  7384. title?: string;
  7385. /**
  7386. * The body of a notification.
  7387. */
  7388. body?: string;
  7389. /**
  7390. * The URL of the image that is shown with the notification. See
  7391. * {@link https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification
  7392. * `notification.image`} for supported image format.
  7393. */
  7394. image?: string;
  7395. }
  7396. function isSupported(): boolean;
  7397. }
  7398. declare namespace firebase.storage {
  7399. /**
  7400. * The full set of object metadata, including read-only properties.
  7401. */
  7402. interface FullMetadata extends firebase.storage.UploadMetadata {
  7403. /**
  7404. * The bucket this object is contained in.
  7405. */
  7406. bucket: string;
  7407. /**
  7408. * The full path of this object.
  7409. */
  7410. fullPath: string;
  7411. /**
  7412. * The object's generation.
  7413. * @see {@link https://cloud.google.com/storage/docs/generations-preconditions}
  7414. */
  7415. generation: string;
  7416. /**
  7417. * The object's metageneration.
  7418. * @see {@link https://cloud.google.com/storage/docs/generations-preconditions}
  7419. */
  7420. metageneration: string;
  7421. /**
  7422. * The short name of this object, which is the last component of the full path.
  7423. * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
  7424. */
  7425. name: string;
  7426. /**
  7427. * The size of this object, in bytes.
  7428. */
  7429. size: number;
  7430. /**
  7431. * A date string representing when this object was created.
  7432. */
  7433. timeCreated: string;
  7434. /**
  7435. * A date string representing when this object was last updated.
  7436. */
  7437. updated: string;
  7438. }
  7439. /**
  7440. * Represents a reference to a Google Cloud Storage object. Developers can
  7441. * upload, download, and delete objects, as well as get/set object metadata.
  7442. */
  7443. interface Reference {
  7444. /**
  7445. * The name of the bucket containing this reference's object.
  7446. */
  7447. bucket: string;
  7448. /**
  7449. * Returns a reference to a relative path from this reference.
  7450. * @param path The relative path from this reference.
  7451. * Leading, trailing, and consecutive slashes are removed.
  7452. * @return The reference to the given path.
  7453. */
  7454. child(path: string): firebase.storage.Reference;
  7455. /**
  7456. * Deletes the object at this reference's location.
  7457. * @return A Promise that resolves if the deletion
  7458. * succeeded and rejects if it failed, including if the object didn't exist.
  7459. */
  7460. delete(): Promise<void>;
  7461. /**
  7462. * The full path of this object.
  7463. */
  7464. fullPath: string;
  7465. /**
  7466. * Fetches a long lived download URL for this object.
  7467. * @return A Promise that resolves with the download
  7468. * URL or rejects if the fetch failed, including if the object did not
  7469. * exist.
  7470. */
  7471. getDownloadURL(): Promise<string>;
  7472. /**
  7473. * Fetches metadata for the object at this location, if one exists.
  7474. * @return A Promise that
  7475. * resolves with the metadata, or rejects if the fetch failed, including if
  7476. * the object did not exist.
  7477. */
  7478. getMetadata(): Promise<FullMetadata>;
  7479. /**
  7480. * The short name of this object, which is the last component of the full path.
  7481. * For example, if fullPath is 'full/path/image.png', name is 'image.png'.
  7482. */
  7483. name: string;
  7484. /**
  7485. * A reference pointing to the parent location of this reference, or null if
  7486. * this reference is the root.
  7487. */
  7488. parent: firebase.storage.Reference | null;
  7489. /**
  7490. * Uploads data to this reference's location.
  7491. * @param data The data to upload.
  7492. * @param metadata Metadata for the newly
  7493. * uploaded object.
  7494. * @return An object that can be used to monitor
  7495. * and manage the upload.
  7496. */
  7497. put(
  7498. data: Blob | Uint8Array | ArrayBuffer,
  7499. metadata?: firebase.storage.UploadMetadata
  7500. ): firebase.storage.UploadTask;
  7501. /**
  7502. * Uploads string data to this reference's location.
  7503. * @param data The string to upload.
  7504. * @param format The format of the string to
  7505. * upload.
  7506. * @param metadata Metadata for the newly
  7507. * uploaded object.
  7508. * @throws If the format is not an allowed format, or if the given string
  7509. * doesn't conform to the specified format.
  7510. */
  7511. putString(
  7512. data: string,
  7513. format?: firebase.storage.StringFormat,
  7514. metadata?: firebase.storage.UploadMetadata
  7515. ): firebase.storage.UploadTask;
  7516. /**
  7517. * A reference to the root of this reference's bucket.
  7518. */
  7519. root: firebase.storage.Reference;
  7520. /**
  7521. * The storage service associated with this reference.
  7522. */
  7523. storage: firebase.storage.Storage;
  7524. /**
  7525. * Returns a gs:// URL for this object in the form
  7526. * `gs://<bucket>/<path>/<to>/<object>`
  7527. * @return The gs:// URL.
  7528. */
  7529. toString(): string;
  7530. /**
  7531. * Updates the metadata for the object at this location, if one exists.
  7532. * @param metadata The new metadata.
  7533. * Setting a property to 'null' removes it on the server, while leaving
  7534. * a property as 'undefined' has no effect.
  7535. * @return A Promise that
  7536. * resolves with the full updated metadata or rejects if the updated failed,
  7537. * including if the object did not exist.
  7538. */
  7539. updateMetadata(
  7540. metadata: firebase.storage.SettableMetadata
  7541. ): Promise<FullMetadata>;
  7542. /**
  7543. * List all items (files) and prefixes (folders) under this storage reference.
  7544. *
  7545. * This is a helper method for calling `list()` repeatedly until there are
  7546. * no more results. The default pagination size is 1000.
  7547. *
  7548. * Note: The results may not be consistent if objects are changed while this
  7549. * operation is running.
  7550. *
  7551. * Warning: `listAll` may potentially consume too many resources if there are
  7552. * too many results.
  7553. *
  7554. * @return A Promise that resolves with all the items and prefixes under
  7555. * the current storage reference. `prefixes` contains references to
  7556. * sub-directories and `items` contains references to objects in this
  7557. * folder. `nextPageToken` is never returned.
  7558. */
  7559. listAll(): Promise<ListResult>;
  7560. /**
  7561. * List items (files) and prefixes (folders) under this storage reference.
  7562. *
  7563. * List API is only available for Firebase Rules Version 2.
  7564. *
  7565. * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
  7566. * delimited folder structure.
  7567. * Refer to GCS's List API if you want to learn more.
  7568. *
  7569. * To adhere to Firebase Rules's Semantics, Firebase Storage does not
  7570. * support objects whose paths end with "/" or contain two consecutive
  7571. * "/"s. Firebase Storage List API will filter these unsupported objects.
  7572. * `list()` may fail if there are too many unsupported objects in the bucket.
  7573. *
  7574. * @param options See `ListOptions` for details.
  7575. * @return A Promise that resolves with the items and prefixes.
  7576. * `prefixes` contains references to sub-folders and `items`
  7577. * contains references to objects in this folder. `nextPageToken`
  7578. * can be used to get the rest of the results.
  7579. */
  7580. list(options?: ListOptions): Promise<ListResult>;
  7581. }
  7582. /**
  7583. * Result returned by list().
  7584. */
  7585. interface ListResult {
  7586. /**
  7587. * References to prefixes (sub-folders). You can call list() on them to
  7588. * get its contents.
  7589. *
  7590. * Folders are implicit based on '/' in the object paths.
  7591. * For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a')
  7592. * will return '/a/b' as a prefix.
  7593. */
  7594. prefixes: Reference[];
  7595. /**
  7596. * Objects in this directory.
  7597. * You can call getMetadata() and getDownloadUrl() on them.
  7598. */
  7599. items: Reference[];
  7600. /**
  7601. * If set, there might be more results for this list. Use this token to resume the list.
  7602. */
  7603. nextPageToken: string | null;
  7604. }
  7605. /**
  7606. * The options `list()` accepts.
  7607. */
  7608. interface ListOptions {
  7609. /**
  7610. * If set, limits the total number of `prefixes` and `items` to return.
  7611. * The default and maximum maxResults is 1000.
  7612. */
  7613. maxResults?: number | null;
  7614. /**
  7615. * The `nextPageToken` from a previous call to `list()`. If provided,
  7616. * listing is resumed from the previous position.
  7617. */
  7618. pageToken?: string | null;
  7619. }
  7620. /**
  7621. * Object metadata that can be set at any time.
  7622. */
  7623. interface SettableMetadata {
  7624. /**
  7625. * Served as the 'Cache-Control' header on object download.
  7626. */
  7627. cacheControl?: string | null;
  7628. contentDisposition?: string | null;
  7629. /**
  7630. * Served as the 'Content-Encoding' header on object download.
  7631. */
  7632. contentEncoding?: string | null;
  7633. /**
  7634. * Served as the 'Content-Language' header on object download.
  7635. */
  7636. contentLanguage?: string | null;
  7637. /**
  7638. * Served as the 'Content-Type' header on object download.
  7639. */
  7640. contentType?: string | null;
  7641. /**
  7642. * Additional user-defined custom metadata.
  7643. */
  7644. customMetadata?: {
  7645. [/* warning: coerced from ? */ key: string]: string;
  7646. } | null;
  7647. }
  7648. /**
  7649. * The Firebase Storage service interface.
  7650. *
  7651. * Do not call this constructor directly. Instead, use
  7652. * {@link firebase.storage `firebase.storage()`}.
  7653. *
  7654. * See
  7655. * {@link
  7656. * https://firebase.google.com/docs/storage/web/start/
  7657. * Get Started on Web}
  7658. * for a full guide on how to use the Firebase Storage service.
  7659. */
  7660. interface Storage {
  7661. /**
  7662. * The {@link firebase.app.App app} associated with the `Storage` service
  7663. * instance.
  7664. *
  7665. * @example
  7666. * ```javascript
  7667. * var app = storage.app;
  7668. * ```
  7669. */
  7670. app: firebase.app.App;
  7671. /**
  7672. * The maximum time to retry operations other than uploads or downloads in
  7673. * milliseconds.
  7674. */
  7675. maxOperationRetryTime: number;
  7676. /**
  7677. * The maximum time to retry uploads in milliseconds.
  7678. */
  7679. maxUploadRetryTime: number;
  7680. /**
  7681. * Returns a reference for the given path in the default bucket.
  7682. * @param path A relative path to initialize the reference with,
  7683. * for example `path/to/image.jpg`. If not passed, the returned reference
  7684. * points to the bucket root.
  7685. * @return A reference for the given path.
  7686. */
  7687. ref(path?: string): firebase.storage.Reference;
  7688. /**
  7689. * Returns a reference for the given absolute URL.
  7690. * @param url A URL in the form: <br />
  7691. * 1) a gs:// URL, for example `gs://bucket/files/image.png` <br />
  7692. * 2) a download URL taken from object metadata. <br />
  7693. * @return A reference for the given URL.
  7694. */
  7695. refFromURL(url: string): firebase.storage.Reference;
  7696. /**
  7697. * @param time The new maximum operation retry time in milliseconds.
  7698. * @see {@link firebase.storage.Storage.maxOperationRetryTime}
  7699. */
  7700. setMaxOperationRetryTime(time: number): any;
  7701. /**
  7702. * @param time The new maximum upload retry time in milliseconds.
  7703. * @see {@link firebase.storage.Storage.maxUploadRetryTime}
  7704. */
  7705. setMaxUploadRetryTime(time: number): any;
  7706. /**
  7707. * Modify this `Storage` instance to communicate with the Cloud Storage emulator.
  7708. *
  7709. * @param host - The emulator host (ex: localhost)
  7710. * @param port - The emulator port (ex: 5001)
  7711. * @param options.mockUserToken the mock auth token to use for unit testing Security Rules
  7712. */
  7713. useEmulator(
  7714. host: string,
  7715. port: number,
  7716. options?: {
  7717. mockUserToken?: EmulatorMockTokenOptions | string;
  7718. }
  7719. ): void;
  7720. }
  7721. /**
  7722. * @enum {string}
  7723. * An enumeration of the possible string formats for upload.
  7724. */
  7725. type StringFormat = string;
  7726. var StringFormat: {
  7727. /**
  7728. * Indicates the string should be interpreted as base64-encoded data.
  7729. * Padding characters (trailing '='s) are optional.
  7730. * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
  7731. * ad 69 8e fb e1 3a b7 bf eb 97
  7732. */
  7733. BASE64: StringFormat;
  7734. /**
  7735. * Indicates the string should be interpreted as base64url-encoded data.
  7736. * Padding characters (trailing '='s) are optional.
  7737. * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
  7738. * ad 69 8e fb e1 3a b7 bf eb 97
  7739. */
  7740. BASE64URL: StringFormat;
  7741. /**
  7742. * Indicates the string is a data URL, such as one obtained from
  7743. * canvas.toDataURL().
  7744. * Example: the string 'data:application/octet-stream;base64,aaaa'
  7745. * becomes the byte sequence
  7746. * 69 a6 9a
  7747. * (the content-type "application/octet-stream" is also applied, but can
  7748. * be overridden in the metadata object).
  7749. */
  7750. DATA_URL: StringFormat;
  7751. /**
  7752. * Indicates the string should be interpreted "raw", that is, as normal text.
  7753. * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
  7754. * sequence.
  7755. * Example: The string 'Hello! \ud83d\ude0a' becomes the byte sequence
  7756. * 48 65 6c 6c 6f 21 20 f0 9f 98 8a
  7757. */
  7758. RAW: StringFormat;
  7759. };
  7760. /**
  7761. * An event that is triggered on a task.
  7762. * @enum {string}
  7763. * @see {@link firebase.storage.UploadTask.on}
  7764. */
  7765. type TaskEvent = string;
  7766. var TaskEvent: {
  7767. /**
  7768. * For this event,
  7769. * <ul>
  7770. * <li>The `next` function is triggered on progress updates and when the
  7771. * task is paused/resumed with a
  7772. * {@link firebase.storage.UploadTaskSnapshot} as the first
  7773. * argument.</li>
  7774. * <li>The `error` function is triggered if the upload is canceled or fails
  7775. * for another reason.</li>
  7776. * <li>The `complete` function is triggered if the upload completes
  7777. * successfully.</li>
  7778. * </ul>
  7779. */
  7780. STATE_CHANGED: TaskEvent;
  7781. };
  7782. /**
  7783. * Represents the current state of a running upload.
  7784. * @enum {string}
  7785. */
  7786. type TaskState = string;
  7787. var TaskState: {
  7788. CANCELED: TaskState;
  7789. ERROR: TaskState;
  7790. PAUSED: TaskState;
  7791. RUNNING: TaskState;
  7792. SUCCESS: TaskState;
  7793. };
  7794. /**
  7795. * Object metadata that can be set at upload.
  7796. */
  7797. interface UploadMetadata extends firebase.storage.SettableMetadata {
  7798. /**
  7799. * A Base64-encoded MD5 hash of the object being uploaded.
  7800. */
  7801. md5Hash?: string | null;
  7802. }
  7803. /**
  7804. * An error returned by the Firebase Storage SDK.
  7805. */
  7806. interface FirebaseStorageError extends FirebaseError {
  7807. serverResponse: string | null;
  7808. }
  7809. interface StorageObserver<T> {
  7810. next?: NextFn<T> | null;
  7811. error?: (error: FirebaseStorageError) => void | null;
  7812. complete?: CompleteFn | null;
  7813. }
  7814. /**
  7815. * Represents the process of uploading an object. Allows you to monitor and
  7816. * manage the upload.
  7817. */
  7818. interface UploadTask {
  7819. /**
  7820. * Cancels a running task. Has no effect on a complete or failed task.
  7821. * @return True if the cancel had an effect.
  7822. */
  7823. cancel(): boolean;
  7824. /**
  7825. * Equivalent to calling `then(null, onRejected)`.
  7826. */
  7827. catch(onRejected: (error: FirebaseStorageError) => any): Promise<any>;
  7828. /**
  7829. * Listens for events on this task.
  7830. *
  7831. * Events have three callback functions (referred to as `next`, `error`, and
  7832. * `complete`).
  7833. *
  7834. * If only the event is passed, a function that can be used to register the
  7835. * callbacks is returned. Otherwise, the callbacks are passed after the event.
  7836. *
  7837. * Callbacks can be passed either as three separate arguments <em>or</em> as the
  7838. * `next`, `error`, and `complete` properties of an object. Any of the three
  7839. * callbacks is optional, as long as at least one is specified. In addition,
  7840. * when you add your callbacks, you get a function back. You can call this
  7841. * function to unregister the associated callbacks.
  7842. *
  7843. * @example **Pass callbacks separately or in an object.**
  7844. * ```javascript
  7845. * var next = function(snapshot) {};
  7846. * var error = function(error) {};
  7847. * var complete = function() {};
  7848. *
  7849. * // The first example.
  7850. * uploadTask.on(
  7851. * firebase.storage.TaskEvent.STATE_CHANGED,
  7852. * next,
  7853. * error,
  7854. * complete);
  7855. *
  7856. * // This is equivalent to the first example.
  7857. * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, {
  7858. * 'next': next,
  7859. * 'error': error,
  7860. * 'complete': complete
  7861. * });
  7862. *
  7863. * // This is equivalent to the first example.
  7864. * var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
  7865. * subscribe(next, error, complete);
  7866. *
  7867. * // This is equivalent to the first example.
  7868. * var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
  7869. * subscribe({
  7870. * 'next': next,
  7871. * 'error': error,
  7872. * 'complete': complete
  7873. * });
  7874. * ```
  7875. *
  7876. * @example **Any callback is optional.**
  7877. * ```javascript
  7878. * // Just listening for completion, this is legal.
  7879. * uploadTask.on(
  7880. * firebase.storage.TaskEvent.STATE_CHANGED,
  7881. * null,
  7882. * null,
  7883. * function() {
  7884. * console.log('upload complete!');
  7885. * });
  7886. *
  7887. * // Just listening for progress/state changes, this is legal.
  7888. * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, function(snapshot) {
  7889. * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
  7890. * console.log(percent + "% done");
  7891. * });
  7892. *
  7893. * // This is also legal.
  7894. * uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, {
  7895. * 'complete': function() {
  7896. * console.log('upload complete!');
  7897. * }
  7898. * });
  7899. * ```
  7900. *
  7901. * @example **Use the returned function to remove callbacks.**
  7902. * ```javascript
  7903. * var unsubscribe = uploadTask.on(
  7904. * firebase.storage.TaskEvent.STATE_CHANGED,
  7905. * function(snapshot) {
  7906. * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
  7907. * console.log(percent + "% done");
  7908. * // Stop after receiving one update.
  7909. * unsubscribe();
  7910. * });
  7911. *
  7912. * // This code is equivalent to the above.
  7913. * var handle = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
  7914. * unsubscribe = handle(function(snapshot) {
  7915. * var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
  7916. * console.log(percent + "% done");
  7917. * // Stop after receiving one update.
  7918. * unsubscribe();
  7919. * });
  7920. * ```
  7921. *
  7922. * @param event The event to listen for.
  7923. * @param nextOrObserver
  7924. * The `next` function, which gets called for each item in
  7925. * the event stream, or an observer object with some or all of these three
  7926. * properties (`next`, `error`, `complete`).
  7927. * @param error A function that gets called with a `FirebaseStorageError`
  7928. * if the event stream ends due to an error.
  7929. * @param complete A function that gets called if the
  7930. * event stream ends normally.
  7931. * @return
  7932. * If only the event argument is passed, returns a function you can use to
  7933. * add callbacks (see the examples above). If more than just the event
  7934. * argument is passed, returns a function you can call to unregister the
  7935. * callbacks.
  7936. */
  7937. on(
  7938. event: firebase.storage.TaskEvent,
  7939. nextOrObserver?:
  7940. | StorageObserver<UploadTaskSnapshot>
  7941. | null
  7942. | ((snapshot: UploadTaskSnapshot) => any),
  7943. error?: ((error: FirebaseStorageError) => any) | null,
  7944. complete?: firebase.Unsubscribe | null
  7945. ): Function;
  7946. /**
  7947. * Pauses a running task. Has no effect on a paused or failed task.
  7948. * @return True if the pause had an effect.
  7949. */
  7950. pause(): boolean;
  7951. /**
  7952. * Resumes a paused task. Has no effect on a running or failed task.
  7953. * @return True if the resume had an effect.
  7954. */
  7955. resume(): boolean;
  7956. /**
  7957. * A snapshot of the current task state.
  7958. */
  7959. snapshot: firebase.storage.UploadTaskSnapshot;
  7960. /**
  7961. * This object behaves like a Promise, and resolves with its snapshot data when
  7962. * the upload completes.
  7963. * @param onFulfilled
  7964. * The fulfillment callback. Promise chaining works as normal.
  7965. * @param onRejected The rejection callback.
  7966. */
  7967. then(
  7968. onFulfilled?:
  7969. | ((snapshot: firebase.storage.UploadTaskSnapshot) => any)
  7970. | null,
  7971. onRejected?: ((error: FirebaseStorageError) => any) | null
  7972. ): Promise<any>;
  7973. }
  7974. /**
  7975. * Holds data about the current state of the upload task.
  7976. */
  7977. interface UploadTaskSnapshot {
  7978. /**
  7979. * The number of bytes that have been successfully uploaded so far.
  7980. */
  7981. bytesTransferred: number;
  7982. /**
  7983. * Before the upload completes, contains the metadata sent to the server.
  7984. * After the upload completes, contains the metadata sent back from the server.
  7985. */
  7986. metadata: firebase.storage.FullMetadata;
  7987. /**
  7988. * The reference that spawned this snapshot's upload task.
  7989. */
  7990. ref: firebase.storage.Reference;
  7991. /**
  7992. * The current state of the task.
  7993. */
  7994. state: firebase.storage.TaskState;
  7995. /**
  7996. * The task of which this is a snapshot.
  7997. */
  7998. task: firebase.storage.UploadTask;
  7999. /**
  8000. * The total number of bytes to be uploaded.
  8001. */
  8002. totalBytes: number;
  8003. }
  8004. }
  8005. declare namespace firebase.firestore {
  8006. /**
  8007. * Document data (for use with `DocumentReference.set()`) consists of fields
  8008. * mapped to values.
  8009. */
  8010. export type DocumentData = { [field: string]: any };
  8011. /**
  8012. * Update data (for use with `DocumentReference.update()`) consists of field
  8013. * paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
  8014. * reference nested fields within the document.
  8015. */
  8016. export type UpdateData = { [fieldPath: string]: any };
  8017. /**
  8018. * Constant used to indicate the LRU garbage collection should be disabled.
  8019. * Set this value as the `cacheSizeBytes` on the settings passed to the
  8020. * `Firestore` instance.
  8021. */
  8022. export const CACHE_SIZE_UNLIMITED: number;
  8023. /**
  8024. * Specifies custom configurations for your Cloud Firestore instance.
  8025. * You must set these before invoking any other methods.
  8026. */
  8027. export interface Settings {
  8028. /** The hostname to connect to. */
  8029. host?: string;
  8030. /** Whether to use SSL when connecting. */
  8031. ssl?: boolean;
  8032. /**
  8033. * An approximate cache size threshold for the on-disk data. If the cache grows beyond this
  8034. * size, Firestore will start removing data that hasn't been recently used. The size is not a
  8035. * guarantee that the cache will stay below that size, only that if the cache exceeds the given
  8036. * size, cleanup will be attempted.
  8037. *
  8038. * The default value is 40 MB. The threshold must be set to at least 1 MB, and can be set to
  8039. * CACHE_SIZE_UNLIMITED to disable garbage collection.
  8040. */
  8041. cacheSizeBytes?: number;
  8042. /**
  8043. * Forces the SDKs underlying network transport (WebChannel) to use
  8044. * long-polling. Each response from the backend will be closed immediately
  8045. * after the backend sends data (by default responses are kept open in
  8046. * case the backend has more data to send). This avoids incompatibility
  8047. * issues with certain proxies, antivirus software, etc. that incorrectly
  8048. * buffer traffic indefinitely. Use of this option will cause some
  8049. * performance degradation though.
  8050. *
  8051. * This setting cannot be used with `experimentalAutoDetectLongPolling` and
  8052. * may be removed in a future release. If you find yourself using it to
  8053. * work around a specific network reliability issue, please tell us about
  8054. * it in https://github.com/firebase/firebase-js-sdk/issues/1674.
  8055. *
  8056. * @webonly
  8057. */
  8058. experimentalForceLongPolling?: boolean;
  8059. /**
  8060. * Configures the SDK's underlying transport (WebChannel) to automatically detect if
  8061. * long-polling should be used. This is very similar to `experimentalForceLongPolling`,
  8062. * but only uses long-polling if required.
  8063. *
  8064. * This setting will likely be enabled by default in future releases and cannot be
  8065. * combined with `experimentalForceLongPolling`.
  8066. *
  8067. * @webonly
  8068. */
  8069. experimentalAutoDetectLongPolling?: boolean;
  8070. /**
  8071. * Whether to skip nested properties that are set to `undefined` during
  8072. * object serialization. If set to `true`, these properties are skipped
  8073. * and not written to Firestore. If set to `false` or omitted, the SDK
  8074. * throws an exception when it encounters properties of type `undefined`.
  8075. */
  8076. ignoreUndefinedProperties?: boolean;
  8077. /**
  8078. * Whether to merge the provided settings with the existing settings. If
  8079. * set to `true`, the settings are merged with existing settings. If
  8080. * set to `false` or left unset, the settings replace the existing
  8081. * settings.
  8082. */
  8083. merge?: boolean;
  8084. }
  8085. /**
  8086. * Settings that can be passed to Firestore.enablePersistence() to configure
  8087. * Firestore persistence.
  8088. */
  8089. export interface PersistenceSettings {
  8090. /**
  8091. * Whether to synchronize the in-memory state of multiple tabs. Setting this
  8092. * to `true` in all open tabs enables shared access to local persistence,
  8093. * shared execution of queries and latency-compensated local document updates
  8094. * across all connected instances.
  8095. *
  8096. * To enable this mode, `synchronizeTabs:true` needs to be set globally in all
  8097. * active tabs. If omitted or set to 'false', `enablePersistence()` will fail
  8098. * in all but the first tab.
  8099. */
  8100. synchronizeTabs?: boolean;
  8101. /**
  8102. * Whether to force enable persistence for the client. This cannot be used
  8103. * with `synchronizeTabs:true` and is primarily intended for use with Web
  8104. * Workers. Setting this to `true` will enable persistence, but cause other
  8105. * tabs using persistence to fail.
  8106. *
  8107. * This setting may be removed in a future release. If you find yourself
  8108. * using it for a specific use case or run into any issues, please tell us
  8109. * about it in
  8110. * https://github.com/firebase/firebase-js-sdk/issues/983.
  8111. */
  8112. experimentalForceOwningTab?: boolean;
  8113. }
  8114. export type LogLevel = 'debug' | 'error' | 'silent';
  8115. /**
  8116. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  8117. *
  8118. * @param logLevel
  8119. * The verbosity you set for activity and error logging. Can be any of
  8120. * the following values:
  8121. *
  8122. * <ul>
  8123. * <li><code>debug</code> for the most verbose logging level, primarily for
  8124. * debugging.</li>
  8125. * <li><code>error</code> to log errors only.</li>
  8126. * <li><code>silent</code> to turn off logging.</li>
  8127. * </ul>
  8128. */
  8129. export function setLogLevel(logLevel: LogLevel): void;
  8130. /**
  8131. * Converter used by `withConverter()` to transform user objects of type T
  8132. * into Firestore data.
  8133. *
  8134. * Using the converter allows you to specify generic type arguments when
  8135. * storing and retrieving objects from Firestore.
  8136. *
  8137. * @example
  8138. * ```typescript
  8139. * class Post {
  8140. * constructor(readonly title: string, readonly author: string) {}
  8141. *
  8142. * toString(): string {
  8143. * return this.title + ', by ' + this.author;
  8144. * }
  8145. * }
  8146. *
  8147. * const postConverter = {
  8148. * toFirestore(post: Post): firebase.firestore.DocumentData {
  8149. * return {title: post.title, author: post.author};
  8150. * },
  8151. * fromFirestore(
  8152. * snapshot: firebase.firestore.QueryDocumentSnapshot,
  8153. * options: firebase.firestore.SnapshotOptions
  8154. * ): Post {
  8155. * const data = snapshot.data(options)!;
  8156. * return new Post(data.title, data.author);
  8157. * }
  8158. * };
  8159. *
  8160. * const postSnap = await firebase.firestore()
  8161. * .collection('posts')
  8162. * .withConverter(postConverter)
  8163. * .doc().get();
  8164. * const post = postSnap.data();
  8165. * if (post !== undefined) {
  8166. * post.title; // string
  8167. * post.toString(); // Should be defined
  8168. * post.someNonExistentProperty; // TS error
  8169. * }
  8170. * ```
  8171. */
  8172. export interface FirestoreDataConverter<T> {
  8173. /**
  8174. * Called by the Firestore SDK to convert a custom model object of type T
  8175. * into a plain Javascript object (suitable for writing directly to the
  8176. * Firestore database). To use `set()` with `merge` and `mergeFields`,
  8177. * `toFirestore()` must be defined with `Partial<T>`.
  8178. */
  8179. toFirestore(modelObject: T): DocumentData;
  8180. toFirestore(modelObject: Partial<T>, options: SetOptions): DocumentData;
  8181. /**
  8182. * Called by the Firestore SDK to convert Firestore data into an object of
  8183. * type T. You can access your data by calling: `snapshot.data(options)`.
  8184. *
  8185. * @param snapshot A QueryDocumentSnapshot containing your data and metadata.
  8186. * @param options The SnapshotOptions from the initial call to `data()`.
  8187. */
  8188. fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): T;
  8189. }
  8190. /**
  8191. * The Cloud Firestore service interface.
  8192. *
  8193. * Do not call this constructor directly. Instead, use
  8194. * {@link firebase.firestore `firebase.firestore()`}.
  8195. */
  8196. export class Firestore {
  8197. private constructor();
  8198. /**
  8199. * Specifies custom settings to be used to configure the `Firestore`
  8200. * instance. Must be set before invoking any other methods.
  8201. *
  8202. * @param settings The settings to use.
  8203. */
  8204. settings(settings: Settings): void;
  8205. /**
  8206. * Modify this instance to communicate with the Cloud Firestore emulator.
  8207. *
  8208. * <p>Note: this must be called before this instance has been used to do any operations.
  8209. *
  8210. * @param host the emulator host (ex: localhost).
  8211. * @param port the emulator port (ex: 9000).
  8212. * @param options.mockUserToken - the mock auth token to use for unit
  8213. * testing Security Rules.
  8214. */
  8215. useEmulator(
  8216. host: string,
  8217. port: number,
  8218. options?: {
  8219. mockUserToken?: EmulatorMockTokenOptions | string;
  8220. }
  8221. ): void;
  8222. /**
  8223. * Attempts to enable persistent storage, if possible.
  8224. *
  8225. * Must be called before any other methods (other than settings() and
  8226. * clearPersistence()).
  8227. *
  8228. * If this fails, enablePersistence() will reject the promise it returns.
  8229. * Note that even after this failure, the firestore instance will remain
  8230. * usable, however offline persistence will be disabled.
  8231. *
  8232. * There are several reasons why this can fail, which can be identified by
  8233. * the `code` on the error.
  8234. *
  8235. * * failed-precondition: The app is already open in another browser tab.
  8236. * * unimplemented: The browser is incompatible with the offline
  8237. * persistence implementation.
  8238. *
  8239. * @param settings Optional settings object to configure persistence.
  8240. * @return A promise that represents successfully enabling persistent
  8241. * storage.
  8242. */
  8243. enablePersistence(settings?: PersistenceSettings): Promise<void>;
  8244. /**
  8245. * Gets a `CollectionReference` instance that refers to the collection at
  8246. * the specified path.
  8247. *
  8248. * @param collectionPath A slash-separated path to a collection.
  8249. * @return The `CollectionReference` instance.
  8250. */
  8251. collection(collectionPath: string): CollectionReference<DocumentData>;
  8252. /**
  8253. * Gets a `DocumentReference` instance that refers to the document at the
  8254. * specified path.
  8255. *
  8256. * @param documentPath A slash-separated path to a document.
  8257. * @return The `DocumentReference` instance.
  8258. */
  8259. doc(documentPath: string): DocumentReference<DocumentData>;
  8260. /**
  8261. * Creates and returns a new Query that includes all documents in the
  8262. * database that are contained in a collection or subcollection with the
  8263. * given collectionId.
  8264. *
  8265. * @param collectionId Identifies the collections to query over. Every
  8266. * collection or subcollection with this ID as the last segment of its path
  8267. * will be included. Cannot contain a slash.
  8268. * @return The created Query.
  8269. */
  8270. collectionGroup(collectionId: string): Query<DocumentData>;
  8271. /**
  8272. * Executes the given `updateFunction` and then attempts to commit the changes
  8273. * applied within the transaction. If any document read within the transaction
  8274. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  8275. * commit after 5 attempts, the transaction fails.
  8276. *
  8277. * The maximum number of writes allowed in a single transaction is 500, but
  8278. * note that each usage of `FieldValue.serverTimestamp()`,
  8279. * `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or
  8280. * `FieldValue.increment()` inside a transaction counts as an additional write.
  8281. *
  8282. * @param updateFunction
  8283. * The function to execute within the transaction context.
  8284. *
  8285. * @return
  8286. * If the transaction completed successfully or was explicitly aborted
  8287. * (the `updateFunction` returned a failed promise),
  8288. * the promise returned by the updateFunction is returned here. Else, if the
  8289. * transaction failed, a rejected promise with the corresponding failure
  8290. * error will be returned.
  8291. */
  8292. runTransaction<T>(
  8293. updateFunction: (transaction: Transaction) => Promise<T>
  8294. ): Promise<T>;
  8295. /**
  8296. * Creates a write batch, used for performing multiple writes as a single
  8297. * atomic operation. The maximum number of writes allowed in a single WriteBatch
  8298. * is 500, but note that each usage of `FieldValue.serverTimestamp()`,
  8299. * `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or
  8300. * `FieldValue.increment()` inside a WriteBatch counts as an additional write.
  8301. *
  8302. * @return
  8303. * A `WriteBatch` that can be used to atomically execute multiple writes.
  8304. */
  8305. batch(): WriteBatch;
  8306. /**
  8307. * The {@link firebase.app.App app} associated with this `Firestore` service
  8308. * instance.
  8309. */
  8310. app: firebase.app.App;
  8311. /**
  8312. * Clears the persistent storage. This includes pending writes and cached
  8313. * documents.
  8314. *
  8315. * Must be called while the firestore instance is not started (after the app
  8316. * is shutdown or when the app is first initialized). On startup, this
  8317. * method must be called before other methods (other than settings()). If
  8318. * the firestore instance is still running, the promise will be rejected
  8319. * with the error code of `failed-precondition`.
  8320. *
  8321. * Note: clearPersistence() is primarily intended to help write reliable
  8322. * tests that use Cloud Firestore. It uses an efficient mechanism for
  8323. * dropping existing data but does not attempt to securely overwrite or
  8324. * otherwise make cached data unrecoverable. For applications that are
  8325. * sensitive to the disclosure of cached data in between user sessions, we
  8326. * strongly recommend not enabling persistence at all.
  8327. *
  8328. * @return A promise that is resolved when the persistent storage is
  8329. * cleared. Otherwise, the promise is rejected with an error.
  8330. */
  8331. clearPersistence(): Promise<void>;
  8332. /**
  8333. * Re-enables use of the network for this Firestore instance after a prior
  8334. * call to {@link firebase.firestore.Firestore.disableNetwork
  8335. * `disableNetwork()`}.
  8336. *
  8337. * @return A promise that is resolved once the network has been
  8338. * enabled.
  8339. */
  8340. enableNetwork(): Promise<void>;
  8341. /**
  8342. * Disables network usage for this instance. It can be re-enabled via
  8343. * {@link firebase.firestore.Firestore.enableNetwork `enableNetwork()`}. While
  8344. * the network is disabled, any snapshot listeners or get() calls will return
  8345. * results from cache, and any write operations will be queued until the network
  8346. * is restored.
  8347. *
  8348. * @return A promise that is resolved once the network has been
  8349. * disabled.
  8350. */
  8351. disableNetwork(): Promise<void>;
  8352. /**
  8353. * Waits until all currently pending writes for the active user have been acknowledged by the
  8354. * backend.
  8355. *
  8356. * The returned Promise resolves immediately if there are no outstanding writes. Otherwise, the
  8357. * Promise waits for all previously issued writes (including those written in a previous app
  8358. * session), but it does not wait for writes that were added after the method is called. If you
  8359. * want to wait for additional writes, call `waitForPendingWrites()` again.
  8360. *
  8361. * Any outstanding `waitForPendingWrites()` Promises are rejected during user changes.
  8362. *
  8363. * @return A Promise which resolves when all currently pending writes have been
  8364. * acknowledged by the backend.
  8365. */
  8366. waitForPendingWrites(): Promise<void>;
  8367. /**
  8368. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
  8369. * event indicates that all listeners affected by a given change have fired,
  8370. * even if a single server-generated change affects multiple listeners.
  8371. *
  8372. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
  8373. * with each other, but does not relate to whether those snapshots are in sync
  8374. * with the server. Use SnapshotMetadata in the individual listeners to
  8375. * determine if a snapshot is from the cache or the server.
  8376. *
  8377. * @param observer A single object containing `next` and `error` callbacks.
  8378. * @return An unsubscribe function that can be called to cancel the snapshot
  8379. * listener.
  8380. */
  8381. onSnapshotsInSync(observer: {
  8382. next?: (value: void) => void;
  8383. error?: (error: FirestoreError) => void;
  8384. complete?: () => void;
  8385. }): () => void;
  8386. /**
  8387. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
  8388. * event indicates that all listeners affected by a given change have fired,
  8389. * even if a single server-generated change affects multiple listeners.
  8390. *
  8391. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
  8392. * with each other, but does not relate to whether those snapshots are in sync
  8393. * with the server. Use SnapshotMetadata in the individual listeners to
  8394. * determine if a snapshot is from the cache or the server.
  8395. *
  8396. * @param onSync A callback to be called every time all snapshot listeners are
  8397. * in sync with each other.
  8398. * @return An unsubscribe function that can be called to cancel the snapshot
  8399. * listener.
  8400. */
  8401. onSnapshotsInSync(onSync: () => void): () => void;
  8402. /**
  8403. * Terminates this Firestore instance.
  8404. *
  8405. * After calling `terminate()` only the `clearPersistence()` method may be used. Any other method
  8406. * will throw a `FirestoreError`.
  8407. *
  8408. * To restart after termination, create a new instance of FirebaseFirestore with
  8409. * `firebase.firestore()`.
  8410. *
  8411. * Termination does not cancel any pending writes, and any promises that are awaiting a response
  8412. * from the server will not be resolved. If you have persistence enabled, the next time you
  8413. * start this instance, it will resume sending these writes to the server.
  8414. *
  8415. * Note: Under normal circumstances, calling `terminate()` is not required. This
  8416. * method is useful only when you want to force this instance to release all of its resources or
  8417. * in combination with `clearPersistence()` to ensure that all local state is destroyed
  8418. * between test runs.
  8419. *
  8420. * @return A promise that is resolved when the instance has been successfully terminated.
  8421. */
  8422. terminate(): Promise<void>;
  8423. /**
  8424. * Loads a Firestore bundle into the local cache.
  8425. *
  8426. * @param bundleData
  8427. * An object representing the bundle to be loaded. Valid objects are `ArrayBuffer`,
  8428. * `ReadableStream<Uint8Array>` or `string`.
  8429. *
  8430. * @return
  8431. * A `LoadBundleTask` object, which notifies callers with progress updates, and completion
  8432. * or error events. It can be used as a `Promise<LoadBundleTaskProgress>`.
  8433. */
  8434. loadBundle(
  8435. bundleData: ArrayBuffer | ReadableStream<Uint8Array> | string
  8436. ): LoadBundleTask;
  8437. /**
  8438. * Reads a Firestore `Query` from local cache, identified by the given name.
  8439. *
  8440. * The named queries are packaged into bundles on the server side (along
  8441. * with resulting documents), and loaded to local cache using `loadBundle`. Once in local
  8442. * cache, use this method to extract a `Query` by name.
  8443. */
  8444. namedQuery(name: string): Promise<Query<DocumentData> | null>;
  8445. /**
  8446. * @hidden
  8447. */
  8448. INTERNAL: { delete: () => Promise<void> };
  8449. }
  8450. /**
  8451. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  8452. * loading, as well as task completion and error events.
  8453. *
  8454. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  8455. */
  8456. export interface LoadBundleTask extends PromiseLike<LoadBundleTaskProgress> {
  8457. /**
  8458. * Registers functions to listen to bundle loading progress events.
  8459. * @param next
  8460. * Called when there is a progress update from bundle loading. Typically `next` calls occur
  8461. * each time a Firestore document is loaded from the bundle.
  8462. * @param error
  8463. * Called when an error occurs during bundle loading. The task aborts after reporting the
  8464. * error, and there should be no more updates after this.
  8465. * @param complete
  8466. * Called when the loading task is complete.
  8467. */
  8468. onProgress(
  8469. next?: (progress: LoadBundleTaskProgress) => any,
  8470. error?: (error: Error) => any,
  8471. complete?: () => void
  8472. ): void;
  8473. /**
  8474. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  8475. *
  8476. * @param onFulfilled
  8477. * Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  8478. * The update will always have its `taskState` set to `"Success"`.
  8479. * @param onRejected
  8480. * Called when an error occurs during bundle loading.
  8481. */
  8482. then<T, R>(
  8483. onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>,
  8484. onRejected?: (a: Error) => R | PromiseLike<R>
  8485. ): Promise<T | R>;
  8486. /**
  8487. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  8488. *
  8489. * @param onRejected
  8490. * Called when an error occurs during bundle loading.
  8491. */
  8492. catch<R>(
  8493. onRejected: (a: Error) => R | PromiseLike<R>
  8494. ): Promise<R | LoadBundleTaskProgress>;
  8495. }
  8496. /**
  8497. * Represents a progress update or a final state from loading bundles.
  8498. */
  8499. export interface LoadBundleTaskProgress {
  8500. /** How many documents have been loaded. */
  8501. documentsLoaded: number;
  8502. /** How many documents are in the bundle being loaded. */
  8503. totalDocuments: number;
  8504. /** How many bytes have been loaded. */
  8505. bytesLoaded: number;
  8506. /** How many bytes are in the bundle being loaded. */
  8507. totalBytes: number;
  8508. /** Current task state. */
  8509. taskState: TaskState;
  8510. }
  8511. /**
  8512. * Represents the state of bundle loading tasks.
  8513. *
  8514. * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will
  8515. * be no more updates after they are reported.
  8516. */
  8517. export type TaskState = 'Error' | 'Running' | 'Success';
  8518. /**
  8519. * An immutable object representing a geo point in Firestore. The geo point
  8520. * is represented as latitude/longitude pair.
  8521. *
  8522. * Latitude values are in the range of [-90, 90].
  8523. * Longitude values are in the range of [-180, 180].
  8524. */
  8525. export class GeoPoint {
  8526. /**
  8527. * Creates a new immutable GeoPoint object with the provided latitude and
  8528. * longitude values.
  8529. * @param latitude The latitude as number between -90 and 90.
  8530. * @param longitude The longitude as number between -180 and 180.
  8531. */
  8532. constructor(latitude: number, longitude: number);
  8533. /**
  8534. * The latitude of this GeoPoint instance.
  8535. */
  8536. readonly latitude: number;
  8537. /**
  8538. * The longitude of this GeoPoint instance.
  8539. */
  8540. readonly longitude: number;
  8541. /**
  8542. * Returns true if this `GeoPoint` is equal to the provided one.
  8543. *
  8544. * @param other The `GeoPoint` to compare against.
  8545. * @return true if this `GeoPoint` is equal to the provided one.
  8546. */
  8547. isEqual(other: GeoPoint): boolean;
  8548. }
  8549. /**
  8550. * A Timestamp represents a point in time independent of any time zone or
  8551. * calendar, represented as seconds and fractions of seconds at nanosecond
  8552. * resolution in UTC Epoch time.
  8553. *
  8554. * It is encoded using the Proleptic Gregorian
  8555. * Calendar which extends the Gregorian calendar backwards to year one. It is
  8556. * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are
  8557. * "smeared" so that no leap second table is needed for interpretation. Range is
  8558. * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
  8559. *
  8560. * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto
  8561. */
  8562. export class Timestamp {
  8563. /**
  8564. * Creates a new timestamp.
  8565. *
  8566. * @param seconds The number of seconds of UTC time since Unix epoch
  8567. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  8568. * 9999-12-31T23:59:59Z inclusive.
  8569. * @param nanoseconds The non-negative fractions of a second at nanosecond
  8570. * resolution. Negative second values with fractions must still have
  8571. * non-negative nanoseconds values that count forward in time. Must be
  8572. * from 0 to 999,999,999 inclusive.
  8573. */
  8574. constructor(seconds: number, nanoseconds: number);
  8575. /**
  8576. * Creates a new timestamp with the current date, with millisecond precision.
  8577. *
  8578. * @return a new timestamp representing the current date.
  8579. */
  8580. static now(): Timestamp;
  8581. /**
  8582. * Creates a new timestamp from the given date.
  8583. *
  8584. * @param date The date to initialize the `Timestamp` from.
  8585. * @return A new `Timestamp` representing the same point in time as the given
  8586. * date.
  8587. */
  8588. static fromDate(date: Date): Timestamp;
  8589. /**
  8590. * Creates a new timestamp from the given number of milliseconds.
  8591. *
  8592. * @param milliseconds Number of milliseconds since Unix epoch
  8593. * 1970-01-01T00:00:00Z.
  8594. * @return A new `Timestamp` representing the same point in time as the given
  8595. * number of milliseconds.
  8596. */
  8597. static fromMillis(milliseconds: number): Timestamp;
  8598. readonly seconds: number;
  8599. readonly nanoseconds: number;
  8600. /**
  8601. * Convert a Timestamp to a JavaScript `Date` object. This conversion causes
  8602. * a loss of precision since `Date` objects only support millisecond precision.
  8603. *
  8604. * @return JavaScript `Date` object representing the same point in time as
  8605. * this `Timestamp`, with millisecond precision.
  8606. */
  8607. toDate(): Date;
  8608. /**
  8609. * Convert a timestamp to a numeric timestamp (in milliseconds since epoch).
  8610. * This operation causes a loss of precision.
  8611. *
  8612. * @return The point in time corresponding to this timestamp, represented as
  8613. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  8614. */
  8615. toMillis(): number;
  8616. /**
  8617. * Returns true if this `Timestamp` is equal to the provided one.
  8618. *
  8619. * @param other The `Timestamp` to compare against.
  8620. * @return true if this `Timestamp` is equal to the provided one.
  8621. */
  8622. isEqual(other: Timestamp): boolean;
  8623. /**
  8624. * Converts this object to a primitive string, which allows Timestamp objects to be compared
  8625. * using the `>`, `<=`, `>=` and `>` operators.
  8626. */
  8627. valueOf(): string;
  8628. }
  8629. /**
  8630. * An immutable object representing an array of bytes.
  8631. */
  8632. export class Blob {
  8633. private constructor();
  8634. /**
  8635. * Creates a new Blob from the given Base64 string, converting it to
  8636. * bytes.
  8637. *
  8638. * @param base64
  8639. * The Base64 string used to create the Blob object.
  8640. */
  8641. static fromBase64String(base64: string): Blob;
  8642. /**
  8643. * Creates a new Blob from the given Uint8Array.
  8644. *
  8645. * @param array
  8646. * The Uint8Array used to create the Blob object.
  8647. */
  8648. static fromUint8Array(array: Uint8Array): Blob;
  8649. /**
  8650. * Returns the bytes of a Blob as a Base64-encoded string.
  8651. *
  8652. * @return
  8653. * The Base64-encoded string created from the Blob object.
  8654. */
  8655. public toBase64(): string;
  8656. /**
  8657. * Returns the bytes of a Blob in a new Uint8Array.
  8658. *
  8659. * @return
  8660. * The Uint8Array created from the Blob object.
  8661. */
  8662. public toUint8Array(): Uint8Array;
  8663. /**
  8664. * Returns true if this `Blob` is equal to the provided one.
  8665. *
  8666. * @param other The `Blob` to compare against.
  8667. * @return true if this `Blob` is equal to the provided one.
  8668. */
  8669. isEqual(other: Blob): boolean;
  8670. }
  8671. /**
  8672. * A reference to a transaction.
  8673. * The `Transaction` object passed to a transaction's updateFunction provides
  8674. * the methods to read and write data within the transaction context. See
  8675. * `Firestore.runTransaction()`.
  8676. */
  8677. export class Transaction {
  8678. private constructor();
  8679. /**
  8680. * Reads the document referenced by the provided `DocumentReference.`
  8681. *
  8682. * @param documentRef A reference to the document to be read.
  8683. * @return A DocumentSnapshot for the read data.
  8684. */
  8685. get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  8686. /**
  8687. * Writes to the document referred to by the provided `DocumentReference`.
  8688. * If the document does not exist yet, it will be created. If you pass
  8689. * `SetOptions`, the provided data can be merged into the existing document.
  8690. *
  8691. * @param documentRef A reference to the document to be set.
  8692. * @param data An object of the fields and values for the document.
  8693. * @param options An object to configure the set behavior.
  8694. * @return This `Transaction` instance. Used for chaining method calls.
  8695. */
  8696. set<T>(
  8697. documentRef: DocumentReference<T>,
  8698. data: Partial<T>,
  8699. options: SetOptions
  8700. ): Transaction;
  8701. /**
  8702. * Writes to the document referred to by the provided `DocumentReference`.
  8703. * If the document does not exist yet, it will be created. If you pass
  8704. * `SetOptions`, the provided data can be merged into the existing document.
  8705. *
  8706. * @param documentRef A reference to the document to be set.
  8707. * @param data An object of the fields and values for the document.
  8708. * @return This `Transaction` instance. Used for chaining method calls.
  8709. */
  8710. set<T>(documentRef: DocumentReference<T>, data: T): Transaction;
  8711. /**
  8712. * Updates fields in the document referred to by the provided
  8713. * `DocumentReference`. The update will fail if applied to a document that
  8714. * does not exist.
  8715. *
  8716. * @param documentRef A reference to the document to be updated.
  8717. * @param data An object containing the fields and values with which to
  8718. * update the document. Fields can contain dots to reference nested fields
  8719. * within the document.
  8720. * @return This `Transaction` instance. Used for chaining method calls.
  8721. */
  8722. update(documentRef: DocumentReference<any>, data: UpdateData): Transaction;
  8723. /**
  8724. * Updates fields in the document referred to by the provided
  8725. * `DocumentReference`. The update will fail if applied to a document that
  8726. * does not exist.
  8727. *
  8728. * Nested fields can be updated by providing dot-separated field path
  8729. * strings or by providing FieldPath objects.
  8730. *
  8731. * @param documentRef A reference to the document to be updated.
  8732. * @param field The first field to update.
  8733. * @param value The first value.
  8734. * @param moreFieldsAndValues Additional key/value pairs.
  8735. * @return A Promise resolved once the data has been successfully written
  8736. * to the backend (Note that it won't resolve while you're offline).
  8737. */
  8738. update(
  8739. documentRef: DocumentReference<any>,
  8740. field: string | FieldPath,
  8741. value: any,
  8742. ...moreFieldsAndValues: any[]
  8743. ): Transaction;
  8744. /**
  8745. * Deletes the document referred to by the provided `DocumentReference`.
  8746. *
  8747. * @param documentRef A reference to the document to be deleted.
  8748. * @return This `Transaction` instance. Used for chaining method calls.
  8749. */
  8750. delete(documentRef: DocumentReference<any>): Transaction;
  8751. }
  8752. /**
  8753. * A write batch, used to perform multiple writes as a single atomic unit.
  8754. *
  8755. * A `WriteBatch` object can be acquired by calling `Firestore.batch()`. It
  8756. * provides methods for adding writes to the write batch. None of the
  8757. * writes will be committed (or visible locally) until `WriteBatch.commit()`
  8758. * is called.
  8759. *
  8760. * Unlike transactions, write batches are persisted offline and therefore are
  8761. * preferable when you don't need to condition your writes on read data.
  8762. */
  8763. export class WriteBatch {
  8764. private constructor();
  8765. /**
  8766. * Writes to the document referred to by the provided `DocumentReference`.
  8767. * If the document does not exist yet, it will be created. If you pass
  8768. * `SetOptions`, the provided data can be merged into the existing document.
  8769. *
  8770. * @param documentRef A reference to the document to be set.
  8771. * @param data An object of the fields and values for the document.
  8772. * @param options An object to configure the set behavior.
  8773. * @return This `WriteBatch` instance. Used for chaining method calls.
  8774. */
  8775. set<T>(
  8776. documentRef: DocumentReference<T>,
  8777. data: Partial<T>,
  8778. options: SetOptions
  8779. ): WriteBatch;
  8780. /**
  8781. * Writes to the document referred to by the provided `DocumentReference`.
  8782. * If the document does not exist yet, it will be created. If you pass
  8783. * `SetOptions`, the provided data can be merged into the existing document.
  8784. *
  8785. * @param documentRef A reference to the document to be set.
  8786. * @param data An object of the fields and values for the document.
  8787. * @return This `WriteBatch` instance. Used for chaining method calls.
  8788. */
  8789. set<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;
  8790. /**
  8791. * Updates fields in the document referred to by the provided
  8792. * `DocumentReference`. The update will fail if applied to a document that
  8793. * does not exist.
  8794. *
  8795. * @param documentRef A reference to the document to be updated.
  8796. * @param data An object containing the fields and values with which to
  8797. * update the document. Fields can contain dots to reference nested fields
  8798. * within the document.
  8799. * @return This `WriteBatch` instance. Used for chaining method calls.
  8800. */
  8801. update(documentRef: DocumentReference<any>, data: UpdateData): WriteBatch;
  8802. /**
  8803. * Updates fields in the document referred to by this `DocumentReference`.
  8804. * The update will fail if applied to a document that does not exist.
  8805. *
  8806. * Nested fields can be update by providing dot-separated field path strings
  8807. * or by providing FieldPath objects.
  8808. *
  8809. * @param documentRef A reference to the document to be updated.
  8810. * @param field The first field to update.
  8811. * @param value The first value.
  8812. * @param moreFieldsAndValues Additional key value pairs.
  8813. * @return A Promise resolved once the data has been successfully written
  8814. * to the backend (Note that it won't resolve while you're offline).
  8815. */
  8816. update(
  8817. documentRef: DocumentReference<any>,
  8818. field: string | FieldPath,
  8819. value: any,
  8820. ...moreFieldsAndValues: any[]
  8821. ): WriteBatch;
  8822. /**
  8823. * Deletes the document referred to by the provided `DocumentReference`.
  8824. *
  8825. * @param documentRef A reference to the document to be deleted.
  8826. * @return This `WriteBatch` instance. Used for chaining method calls.
  8827. */
  8828. delete(documentRef: DocumentReference<any>): WriteBatch;
  8829. /**
  8830. * Commits all of the writes in this write batch as a single atomic unit.
  8831. *
  8832. * @return A Promise resolved once all of the writes in the batch have been
  8833. * successfully written to the backend as an atomic unit. Note that it won't
  8834. * resolve while you're offline.
  8835. */
  8836. commit(): Promise<void>;
  8837. }
  8838. /**
  8839. * An options object that can be passed to `DocumentReference.onSnapshot()`,
  8840. * `Query.onSnapshot()` and `QuerySnapshot.docChanges()` to control which
  8841. * types of changes to include in the result set.
  8842. */
  8843. export interface SnapshotListenOptions {
  8844. /**
  8845. * Include a change even if only the metadata of the query or of a document
  8846. * changed. Default is false.
  8847. */
  8848. readonly includeMetadataChanges?: boolean;
  8849. }
  8850. /**
  8851. * An options object that configures the behavior of `set()` calls in
  8852. * {@link firebase.firestore.DocumentReference.set DocumentReference}, {@link
  8853. * firebase.firestore.WriteBatch.set WriteBatch} and {@link
  8854. * firebase.firestore.Transaction.set Transaction}. These calls can be
  8855. * configured to perform granular merges instead of overwriting the target
  8856. * documents in their entirety by providing a `SetOptions` with `merge: true`.
  8857. */
  8858. export interface SetOptions {
  8859. /**
  8860. * Changes the behavior of a set() call to only replace the values specified
  8861. * in its data argument. Fields omitted from the set() call remain
  8862. * untouched.
  8863. */
  8864. readonly merge?: boolean;
  8865. /**
  8866. * Changes the behavior of set() calls to only replace the specified field
  8867. * paths. Any field path that is not specified is ignored and remains
  8868. * untouched.
  8869. */
  8870. readonly mergeFields?: (string | FieldPath)[];
  8871. }
  8872. /**
  8873. * An options object that configures the behavior of `get()` calls on
  8874. * `DocumentReference` and `Query`. By providing a `GetOptions` object, these
  8875. * methods can be configured to fetch results only from the server, only from
  8876. * the local cache or attempt to fetch results from the server and fall back to
  8877. * the cache (which is the default).
  8878. */
  8879. export interface GetOptions {
  8880. /**
  8881. * Describes whether we should get from server or cache.
  8882. *
  8883. * Setting to `default` (or not setting at all), causes Firestore to try to
  8884. * retrieve an up-to-date (server-retrieved) snapshot, but fall back to
  8885. * returning cached data if the server can't be reached.
  8886. *
  8887. * Setting to `server` causes Firestore to avoid the cache, generating an
  8888. * error if the server cannot be reached. Note that the cache will still be
  8889. * updated if the server request succeeds. Also note that latency-compensation
  8890. * still takes effect, so any pending write operations will be visible in the
  8891. * returned data (merged into the server-provided data).
  8892. *
  8893. * Setting to `cache` causes Firestore to immediately return a value from the
  8894. * cache, ignoring the server completely (implying that the returned value
  8895. * may be stale with respect to the value on the server.) If there is no data
  8896. * in the cache to satisfy the `get()` call, `DocumentReference.get()` will
  8897. * return an error and `QuerySnapshot.get()` will return an empty
  8898. * `QuerySnapshot` with no documents.
  8899. */
  8900. readonly source?: 'default' | 'server' | 'cache';
  8901. }
  8902. /**
  8903. * A `DocumentReference` refers to a document location in a Firestore database
  8904. * and can be used to write, read, or listen to the location. The document at
  8905. * the referenced location may or may not exist. A `DocumentReference` can
  8906. * also be used to create a `CollectionReference` to a subcollection.
  8907. */
  8908. export class DocumentReference<T = DocumentData> {
  8909. private constructor();
  8910. /**
  8911. * The document's identifier within its collection.
  8912. */
  8913. readonly id: string;
  8914. /**
  8915. * The {@link firebase.firestore.Firestore} the document is in.
  8916. * This is useful for performing transactions, for example.
  8917. */
  8918. readonly firestore: Firestore;
  8919. /**
  8920. * The Collection this `DocumentReference` belongs to.
  8921. */
  8922. readonly parent: CollectionReference<T>;
  8923. /**
  8924. * A string representing the path of the referenced document (relative
  8925. * to the root of the database).
  8926. */
  8927. readonly path: string;
  8928. /**
  8929. * Gets a `CollectionReference` instance that refers to the collection at
  8930. * the specified path.
  8931. *
  8932. * @param collectionPath A slash-separated path to a collection.
  8933. * @return The `CollectionReference` instance.
  8934. */
  8935. collection(collectionPath: string): CollectionReference<DocumentData>;
  8936. /**
  8937. * Returns true if this `DocumentReference` is equal to the provided one.
  8938. *
  8939. * @param other The `DocumentReference` to compare against.
  8940. * @return true if this `DocumentReference` is equal to the provided one.
  8941. */
  8942. isEqual(other: DocumentReference<T>): boolean;
  8943. /**
  8944. * Writes to the document referred to by this `DocumentReference`. If the
  8945. * document does not yet exist, it will be created. If you pass
  8946. * `SetOptions`, the provided data can be merged into an existing document.
  8947. *
  8948. * @param data A map of the fields and values for the document.
  8949. * @param options An object to configure the set behavior.
  8950. * @return A Promise resolved once the data has been successfully written
  8951. * to the backend (Note that it won't resolve while you're offline).
  8952. */
  8953. set(data: Partial<T>, options: SetOptions): Promise<void>;
  8954. /**
  8955. * Writes to the document referred to by this `DocumentReference`. If the
  8956. * document does not yet exist, it will be created. If you pass
  8957. * `SetOptions`, the provided data can be merged into an existing document.
  8958. *
  8959. * @param data A map of the fields and values for the document.
  8960. * @return A Promise resolved once the data has been successfully written
  8961. * to the backend (Note that it won't resolve while you're offline).
  8962. */
  8963. set(data: T): Promise<void>;
  8964. /**
  8965. * Updates fields in the document referred to by this `DocumentReference`.
  8966. * The update will fail if applied to a document that does not exist.
  8967. *
  8968. * @param data An object containing the fields and values with which to
  8969. * update the document. Fields can contain dots to reference nested fields
  8970. * within the document.
  8971. * @return A Promise resolved once the data has been successfully written
  8972. * to the backend (Note that it won't resolve while you're offline).
  8973. */
  8974. update(data: UpdateData): Promise<void>;
  8975. /**
  8976. * Updates fields in the document referred to by this `DocumentReference`.
  8977. * The update will fail if applied to a document that does not exist.
  8978. *
  8979. * Nested fields can be updated by providing dot-separated field path
  8980. * strings or by providing FieldPath objects.
  8981. *
  8982. * @param field The first field to update.
  8983. * @param value The first value.
  8984. * @param moreFieldsAndValues Additional key value pairs.
  8985. * @return A Promise resolved once the data has been successfully written
  8986. * to the backend (Note that it won't resolve while you're offline).
  8987. */
  8988. update(
  8989. field: string | FieldPath,
  8990. value: any,
  8991. ...moreFieldsAndValues: any[]
  8992. ): Promise<void>;
  8993. /**
  8994. * Deletes the document referred to by this `DocumentReference`.
  8995. *
  8996. * @return A Promise resolved once the document has been successfully
  8997. * deleted from the backend (Note that it won't resolve while you're
  8998. * offline).
  8999. */
  9000. delete(): Promise<void>;
  9001. /**
  9002. * Reads the document referred to by this `DocumentReference`.
  9003. *
  9004. * Note: By default, get() attempts to provide up-to-date data when possible
  9005. * by waiting for data from the server, but it may return cached data or fail
  9006. * if you are offline and the server cannot be reached. This behavior can be
  9007. * altered via the `GetOptions` parameter.
  9008. *
  9009. * @param options An object to configure the get behavior.
  9010. * @return A Promise resolved with a DocumentSnapshot containing the
  9011. * current document contents.
  9012. */
  9013. get(options?: GetOptions): Promise<DocumentSnapshot<T>>;
  9014. /**
  9015. * Attaches a listener for DocumentSnapshot events. You may either pass
  9016. * individual `onNext` and `onError` callbacks or pass a single observer
  9017. * object with `next` and `error` callbacks.
  9018. *
  9019. * NOTE: Although an `onCompletion` callback can be provided, it will
  9020. * never be called because the snapshot stream is never-ending.
  9021. *
  9022. * @param observer A single object containing `next` and `error` callbacks.
  9023. * @return An unsubscribe function that can be called to cancel
  9024. * the snapshot listener.
  9025. */
  9026. onSnapshot(observer: {
  9027. next?: (snapshot: DocumentSnapshot<T>) => void;
  9028. error?: (error: FirestoreError) => void;
  9029. complete?: () => void;
  9030. }): () => void;
  9031. /**
  9032. * Attaches a listener for DocumentSnapshot events. You may either pass
  9033. * individual `onNext` and `onError` callbacks or pass a single observer
  9034. * object with `next` and `error` callbacks.
  9035. *
  9036. * NOTE: Although an `onCompletion` callback can be provided, it will
  9037. * never be called because the snapshot stream is never-ending.
  9038. *
  9039. * @param options Options controlling the listen behavior.
  9040. * @param observer A single object containing `next` and `error` callbacks.
  9041. * @return An unsubscribe function that can be called to cancel
  9042. * the snapshot listener.
  9043. */
  9044. onSnapshot(
  9045. options: SnapshotListenOptions,
  9046. observer: {
  9047. next?: (snapshot: DocumentSnapshot<T>) => void;
  9048. error?: (error: FirestoreError) => void;
  9049. complete?: () => void;
  9050. }
  9051. ): () => void;
  9052. /**
  9053. * Attaches a listener for DocumentSnapshot events. You may either pass
  9054. * individual `onNext` and `onError` callbacks or pass a single observer
  9055. * object with `next` and `error` callbacks.
  9056. *
  9057. * NOTE: Although an `onCompletion` callback can be provided, it will
  9058. * never be called because the snapshot stream is never-ending.
  9059. *
  9060. * @param onNext A callback to be called every time a new `DocumentSnapshot`
  9061. * is available.
  9062. * @param onError A callback to be called if the listen fails or is
  9063. * cancelled. No further callbacks will occur.
  9064. * @return An unsubscribe function that can be called to cancel
  9065. * the snapshot listener.
  9066. */
  9067. onSnapshot(
  9068. onNext: (snapshot: DocumentSnapshot<T>) => void,
  9069. onError?: (error: FirestoreError) => void,
  9070. onCompletion?: () => void
  9071. ): () => void;
  9072. /**
  9073. * Attaches a listener for DocumentSnapshot events. You may either pass
  9074. * individual `onNext` and `onError` callbacks or pass a single observer
  9075. * object with `next` and `error` callbacks.
  9076. *
  9077. * NOTE: Although an `onCompletion` callback can be provided, it will
  9078. * never be called because the snapshot stream is never-ending.
  9079. *
  9080. * @param options Options controlling the listen behavior.
  9081. * @param onNext A callback to be called every time a new `DocumentSnapshot`
  9082. * is available.
  9083. * @param onError A callback to be called if the listen fails or is
  9084. * cancelled. No further callbacks will occur.
  9085. * @return An unsubscribe function that can be called to cancel
  9086. * the snapshot listener.
  9087. */
  9088. onSnapshot(
  9089. options: SnapshotListenOptions,
  9090. onNext: (snapshot: DocumentSnapshot<T>) => void,
  9091. onError?: (error: FirestoreError) => void,
  9092. onCompletion?: () => void
  9093. ): () => void;
  9094. /**
  9095. * Applies a custom data converter to this DocumentReference, allowing you
  9096. * to use your own custom model objects with Firestore. When you call
  9097. * set(), get(), etc. on the returned DocumentReference instance, the
  9098. * provided converter will convert between Firestore data and your custom
  9099. * type U.
  9100. *
  9101. * Passing in `null` as the converter parameter removes the current
  9102. * converter.
  9103. *
  9104. * @param converter Converts objects to and from Firestore. Passing in
  9105. * `null` removes the current converter.
  9106. * @return A DocumentReference<U> that uses the provided converter.
  9107. */
  9108. withConverter(converter: null): DocumentReference<DocumentData>;
  9109. /**
  9110. * Applies a custom data converter to this DocumentReference, allowing you
  9111. * to use your own custom model objects with Firestore. When you call
  9112. * set(), get(), etc. on the returned DocumentReference instance, the
  9113. * provided converter will convert between Firestore data and your custom
  9114. * type U.
  9115. *
  9116. * Passing in `null` as the converter parameter removes the current
  9117. * converter.
  9118. *
  9119. * @param converter Converts objects to and from Firestore. Passing in
  9120. * `null` removes the current converter.
  9121. * @return A DocumentReference<U> that uses the provided converter.
  9122. */
  9123. withConverter<U>(
  9124. converter: FirestoreDataConverter<U>
  9125. ): DocumentReference<U>;
  9126. }
  9127. /**
  9128. * Options that configure how data is retrieved from a `DocumentSnapshot`
  9129. * (e.g. the desired behavior for server timestamps that have not yet been set
  9130. * to their final value).
  9131. */
  9132. export interface SnapshotOptions {
  9133. /**
  9134. * If set, controls the return value for server timestamps that have not yet
  9135. * been set to their final value.
  9136. *
  9137. * By specifying 'estimate', pending server timestamps return an estimate
  9138. * based on the local clock. This estimate will differ from the final value
  9139. * and cause these values to change once the server result becomes available.
  9140. *
  9141. * By specifying 'previous', pending timestamps will be ignored and return
  9142. * their previous value instead.
  9143. *
  9144. * If omitted or set to 'none', `null` will be returned by default until the
  9145. * server value becomes available.
  9146. */
  9147. readonly serverTimestamps?: 'estimate' | 'previous' | 'none';
  9148. }
  9149. /**
  9150. * Metadata about a snapshot, describing the state of the snapshot.
  9151. */
  9152. export interface SnapshotMetadata {
  9153. /**
  9154. * True if the snapshot contains the result of local writes (e.g. set() or
  9155. * update() calls) that have not yet been committed to the backend.
  9156. * If your listener has opted into metadata updates (via
  9157. * `SnapshotListenOptions`) you will receive another
  9158. * snapshot with `hasPendingWrites` equal to false once the writes have been
  9159. * committed to the backend.
  9160. */
  9161. readonly hasPendingWrites: boolean;
  9162. /**
  9163. * True if the snapshot was created from cached data rather than guaranteed
  9164. * up-to-date server data. If your listener has opted into metadata updates
  9165. * (via `SnapshotListenOptions`)
  9166. * you will receive another snapshot with `fromCache` set to false once
  9167. * the client has received up-to-date data from the backend.
  9168. */
  9169. readonly fromCache: boolean;
  9170. /**
  9171. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  9172. *
  9173. * @param other The `SnapshotMetadata` to compare against.
  9174. * @return true if this `SnapshotMetadata` is equal to the provided one.
  9175. */
  9176. isEqual(other: SnapshotMetadata): boolean;
  9177. }
  9178. /**
  9179. * A `DocumentSnapshot` contains data read from a document in your Firestore
  9180. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  9181. * get a specific field.
  9182. *
  9183. * For a `DocumentSnapshot` that points to a non-existing document, any data
  9184. * access will return 'undefined'. You can use the `exists` property to
  9185. * explicitly verify a document's existence.
  9186. */
  9187. export class DocumentSnapshot<T = DocumentData> {
  9188. protected constructor();
  9189. /**
  9190. * Property of the `DocumentSnapshot` that signals whether or not the data
  9191. * exists. True if the document exists.
  9192. */
  9193. readonly exists: boolean;
  9194. /**
  9195. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  9196. */
  9197. readonly ref: DocumentReference<T>;
  9198. /**
  9199. * Property of the `DocumentSnapshot` that provides the document's ID.
  9200. */
  9201. readonly id: string;
  9202. /**
  9203. * Metadata about the `DocumentSnapshot`, including information about its
  9204. * source and local modifications.
  9205. */
  9206. readonly metadata: SnapshotMetadata;
  9207. /**
  9208. * Retrieves all fields in the document as an Object. Returns 'undefined' if
  9209. * the document doesn't exist.
  9210. *
  9211. * By default, `FieldValue.serverTimestamp()` values that have not yet been
  9212. * set to their final value will be returned as `null`. You can override
  9213. * this by passing an options object.
  9214. *
  9215. * @param options An options object to configure how data is retrieved from
  9216. * the snapshot (e.g. the desired behavior for server timestamps that have
  9217. * not yet been set to their final value).
  9218. * @return An Object containing all fields in the document or 'undefined' if
  9219. * the document doesn't exist.
  9220. */
  9221. data(options?: SnapshotOptions): T | undefined;
  9222. /**
  9223. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  9224. * document or field doesn't exist.
  9225. *
  9226. * By default, a `FieldValue.serverTimestamp()` that has not yet been set to
  9227. * its final value will be returned as `null`. You can override this by
  9228. * passing an options object.
  9229. *
  9230. * @param fieldPath The path (e.g. 'foo' or 'foo.bar') to a specific field.
  9231. * @param options An options object to configure how the field is retrieved
  9232. * from the snapshot (e.g. the desired behavior for server timestamps that have
  9233. * not yet been set to their final value).
  9234. * @return The data at the specified field location or undefined if no such
  9235. * field exists in the document.
  9236. */
  9237. get(fieldPath: string | FieldPath, options?: SnapshotOptions): any;
  9238. /**
  9239. * Returns true if this `DocumentSnapshot` is equal to the provided one.
  9240. *
  9241. * @param other The `DocumentSnapshot` to compare against.
  9242. * @return true if this `DocumentSnapshot` is equal to the provided one.
  9243. */
  9244. isEqual(other: DocumentSnapshot<T>): boolean;
  9245. }
  9246. /**
  9247. * A `QueryDocumentSnapshot` contains data read from a document in your
  9248. * Firestore database as part of a query. The document is guaranteed to exist
  9249. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  9250. * specific field.
  9251. *
  9252. * A `QueryDocumentSnapshot` offers the same API surface as a
  9253. * `DocumentSnapshot`. Since query results contain only existing documents, the
  9254. * `exists` property will always be true and `data()` will never return
  9255. * 'undefined'.
  9256. */
  9257. export class QueryDocumentSnapshot<
  9258. T = DocumentData
  9259. > extends DocumentSnapshot<T> {
  9260. private constructor();
  9261. /**
  9262. * Retrieves all fields in the document as an Object.
  9263. *
  9264. * By default, `FieldValue.serverTimestamp()` values that have not yet been
  9265. * set to their final value will be returned as `null`. You can override
  9266. * this by passing an options object.
  9267. *
  9268. * @override
  9269. * @param options An options object to configure how data is retrieved from
  9270. * the snapshot (e.g. the desired behavior for server timestamps that have
  9271. * not yet been set to their final value).
  9272. * @return An Object containing all fields in the document.
  9273. */
  9274. data(options?: SnapshotOptions): T;
  9275. }
  9276. /**
  9277. * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc'
  9278. * (descending or ascending).
  9279. */
  9280. export type OrderByDirection = 'desc' | 'asc';
  9281. /**
  9282. * Filter conditions in a `Query.where()` clause are specified using the
  9283. * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in',
  9284. * 'array-contains-any', and 'not-in'.
  9285. */
  9286. export type WhereFilterOp =
  9287. | '<'
  9288. | '<='
  9289. | '=='
  9290. | '!='
  9291. | '>='
  9292. | '>'
  9293. | 'array-contains'
  9294. | 'in'
  9295. | 'array-contains-any'
  9296. | 'not-in';
  9297. /**
  9298. * A `Query` refers to a Query which you can read or listen to. You can also
  9299. * construct refined `Query` objects by adding filters and ordering.
  9300. */
  9301. export class Query<T = DocumentData> {
  9302. protected constructor();
  9303. /**
  9304. * The `Firestore` for the Firestore database (useful for performing
  9305. * transactions, etc.).
  9306. */
  9307. readonly firestore: Firestore;
  9308. /**
  9309. * Creates and returns a new Query with the additional filter that documents
  9310. * must contain the specified field and the value should satisfy the
  9311. * relation constraint provided.
  9312. *
  9313. * @param fieldPath The path to compare
  9314. * @param opStr The operation string (e.g "<", "<=", "==", ">", ">=").
  9315. * @param value The value for comparison
  9316. * @return The created Query.
  9317. */
  9318. where(
  9319. fieldPath: string | FieldPath,
  9320. opStr: WhereFilterOp,
  9321. value: any
  9322. ): Query<T>;
  9323. /**
  9324. * Creates and returns a new Query that's additionally sorted by the
  9325. * specified field, optionally in descending order instead of ascending.
  9326. *
  9327. * @param fieldPath The field to sort by.
  9328. * @param directionStr Optional direction to sort by (`asc` or `desc`). If
  9329. * not specified, order will be ascending.
  9330. * @return The created Query.
  9331. */
  9332. orderBy(
  9333. fieldPath: string | FieldPath,
  9334. directionStr?: OrderByDirection
  9335. ): Query<T>;
  9336. /**
  9337. * Creates and returns a new Query that only returns the first matching
  9338. * documents.
  9339. *
  9340. * @param limit The maximum number of items to return.
  9341. * @return The created Query.
  9342. */
  9343. limit(limit: number): Query<T>;
  9344. /**
  9345. * Creates and returns a new Query that only returns the last matching
  9346. * documents.
  9347. *
  9348. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  9349. * otherwise an exception will be thrown during execution.
  9350. *
  9351. * @param limit The maximum number of items to return.
  9352. * @return The created Query.
  9353. */
  9354. limitToLast(limit: number): Query<T>;
  9355. /**
  9356. * Creates and returns a new Query that starts at the provided document
  9357. * (inclusive). The starting position is relative to the order of the query.
  9358. * The document must contain all of the fields provided in the `orderBy` of
  9359. * this query.
  9360. *
  9361. * @param snapshot The snapshot of the document to start at.
  9362. * @return The created Query.
  9363. */
  9364. startAt(snapshot: DocumentSnapshot<any>): Query<T>;
  9365. /**
  9366. * Creates and returns a new Query that starts at the provided fields
  9367. * relative to the order of the query. The order of the field values
  9368. * must match the order of the order by clauses of the query.
  9369. *
  9370. * @param fieldValues The field values to start this query at, in order
  9371. * of the query's order by.
  9372. * @return The created Query.
  9373. */
  9374. startAt(...fieldValues: any[]): Query<T>;
  9375. /**
  9376. * Creates and returns a new Query that starts after the provided document
  9377. * (exclusive). The starting position is relative to the order of the query.
  9378. * The document must contain all of the fields provided in the orderBy of
  9379. * this query.
  9380. *
  9381. * @param snapshot The snapshot of the document to start after.
  9382. * @return The created Query.
  9383. */
  9384. startAfter(snapshot: DocumentSnapshot<any>): Query<T>;
  9385. /**
  9386. * Creates and returns a new Query that starts after the provided fields
  9387. * relative to the order of the query. The order of the field values
  9388. * must match the order of the order by clauses of the query.
  9389. *
  9390. * @param fieldValues The field values to start this query after, in order
  9391. * of the query's order by.
  9392. * @return The created Query.
  9393. */
  9394. startAfter(...fieldValues: any[]): Query<T>;
  9395. /**
  9396. * Creates and returns a new Query that ends before the provided document
  9397. * (exclusive). The end position is relative to the order of the query. The
  9398. * document must contain all of the fields provided in the orderBy of this
  9399. * query.
  9400. *
  9401. * @param snapshot The snapshot of the document to end before.
  9402. * @return The created Query.
  9403. */
  9404. endBefore(snapshot: DocumentSnapshot<any>): Query<T>;
  9405. /**
  9406. * Creates and returns a new Query that ends before the provided fields
  9407. * relative to the order of the query. The order of the field values
  9408. * must match the order of the order by clauses of the query.
  9409. *
  9410. * @param fieldValues The field values to end this query before, in order
  9411. * of the query's order by.
  9412. * @return The created Query.
  9413. */
  9414. endBefore(...fieldValues: any[]): Query<T>;
  9415. /**
  9416. * Creates and returns a new Query that ends at the provided document
  9417. * (inclusive). The end position is relative to the order of the query. The
  9418. * document must contain all of the fields provided in the orderBy of this
  9419. * query.
  9420. *
  9421. * @param snapshot The snapshot of the document to end at.
  9422. * @return The created Query.
  9423. */
  9424. endAt(snapshot: DocumentSnapshot<any>): Query<T>;
  9425. /**
  9426. * Creates and returns a new Query that ends at the provided fields
  9427. * relative to the order of the query. The order of the field values
  9428. * must match the order of the order by clauses of the query.
  9429. *
  9430. * @param fieldValues The field values to end this query at, in order
  9431. * of the query's order by.
  9432. * @return The created Query.
  9433. */
  9434. endAt(...fieldValues: any[]): Query<T>;
  9435. /**
  9436. * Returns true if this `Query` is equal to the provided one.
  9437. *
  9438. * @param other The `Query` to compare against.
  9439. * @return true if this `Query` is equal to the provided one.
  9440. */
  9441. isEqual(other: Query<T>): boolean;
  9442. /**
  9443. * Executes the query and returns the results as a `QuerySnapshot`.
  9444. *
  9445. * Note: By default, get() attempts to provide up-to-date data when possible
  9446. * by waiting for data from the server, but it may return cached data or fail
  9447. * if you are offline and the server cannot be reached. This behavior can be
  9448. * altered via the `GetOptions` parameter.
  9449. *
  9450. * @param options An object to configure the get behavior.
  9451. * @return A Promise that will be resolved with the results of the Query.
  9452. */
  9453. get(options?: GetOptions): Promise<QuerySnapshot<T>>;
  9454. /**
  9455. * Attaches a listener for QuerySnapshot events. You may either pass
  9456. * individual `onNext` and `onError` callbacks or pass a single observer
  9457. * object with `next` and `error` callbacks. The listener can be cancelled by
  9458. * calling the function that is returned when `onSnapshot` is called.
  9459. *
  9460. * NOTE: Although an `onCompletion` callback can be provided, it will
  9461. * never be called because the snapshot stream is never-ending.
  9462. *
  9463. * @param observer A single object containing `next` and `error` callbacks.
  9464. * @return An unsubscribe function that can be called to cancel
  9465. * the snapshot listener.
  9466. */
  9467. onSnapshot(observer: {
  9468. next?: (snapshot: QuerySnapshot<T>) => void;
  9469. error?: (error: FirestoreError) => void;
  9470. complete?: () => void;
  9471. }): () => void;
  9472. /**
  9473. * Attaches a listener for QuerySnapshot events. You may either pass
  9474. * individual `onNext` and `onError` callbacks or pass a single observer
  9475. * object with `next` and `error` callbacks. The listener can be cancelled by
  9476. * calling the function that is returned when `onSnapshot` is called.
  9477. *
  9478. * NOTE: Although an `onCompletion` callback can be provided, it will
  9479. * never be called because the snapshot stream is never-ending.
  9480. *
  9481. * @param options Options controlling the listen behavior.
  9482. * @param observer A single object containing `next` and `error` callbacks.
  9483. * @return An unsubscribe function that can be called to cancel
  9484. * the snapshot listener.
  9485. */
  9486. onSnapshot(
  9487. options: SnapshotListenOptions,
  9488. observer: {
  9489. next?: (snapshot: QuerySnapshot<T>) => void;
  9490. error?: (error: FirestoreError) => void;
  9491. complete?: () => void;
  9492. }
  9493. ): () => void;
  9494. /**
  9495. * Attaches a listener for QuerySnapshot events. You may either pass
  9496. * individual `onNext` and `onError` callbacks or pass a single observer
  9497. * object with `next` and `error` callbacks. The listener can be cancelled by
  9498. * calling the function that is returned when `onSnapshot` is called.
  9499. *
  9500. * NOTE: Although an `onCompletion` callback can be provided, it will
  9501. * never be called because the snapshot stream is never-ending.
  9502. *
  9503. * @param onNext A callback to be called every time a new `QuerySnapshot`
  9504. * is available.
  9505. * @param onError A callback to be called if the listen fails or is
  9506. * cancelled. No further callbacks will occur.
  9507. * @return An unsubscribe function that can be called to cancel
  9508. * the snapshot listener.
  9509. */
  9510. onSnapshot(
  9511. onNext: (snapshot: QuerySnapshot<T>) => void,
  9512. onError?: (error: FirestoreError) => void,
  9513. onCompletion?: () => void
  9514. ): () => void;
  9515. /**
  9516. * Attaches a listener for QuerySnapshot events. You may either pass
  9517. * individual `onNext` and `onError` callbacks or pass a single observer
  9518. * object with `next` and `error` callbacks. The listener can be cancelled by
  9519. * calling the function that is returned when `onSnapshot` is called.
  9520. *
  9521. * NOTE: Although an `onCompletion` callback can be provided, it will
  9522. * never be called because the snapshot stream is never-ending.
  9523. *
  9524. * @param options Options controlling the listen behavior.
  9525. * @param onNext A callback to be called every time a new `QuerySnapshot`
  9526. * is available.
  9527. * @param onError A callback to be called if the listen fails or is
  9528. * cancelled. No further callbacks will occur.
  9529. * @return An unsubscribe function that can be called to cancel
  9530. * the snapshot listener.
  9531. */
  9532. onSnapshot(
  9533. options: SnapshotListenOptions,
  9534. onNext: (snapshot: QuerySnapshot<T>) => void,
  9535. onError?: (error: FirestoreError) => void,
  9536. onCompletion?: () => void
  9537. ): () => void;
  9538. /**
  9539. * Applies a custom data converter to this Query, allowing you to use your
  9540. * own custom model objects with Firestore. When you call get() on the
  9541. * returned Query, the provided converter will convert between Firestore
  9542. * data and your custom type U.
  9543. *
  9544. * Passing in `null` as the converter parameter removes the current
  9545. * converter.
  9546. *
  9547. * @param converter Converts objects to and from Firestore. Passing in
  9548. * `null` removes the current converter.
  9549. * @return A Query<U> that uses the provided converter.
  9550. */
  9551. withConverter(converter: null): Query<DocumentData>;
  9552. /**
  9553. * Applies a custom data converter to this Query, allowing you to use your
  9554. * own custom model objects with Firestore. When you call get() on the
  9555. * returned Query, the provided converter will convert between Firestore
  9556. * data and your custom type U.
  9557. *
  9558. * Passing in `null` as the converter parameter removes the current
  9559. * converter.
  9560. *
  9561. * @param converter Converts objects to and from Firestore. Passing in
  9562. * `null` removes the current converter.
  9563. * @return A Query<U> that uses the provided converter.
  9564. */
  9565. withConverter<U>(converter: FirestoreDataConverter<U>): Query<U>;
  9566. }
  9567. /**
  9568. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  9569. * representing the results of a query. The documents can be accessed as an
  9570. * array via the `docs` property or enumerated using the `forEach` method. The
  9571. * number of documents can be determined via the `empty` and `size`
  9572. * properties.
  9573. */
  9574. export class QuerySnapshot<T = DocumentData> {
  9575. private constructor();
  9576. /**
  9577. * The query on which you called `get` or `onSnapshot` in order to get this
  9578. * `QuerySnapshot`.
  9579. */
  9580. readonly query: Query<T>;
  9581. /**
  9582. * Metadata about this snapshot, concerning its source and if it has local
  9583. * modifications.
  9584. */
  9585. readonly metadata: SnapshotMetadata;
  9586. /** An array of all the documents in the `QuerySnapshot`. */
  9587. readonly docs: Array<QueryDocumentSnapshot<T>>;
  9588. /** The number of documents in the `QuerySnapshot`. */
  9589. readonly size: number;
  9590. /** True if there are no documents in the `QuerySnapshot`. */
  9591. readonly empty: boolean;
  9592. /**
  9593. * Returns an array of the documents changes since the last snapshot. If this
  9594. * is the first snapshot, all documents will be in the list as added changes.
  9595. *
  9596. * @param options `SnapshotListenOptions` that control whether metadata-only
  9597. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  9598. * snapshot events.
  9599. */
  9600. docChanges(options?: SnapshotListenOptions): Array<DocumentChange<T>>;
  9601. /**
  9602. * Enumerates all of the documents in the `QuerySnapshot`.
  9603. *
  9604. * @param callback A callback to be called with a `QueryDocumentSnapshot` for
  9605. * each document in the snapshot.
  9606. * @param thisArg The `this` binding for the callback.
  9607. */
  9608. forEach(
  9609. callback: (result: QueryDocumentSnapshot<T>) => void,
  9610. thisArg?: any
  9611. ): void;
  9612. /**
  9613. * Returns true if this `QuerySnapshot` is equal to the provided one.
  9614. *
  9615. * @param other The `QuerySnapshot` to compare against.
  9616. * @return true if this `QuerySnapshot` is equal to the provided one.
  9617. */
  9618. isEqual(other: QuerySnapshot<T>): boolean;
  9619. }
  9620. /**
  9621. * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.
  9622. */
  9623. export type DocumentChangeType = 'added' | 'removed' | 'modified';
  9624. /**
  9625. * A `DocumentChange` represents a change to the documents matching a query.
  9626. * It contains the document affected and the type of change that occurred.
  9627. */
  9628. export interface DocumentChange<T = DocumentData> {
  9629. /** The type of change ('added', 'modified', or 'removed'). */
  9630. readonly type: DocumentChangeType;
  9631. /** The document affected by this change. */
  9632. readonly doc: QueryDocumentSnapshot<T>;
  9633. /**
  9634. * The index of the changed document in the result set immediately prior to
  9635. * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects
  9636. * have been applied). Is -1 for 'added' events.
  9637. */
  9638. readonly oldIndex: number;
  9639. /**
  9640. * The index of the changed document in the result set immediately after
  9641. * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`
  9642. * objects and the current `DocumentChange` object have been applied).
  9643. * Is -1 for 'removed' events.
  9644. */
  9645. readonly newIndex: number;
  9646. }
  9647. /**
  9648. * A `CollectionReference` object can be used for adding documents, getting
  9649. * document references, and querying for documents (using the methods
  9650. * inherited from `Query`).
  9651. */
  9652. export class CollectionReference<T = DocumentData> extends Query<T> {
  9653. private constructor();
  9654. /** The collection's identifier. */
  9655. readonly id: string;
  9656. /**
  9657. * A reference to the containing `DocumentReference` if this is a subcollection.
  9658. * If this isn't a subcollection, the reference is null.
  9659. */
  9660. readonly parent: DocumentReference<DocumentData> | null;
  9661. /**
  9662. * A string representing the path of the referenced collection (relative
  9663. * to the root of the database).
  9664. */
  9665. readonly path: string;
  9666. /**
  9667. * Get a `DocumentReference` for the document within the collection at the
  9668. * specified path. If no path is specified, an automatically-generated
  9669. * unique ID will be used for the returned DocumentReference.
  9670. *
  9671. * @param documentPath A slash-separated path to a document.
  9672. * @return The `DocumentReference` instance.
  9673. */
  9674. doc(documentPath?: string): DocumentReference<T>;
  9675. /**
  9676. * Add a new document to this collection with the specified data, assigning
  9677. * it a document ID automatically.
  9678. *
  9679. * @param data An Object containing the data for the new document.
  9680. * @return A Promise resolved with a `DocumentReference` pointing to the
  9681. * newly created document after it has been written to the backend.
  9682. */
  9683. add(data: T): Promise<DocumentReference<T>>;
  9684. /**
  9685. * Returns true if this `CollectionReference` is equal to the provided one.
  9686. *
  9687. * @param other The `CollectionReference` to compare against.
  9688. * @return true if this `CollectionReference` is equal to the provided one.
  9689. */
  9690. isEqual(other: CollectionReference<T>): boolean;
  9691. /**
  9692. * Applies a custom data converter to this CollectionReference, allowing you
  9693. * to use your own custom model objects with Firestore. When you call add()
  9694. * on the returned CollectionReference instance, the provided converter will
  9695. * convert between Firestore data and your custom type U.
  9696. *
  9697. * Passing in `null` as the converter parameter removes the current
  9698. * converter.
  9699. *
  9700. * @param converter Converts objects to and from Firestore. Passing in
  9701. * `null` removes the current converter.
  9702. * @return A CollectionReference<U> that uses the provided converter.
  9703. */
  9704. withConverter(converter: null): CollectionReference<DocumentData>;
  9705. /**
  9706. * Applies a custom data converter to this CollectionReference, allowing you
  9707. * to use your own custom model objects with Firestore. When you call add()
  9708. * on the returned CollectionReference instance, the provided converter will
  9709. * convert between Firestore data and your custom type U.
  9710. *
  9711. * Passing in `null` as the converter parameter removes the current
  9712. * converter.
  9713. *
  9714. * @param converter Converts objects to and from Firestore. Passing in
  9715. * `null` removes the current converter.
  9716. * @return A CollectionReference<U> that uses the provided converter.
  9717. */
  9718. withConverter<U>(
  9719. converter: FirestoreDataConverter<U>
  9720. ): CollectionReference<U>;
  9721. }
  9722. /**
  9723. * Sentinel values that can be used when writing document fields with `set()`
  9724. * or `update()`.
  9725. */
  9726. export class FieldValue {
  9727. private constructor();
  9728. /**
  9729. * Returns a sentinel used with `set()` or `update()` to include a
  9730. * server-generated timestamp in the written data.
  9731. */
  9732. static serverTimestamp(): FieldValue;
  9733. /**
  9734. * Returns a sentinel for use with `update()` to mark a field for deletion.
  9735. */
  9736. static delete(): FieldValue;
  9737. /**
  9738. * Returns a special value that can be used with `set()` or `update()` that tells
  9739. * the server to union the given elements with any array value that already
  9740. * exists on the server. Each specified element that doesn't already exist in
  9741. * the array will be added to the end. If the field being modified is not
  9742. * already an array it will be overwritten with an array containing exactly
  9743. * the specified elements.
  9744. *
  9745. * @param elements The elements to union into the array.
  9746. * @return The FieldValue sentinel for use in a call to `set()` or `update()`.
  9747. */
  9748. static arrayUnion(...elements: any[]): FieldValue;
  9749. /**
  9750. * Returns a special value that can be used with `set()` or `update()` that tells
  9751. * the server to remove the given elements from any array value that already
  9752. * exists on the server. All instances of each element specified will be
  9753. * removed from the array. If the field being modified is not already an
  9754. * array it will be overwritten with an empty array.
  9755. *
  9756. * @param elements The elements to remove from the array.
  9757. * @return The FieldValue sentinel for use in a call to `set()` or `update()`.
  9758. */
  9759. static arrayRemove(...elements: any[]): FieldValue;
  9760. /**
  9761. * Returns a special value that can be used with `set()` or `update()` that tells
  9762. * the server to increment the field's current value by the given value.
  9763. *
  9764. * If either the operand or the current field value uses floating point precision,
  9765. * all arithmetic follows IEEE 754 semantics. If both values are integers,
  9766. * values outside of JavaScript's safe number range (`Number.MIN_SAFE_INTEGER` to
  9767. * `Number.MAX_SAFE_INTEGER`) are also subject to precision loss. Furthermore,
  9768. * once processed by the Firestore backend, all integer operations are capped
  9769. * between -2^63 and 2^63-1.
  9770. *
  9771. * If the current field value is not of type `number`, or if the field does not
  9772. * yet exist, the transformation sets the field to the given value.
  9773. *
  9774. * @param n The value to increment by.
  9775. * @return The FieldValue sentinel for use in a call to `set()` or `update()`.
  9776. */
  9777. static increment(n: number): FieldValue;
  9778. /**
  9779. * Returns true if this `FieldValue` is equal to the provided one.
  9780. *
  9781. * @param other The `FieldValue` to compare against.
  9782. * @return true if this `FieldValue` is equal to the provided one.
  9783. */
  9784. isEqual(other: FieldValue): boolean;
  9785. }
  9786. /**
  9787. * A FieldPath refers to a field in a document. The path may consist of a
  9788. * single field name (referring to a top-level field in the document), or a
  9789. * list of field names (referring to a nested field in the document).
  9790. *
  9791. * Create a FieldPath by providing field names. If more than one field
  9792. * name is provided, the path will point to a nested field in a document.
  9793. *
  9794. */
  9795. export class FieldPath {
  9796. /**
  9797. * Creates a FieldPath from the provided field names. If more than one field
  9798. * name is provided, the path will point to a nested field in a document.
  9799. *
  9800. * @param fieldNames A list of field names.
  9801. */
  9802. constructor(...fieldNames: string[]);
  9803. /**
  9804. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  9805. * It can be used in queries to sort or filter by the document ID.
  9806. */
  9807. static documentId(): FieldPath;
  9808. /**
  9809. * Returns true if this `FieldPath` is equal to the provided one.
  9810. *
  9811. * @param other The `FieldPath` to compare against.
  9812. * @return true if this `FieldPath` is equal to the provided one.
  9813. */
  9814. isEqual(other: FieldPath): boolean;
  9815. }
  9816. /**
  9817. * The set of Firestore status codes. The codes are the same at the ones
  9818. * exposed by gRPC here:
  9819. * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  9820. *
  9821. * Possible values:
  9822. * - 'cancelled': The operation was cancelled (typically by the caller).
  9823. * - 'unknown': Unknown error or an error from a different error domain.
  9824. * - 'invalid-argument': Client specified an invalid argument. Note that this
  9825. * differs from 'failed-precondition'. 'invalid-argument' indicates
  9826. * arguments that are problematic regardless of the state of the system
  9827. * (e.g. an invalid field name).
  9828. * - 'deadline-exceeded': Deadline expired before operation could complete.
  9829. * For operations that change the state of the system, this error may be
  9830. * returned even if the operation has completed successfully. For example,
  9831. * a successful response from a server could have been delayed long enough
  9832. * for the deadline to expire.
  9833. * - 'not-found': Some requested document was not found.
  9834. * - 'already-exists': Some document that we attempted to create already
  9835. * exists.
  9836. * - 'permission-denied': The caller does not have permission to execute the
  9837. * specified operation.
  9838. * - 'resource-exhausted': Some resource has been exhausted, perhaps a
  9839. * per-user quota, or perhaps the entire file system is out of space.
  9840. * - 'failed-precondition': Operation was rejected because the system is not
  9841. * in a state required for the operation's execution.
  9842. * - 'aborted': The operation was aborted, typically due to a concurrency
  9843. * issue like transaction aborts, etc.
  9844. * - 'out-of-range': Operation was attempted past the valid range.
  9845. * - 'unimplemented': Operation is not implemented or not supported/enabled.
  9846. * - 'internal': Internal errors. Means some invariants expected by
  9847. * underlying system has been broken. If you see one of these errors,
  9848. * something is very broken.
  9849. * - 'unavailable': The service is currently unavailable. This is most likely
  9850. * a transient condition and may be corrected by retrying with a backoff.
  9851. * - 'data-loss': Unrecoverable data loss or corruption.
  9852. * - 'unauthenticated': The request does not have valid authentication
  9853. * credentials for the operation.
  9854. */
  9855. export type FirestoreErrorCode =
  9856. | 'cancelled'
  9857. | 'unknown'
  9858. | 'invalid-argument'
  9859. | 'deadline-exceeded'
  9860. | 'not-found'
  9861. | 'already-exists'
  9862. | 'permission-denied'
  9863. | 'resource-exhausted'
  9864. | 'failed-precondition'
  9865. | 'aborted'
  9866. | 'out-of-range'
  9867. | 'unimplemented'
  9868. | 'internal'
  9869. | 'unavailable'
  9870. | 'data-loss'
  9871. | 'unauthenticated';
  9872. /** An error returned by a Firestore operation. */
  9873. // TODO(b/63008957): FirestoreError should extend firebase.FirebaseError
  9874. export interface FirestoreError {
  9875. code: FirestoreErrorCode;
  9876. message: string;
  9877. name: string;
  9878. stack?: string;
  9879. }
  9880. export type EmulatorMockTokenOptions = firebase.EmulatorMockTokenOptions;
  9881. }
  9882. export default firebase;
  9883. export as namespace firebase;