index.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. 'use strict';
  2. var firebase = require('@firebase/app-compat');
  3. var component = require('@firebase/component');
  4. var database = require('@firebase/database');
  5. var util = require('@firebase/util');
  6. var logger = require('@firebase/logger');
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var firebase__default = /*#__PURE__*/_interopDefaultLegacy(firebase);
  9. const name = "@firebase/database-compat";
  10. const version = "1.0.10";
  11. /**
  12. * @license
  13. * Copyright 2021 Google LLC
  14. *
  15. * Licensed under the Apache License, Version 2.0 (the "License");
  16. * you may not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing, software
  22. * distributed under the License is distributed on an "AS IS" BASIS,
  23. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. * See the License for the specific language governing permissions and
  25. * limitations under the License.
  26. */
  27. const logClient = new logger.Logger('@firebase/database-compat');
  28. const warn = function (msg) {
  29. const message = 'FIREBASE WARNING: ' + msg;
  30. logClient.warn(message);
  31. };
  32. /**
  33. * @license
  34. * Copyright 2021 Google LLC
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License");
  37. * you may not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS,
  44. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. const validateBoolean = function (fnName, argumentName, bool, optional) {
  49. if (optional && bool === undefined) {
  50. return;
  51. }
  52. if (typeof bool !== 'boolean') {
  53. throw new Error(util.errorPrefix(fnName, argumentName) + 'must be a boolean.');
  54. }
  55. };
  56. const validateEventType = function (fnName, eventType, optional) {
  57. if (optional && eventType === undefined) {
  58. return;
  59. }
  60. switch (eventType) {
  61. case 'value':
  62. case 'child_added':
  63. case 'child_removed':
  64. case 'child_changed':
  65. case 'child_moved':
  66. break;
  67. default:
  68. throw new Error(util.errorPrefix(fnName, 'eventType') +
  69. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  70. '"child_changed", or "child_moved".');
  71. }
  72. };
  73. /**
  74. * @license
  75. * Copyright 2017 Google LLC
  76. *
  77. * Licensed under the Apache License, Version 2.0 (the "License");
  78. * you may not use this file except in compliance with the License.
  79. * You may obtain a copy of the License at
  80. *
  81. * http://www.apache.org/licenses/LICENSE-2.0
  82. *
  83. * Unless required by applicable law or agreed to in writing, software
  84. * distributed under the License is distributed on an "AS IS" BASIS,
  85. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  86. * See the License for the specific language governing permissions and
  87. * limitations under the License.
  88. */
  89. class OnDisconnect {
  90. constructor(_delegate) {
  91. this._delegate = _delegate;
  92. }
  93. cancel(onComplete) {
  94. util.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);
  95. util.validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);
  96. const result = this._delegate.cancel();
  97. if (onComplete) {
  98. result.then(() => onComplete(null), error => onComplete(error));
  99. }
  100. return result;
  101. }
  102. remove(onComplete) {
  103. util.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);
  104. util.validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);
  105. const result = this._delegate.remove();
  106. if (onComplete) {
  107. result.then(() => onComplete(null), error => onComplete(error));
  108. }
  109. return result;
  110. }
  111. set(value, onComplete) {
  112. util.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);
  113. util.validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);
  114. const result = this._delegate.set(value);
  115. if (onComplete) {
  116. result.then(() => onComplete(null), error => onComplete(error));
  117. }
  118. return result;
  119. }
  120. setWithPriority(value, priority, onComplete) {
  121. util.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);
  122. util.validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true);
  123. const result = this._delegate.setWithPriority(value, priority);
  124. if (onComplete) {
  125. result.then(() => onComplete(null), error => onComplete(error));
  126. }
  127. return result;
  128. }
  129. update(objectToMerge, onComplete) {
  130. util.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);
  131. if (Array.isArray(objectToMerge)) {
  132. const newObjectToMerge = {};
  133. for (let i = 0; i < objectToMerge.length; ++i) {
  134. newObjectToMerge['' + i] = objectToMerge[i];
  135. }
  136. objectToMerge = newObjectToMerge;
  137. warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +
  138. 'existing data, or an Object with integer keys if you really do want to only update some of the children.');
  139. }
  140. util.validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);
  141. const result = this._delegate.update(objectToMerge);
  142. if (onComplete) {
  143. result.then(() => onComplete(null), error => onComplete(error));
  144. }
  145. return result;
  146. }
  147. }
  148. /**
  149. * @license
  150. * Copyright 2017 Google LLC
  151. *
  152. * Licensed under the Apache License, Version 2.0 (the "License");
  153. * you may not use this file except in compliance with the License.
  154. * You may obtain a copy of the License at
  155. *
  156. * http://www.apache.org/licenses/LICENSE-2.0
  157. *
  158. * Unless required by applicable law or agreed to in writing, software
  159. * distributed under the License is distributed on an "AS IS" BASIS,
  160. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  161. * See the License for the specific language governing permissions and
  162. * limitations under the License.
  163. */
  164. class TransactionResult {
  165. /**
  166. * A type for the resolve value of Firebase.transaction.
  167. */
  168. constructor(committed, snapshot) {
  169. this.committed = committed;
  170. this.snapshot = snapshot;
  171. }
  172. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  173. // for end-users
  174. toJSON() {
  175. util.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);
  176. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  177. }
  178. }
  179. /**
  180. * @license
  181. * Copyright 2017 Google LLC
  182. *
  183. * Licensed under the Apache License, Version 2.0 (the "License");
  184. * you may not use this file except in compliance with the License.
  185. * You may obtain a copy of the License at
  186. *
  187. * http://www.apache.org/licenses/LICENSE-2.0
  188. *
  189. * Unless required by applicable law or agreed to in writing, software
  190. * distributed under the License is distributed on an "AS IS" BASIS,
  191. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  192. * See the License for the specific language governing permissions and
  193. * limitations under the License.
  194. */
  195. /**
  196. * Class representing a firebase data snapshot. It wraps a SnapshotNode and
  197. * surfaces the public methods (val, forEach, etc.) we want to expose.
  198. */
  199. class DataSnapshot {
  200. constructor(_database, _delegate) {
  201. this._database = _database;
  202. this._delegate = _delegate;
  203. }
  204. /**
  205. * Retrieves the snapshot contents as JSON. Returns null if the snapshot is
  206. * empty.
  207. *
  208. * @returns JSON representation of the DataSnapshot contents, or null if empty.
  209. */
  210. val() {
  211. util.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);
  212. return this._delegate.val();
  213. }
  214. /**
  215. * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting
  216. * the entire node contents.
  217. * @returns JSON representation of the DataSnapshot contents, or null if empty.
  218. */
  219. exportVal() {
  220. util.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);
  221. return this._delegate.exportVal();
  222. }
  223. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  224. // for end-users
  225. toJSON() {
  226. // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content
  227. util.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);
  228. return this._delegate.toJSON();
  229. }
  230. /**
  231. * Returns whether the snapshot contains a non-null value.
  232. *
  233. * @returns Whether the snapshot contains a non-null value, or is empty.
  234. */
  235. exists() {
  236. util.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);
  237. return this._delegate.exists();
  238. }
  239. /**
  240. * Returns a DataSnapshot of the specified child node's contents.
  241. *
  242. * @param path - Path to a child.
  243. * @returns DataSnapshot for child node.
  244. */
  245. child(path) {
  246. util.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);
  247. // Ensure the childPath is a string (can be a number)
  248. path = String(path);
  249. database._validatePathString('DataSnapshot.child', 'path', path, false);
  250. return new DataSnapshot(this._database, this._delegate.child(path));
  251. }
  252. /**
  253. * Returns whether the snapshot contains a child at the specified path.
  254. *
  255. * @param path - Path to a child.
  256. * @returns Whether the child exists.
  257. */
  258. hasChild(path) {
  259. util.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);
  260. database._validatePathString('DataSnapshot.hasChild', 'path', path, false);
  261. return this._delegate.hasChild(path);
  262. }
  263. /**
  264. * Returns the priority of the object, or null if no priority was set.
  265. *
  266. * @returns The priority.
  267. */
  268. getPriority() {
  269. util.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);
  270. return this._delegate.priority;
  271. }
  272. /**
  273. * Iterates through child nodes and calls the specified action for each one.
  274. *
  275. * @param action - Callback function to be called
  276. * for each child.
  277. * @returns True if forEach was canceled by action returning true for
  278. * one of the child nodes.
  279. */
  280. forEach(action) {
  281. util.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);
  282. util.validateCallback('DataSnapshot.forEach', 'action', action, false);
  283. return this._delegate.forEach(expDataSnapshot => action(new DataSnapshot(this._database, expDataSnapshot)));
  284. }
  285. /**
  286. * Returns whether this DataSnapshot has children.
  287. * @returns True if the DataSnapshot contains 1 or more child nodes.
  288. */
  289. hasChildren() {
  290. util.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);
  291. return this._delegate.hasChildren();
  292. }
  293. get key() {
  294. return this._delegate.key;
  295. }
  296. /**
  297. * Returns the number of children for this DataSnapshot.
  298. * @returns The number of children that this DataSnapshot contains.
  299. */
  300. numChildren() {
  301. util.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);
  302. return this._delegate.size;
  303. }
  304. /**
  305. * @returns The Firebase reference for the location this snapshot's data came
  306. * from.
  307. */
  308. getRef() {
  309. util.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);
  310. return new Reference(this._database, this._delegate.ref);
  311. }
  312. get ref() {
  313. return this.getRef();
  314. }
  315. }
  316. /**
  317. * A Query represents a filter to be applied to a firebase location. This object purely represents the
  318. * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.
  319. *
  320. * Since every Firebase reference is a query, Firebase inherits from this object.
  321. */
  322. class Query {
  323. constructor(database, _delegate) {
  324. this.database = database;
  325. this._delegate = _delegate;
  326. }
  327. on(eventType, callback, cancelCallbackOrContext, context) {
  328. var _a;
  329. util.validateArgCount('Query.on', 2, 4, arguments.length);
  330. util.validateCallback('Query.on', 'callback', callback, false);
  331. const ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);
  332. const valueCallback = (expSnapshot, previousChildName) => {
  333. callback.call(ret.context, new DataSnapshot(this.database, expSnapshot), previousChildName);
  334. };
  335. valueCallback.userCallback = callback;
  336. valueCallback.context = ret.context;
  337. const cancelCallback = (_a = ret.cancel) === null || _a === void 0 ? void 0 : _a.bind(ret.context);
  338. switch (eventType) {
  339. case 'value':
  340. database.onValue(this._delegate, valueCallback, cancelCallback);
  341. return callback;
  342. case 'child_added':
  343. database.onChildAdded(this._delegate, valueCallback, cancelCallback);
  344. return callback;
  345. case 'child_removed':
  346. database.onChildRemoved(this._delegate, valueCallback, cancelCallback);
  347. return callback;
  348. case 'child_changed':
  349. database.onChildChanged(this._delegate, valueCallback, cancelCallback);
  350. return callback;
  351. case 'child_moved':
  352. database.onChildMoved(this._delegate, valueCallback, cancelCallback);
  353. return callback;
  354. default:
  355. throw new Error(util.errorPrefix('Query.on', 'eventType') +
  356. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  357. '"child_changed", or "child_moved".');
  358. }
  359. }
  360. off(eventType, callback, context) {
  361. util.validateArgCount('Query.off', 0, 3, arguments.length);
  362. validateEventType('Query.off', eventType, true);
  363. util.validateCallback('Query.off', 'callback', callback, true);
  364. util.validateContextObject('Query.off', 'context', context, true);
  365. if (callback) {
  366. const valueCallback = () => { };
  367. valueCallback.userCallback = callback;
  368. valueCallback.context = context;
  369. database.off(this._delegate, eventType, valueCallback);
  370. }
  371. else {
  372. database.off(this._delegate, eventType);
  373. }
  374. }
  375. /**
  376. * Get the server-value for this query, or return a cached value if not connected.
  377. */
  378. get() {
  379. return database.get(this._delegate).then(expSnapshot => {
  380. return new DataSnapshot(this.database, expSnapshot);
  381. });
  382. }
  383. /**
  384. * Attaches a listener, waits for the first event, and then removes the listener
  385. */
  386. once(eventType, callback, failureCallbackOrContext, context) {
  387. util.validateArgCount('Query.once', 1, 4, arguments.length);
  388. util.validateCallback('Query.once', 'callback', callback, true);
  389. const ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context);
  390. const deferred = new util.Deferred();
  391. const valueCallback = (expSnapshot, previousChildName) => {
  392. const result = new DataSnapshot(this.database, expSnapshot);
  393. if (callback) {
  394. callback.call(ret.context, result, previousChildName);
  395. }
  396. deferred.resolve(result);
  397. };
  398. valueCallback.userCallback = callback;
  399. valueCallback.context = ret.context;
  400. const cancelCallback = (error) => {
  401. if (ret.cancel) {
  402. ret.cancel.call(ret.context, error);
  403. }
  404. deferred.reject(error);
  405. };
  406. switch (eventType) {
  407. case 'value':
  408. database.onValue(this._delegate, valueCallback, cancelCallback, {
  409. onlyOnce: true
  410. });
  411. break;
  412. case 'child_added':
  413. database.onChildAdded(this._delegate, valueCallback, cancelCallback, {
  414. onlyOnce: true
  415. });
  416. break;
  417. case 'child_removed':
  418. database.onChildRemoved(this._delegate, valueCallback, cancelCallback, {
  419. onlyOnce: true
  420. });
  421. break;
  422. case 'child_changed':
  423. database.onChildChanged(this._delegate, valueCallback, cancelCallback, {
  424. onlyOnce: true
  425. });
  426. break;
  427. case 'child_moved':
  428. database.onChildMoved(this._delegate, valueCallback, cancelCallback, {
  429. onlyOnce: true
  430. });
  431. break;
  432. default:
  433. throw new Error(util.errorPrefix('Query.once', 'eventType') +
  434. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  435. '"child_changed", or "child_moved".');
  436. }
  437. return deferred.promise;
  438. }
  439. /**
  440. * Set a limit and anchor it to the start of the window.
  441. */
  442. limitToFirst(limit) {
  443. util.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);
  444. return new Query(this.database, database.query(this._delegate, database.limitToFirst(limit)));
  445. }
  446. /**
  447. * Set a limit and anchor it to the end of the window.
  448. */
  449. limitToLast(limit) {
  450. util.validateArgCount('Query.limitToLast', 1, 1, arguments.length);
  451. return new Query(this.database, database.query(this._delegate, database.limitToLast(limit)));
  452. }
  453. /**
  454. * Given a child path, return a new query ordered by the specified grandchild path.
  455. */
  456. orderByChild(path) {
  457. util.validateArgCount('Query.orderByChild', 1, 1, arguments.length);
  458. return new Query(this.database, database.query(this._delegate, database.orderByChild(path)));
  459. }
  460. /**
  461. * Return a new query ordered by the KeyIndex
  462. */
  463. orderByKey() {
  464. util.validateArgCount('Query.orderByKey', 0, 0, arguments.length);
  465. return new Query(this.database, database.query(this._delegate, database.orderByKey()));
  466. }
  467. /**
  468. * Return a new query ordered by the PriorityIndex
  469. */
  470. orderByPriority() {
  471. util.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);
  472. return new Query(this.database, database.query(this._delegate, database.orderByPriority()));
  473. }
  474. /**
  475. * Return a new query ordered by the ValueIndex
  476. */
  477. orderByValue() {
  478. util.validateArgCount('Query.orderByValue', 0, 0, arguments.length);
  479. return new Query(this.database, database.query(this._delegate, database.orderByValue()));
  480. }
  481. startAt(value = null, name) {
  482. util.validateArgCount('Query.startAt', 0, 2, arguments.length);
  483. return new Query(this.database, database.query(this._delegate, database.startAt(value, name)));
  484. }
  485. startAfter(value = null, name) {
  486. util.validateArgCount('Query.startAfter', 0, 2, arguments.length);
  487. return new Query(this.database, database.query(this._delegate, database.startAfter(value, name)));
  488. }
  489. endAt(value = null, name) {
  490. util.validateArgCount('Query.endAt', 0, 2, arguments.length);
  491. return new Query(this.database, database.query(this._delegate, database.endAt(value, name)));
  492. }
  493. endBefore(value = null, name) {
  494. util.validateArgCount('Query.endBefore', 0, 2, arguments.length);
  495. return new Query(this.database, database.query(this._delegate, database.endBefore(value, name)));
  496. }
  497. /**
  498. * Load the selection of children with exactly the specified value, and, optionally,
  499. * the specified name.
  500. */
  501. equalTo(value, name) {
  502. util.validateArgCount('Query.equalTo', 1, 2, arguments.length);
  503. return new Query(this.database, database.query(this._delegate, database.equalTo(value, name)));
  504. }
  505. /**
  506. * @returns URL for this location.
  507. */
  508. toString() {
  509. util.validateArgCount('Query.toString', 0, 0, arguments.length);
  510. return this._delegate.toString();
  511. }
  512. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  513. // for end-users.
  514. toJSON() {
  515. // An optional spacer argument is unnecessary for a string.
  516. util.validateArgCount('Query.toJSON', 0, 1, arguments.length);
  517. return this._delegate.toJSON();
  518. }
  519. /**
  520. * Return true if this query and the provided query are equivalent; otherwise, return false.
  521. */
  522. isEqual(other) {
  523. util.validateArgCount('Query.isEqual', 1, 1, arguments.length);
  524. if (!(other instanceof Query)) {
  525. const error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';
  526. throw new Error(error);
  527. }
  528. return this._delegate.isEqual(other._delegate);
  529. }
  530. /**
  531. * Helper used by .on and .once to extract the context and or cancel arguments.
  532. * @param fnName - The function name (on or once)
  533. *
  534. */
  535. static getCancelAndContextArgs_(fnName, cancelOrContext, context) {
  536. const ret = { cancel: undefined, context: undefined };
  537. if (cancelOrContext && context) {
  538. ret.cancel = cancelOrContext;
  539. util.validateCallback(fnName, 'cancel', ret.cancel, true);
  540. ret.context = context;
  541. util.validateContextObject(fnName, 'context', ret.context, true);
  542. }
  543. else if (cancelOrContext) {
  544. // we have either a cancel callback or a context.
  545. if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {
  546. // it's a context!
  547. ret.context = cancelOrContext;
  548. }
  549. else if (typeof cancelOrContext === 'function') {
  550. ret.cancel = cancelOrContext;
  551. }
  552. else {
  553. throw new Error(util.errorPrefix(fnName, 'cancelOrContext') +
  554. ' must either be a cancel callback or a context object.');
  555. }
  556. }
  557. return ret;
  558. }
  559. get ref() {
  560. return new Reference(this.database, new database._ReferenceImpl(this._delegate._repo, this._delegate._path));
  561. }
  562. }
  563. class Reference extends Query {
  564. /**
  565. * Call options:
  566. * new Reference(Repo, Path) or
  567. * new Reference(url: string, string|RepoManager)
  568. *
  569. * Externally - this is the firebase.database.Reference type.
  570. */
  571. constructor(database$1, _delegate) {
  572. super(database$1, new database._QueryImpl(_delegate._repo, _delegate._path, new database._QueryParams(), false));
  573. this.database = database$1;
  574. this._delegate = _delegate;
  575. }
  576. /** @returns {?string} */
  577. getKey() {
  578. util.validateArgCount('Reference.key', 0, 0, arguments.length);
  579. return this._delegate.key;
  580. }
  581. child(pathString) {
  582. util.validateArgCount('Reference.child', 1, 1, arguments.length);
  583. if (typeof pathString === 'number') {
  584. pathString = String(pathString);
  585. }
  586. return new Reference(this.database, database.child(this._delegate, pathString));
  587. }
  588. /** @returns {?Reference} */
  589. getParent() {
  590. util.validateArgCount('Reference.parent', 0, 0, arguments.length);
  591. const parent = this._delegate.parent;
  592. return parent ? new Reference(this.database, parent) : null;
  593. }
  594. /** @returns {!Reference} */
  595. getRoot() {
  596. util.validateArgCount('Reference.root', 0, 0, arguments.length);
  597. return new Reference(this.database, this._delegate.root);
  598. }
  599. set(newVal, onComplete) {
  600. util.validateArgCount('Reference.set', 1, 2, arguments.length);
  601. util.validateCallback('Reference.set', 'onComplete', onComplete, true);
  602. const result = database.set(this._delegate, newVal);
  603. if (onComplete) {
  604. result.then(() => onComplete(null), error => onComplete(error));
  605. }
  606. return result;
  607. }
  608. update(values, onComplete) {
  609. util.validateArgCount('Reference.update', 1, 2, arguments.length);
  610. if (Array.isArray(values)) {
  611. const newObjectToMerge = {};
  612. for (let i = 0; i < values.length; ++i) {
  613. newObjectToMerge['' + i] = values[i];
  614. }
  615. values = newObjectToMerge;
  616. warn('Passing an Array to Firebase.update() is deprecated. ' +
  617. 'Use set() if you want to overwrite the existing data, or ' +
  618. 'an Object with integer keys if you really do want to ' +
  619. 'only update some of the children.');
  620. }
  621. database._validateWritablePath('Reference.update', this._delegate._path);
  622. util.validateCallback('Reference.update', 'onComplete', onComplete, true);
  623. const result = database.update(this._delegate, values);
  624. if (onComplete) {
  625. result.then(() => onComplete(null), error => onComplete(error));
  626. }
  627. return result;
  628. }
  629. setWithPriority(newVal, newPriority, onComplete) {
  630. util.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);
  631. util.validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true);
  632. const result = database.setWithPriority(this._delegate, newVal, newPriority);
  633. if (onComplete) {
  634. result.then(() => onComplete(null), error => onComplete(error));
  635. }
  636. return result;
  637. }
  638. remove(onComplete) {
  639. util.validateArgCount('Reference.remove', 0, 1, arguments.length);
  640. util.validateCallback('Reference.remove', 'onComplete', onComplete, true);
  641. const result = database.remove(this._delegate);
  642. if (onComplete) {
  643. result.then(() => onComplete(null), error => onComplete(error));
  644. }
  645. return result;
  646. }
  647. transaction(transactionUpdate, onComplete, applyLocally) {
  648. util.validateArgCount('Reference.transaction', 1, 3, arguments.length);
  649. util.validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false);
  650. util.validateCallback('Reference.transaction', 'onComplete', onComplete, true);
  651. validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true);
  652. const result = database.runTransaction(this._delegate, transactionUpdate, {
  653. applyLocally
  654. }).then(transactionResult => new TransactionResult(transactionResult.committed, new DataSnapshot(this.database, transactionResult.snapshot)));
  655. if (onComplete) {
  656. result.then(transactionResult => onComplete(null, transactionResult.committed, transactionResult.snapshot), error => onComplete(error, false, null));
  657. }
  658. return result;
  659. }
  660. setPriority(priority, onComplete) {
  661. util.validateArgCount('Reference.setPriority', 1, 2, arguments.length);
  662. util.validateCallback('Reference.setPriority', 'onComplete', onComplete, true);
  663. const result = database.setPriority(this._delegate, priority);
  664. if (onComplete) {
  665. result.then(() => onComplete(null), error => onComplete(error));
  666. }
  667. return result;
  668. }
  669. push(value, onComplete) {
  670. util.validateArgCount('Reference.push', 0, 2, arguments.length);
  671. util.validateCallback('Reference.push', 'onComplete', onComplete, true);
  672. const expPromise = database.push(this._delegate, value);
  673. const promise = expPromise.then(expRef => new Reference(this.database, expRef));
  674. if (onComplete) {
  675. promise.then(() => onComplete(null), error => onComplete(error));
  676. }
  677. const result = new Reference(this.database, expPromise);
  678. result.then = promise.then.bind(promise);
  679. result.catch = promise.catch.bind(promise, undefined);
  680. return result;
  681. }
  682. onDisconnect() {
  683. database._validateWritablePath('Reference.onDisconnect', this._delegate._path);
  684. return new OnDisconnect(new database.OnDisconnect(this._delegate._repo, this._delegate._path));
  685. }
  686. get key() {
  687. return this.getKey();
  688. }
  689. get parent() {
  690. return this.getParent();
  691. }
  692. get root() {
  693. return this.getRoot();
  694. }
  695. }
  696. /**
  697. * @license
  698. * Copyright 2017 Google LLC
  699. *
  700. * Licensed under the Apache License, Version 2.0 (the "License");
  701. * you may not use this file except in compliance with the License.
  702. * You may obtain a copy of the License at
  703. *
  704. * http://www.apache.org/licenses/LICENSE-2.0
  705. *
  706. * Unless required by applicable law or agreed to in writing, software
  707. * distributed under the License is distributed on an "AS IS" BASIS,
  708. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  709. * See the License for the specific language governing permissions and
  710. * limitations under the License.
  711. */
  712. /**
  713. * Class representing a firebase database.
  714. */
  715. class Database {
  716. /**
  717. * The constructor should not be called by users of our public API.
  718. */
  719. constructor(_delegate, app) {
  720. this._delegate = _delegate;
  721. this.app = app;
  722. this.INTERNAL = {
  723. delete: () => this._delegate._delete(),
  724. forceWebSockets: database.forceWebSockets,
  725. forceLongPolling: database.forceLongPolling
  726. };
  727. }
  728. /**
  729. * Modify this instance to communicate with the Realtime Database emulator.
  730. *
  731. * <p>Note: This method must be called before performing any other operation.
  732. *
  733. * @param host - the emulator host (ex: localhost)
  734. * @param port - the emulator port (ex: 8080)
  735. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  736. */
  737. useEmulator(host, port, options = {}) {
  738. database.connectDatabaseEmulator(this._delegate, host, port, options);
  739. }
  740. ref(path) {
  741. util.validateArgCount('database.ref', 0, 1, arguments.length);
  742. if (path instanceof Reference) {
  743. const childRef = database.refFromURL(this._delegate, path.toString());
  744. return new Reference(this, childRef);
  745. }
  746. else {
  747. const childRef = database.ref(this._delegate, path);
  748. return new Reference(this, childRef);
  749. }
  750. }
  751. /**
  752. * Returns a reference to the root or the path specified in url.
  753. * We throw a exception if the url is not in the same domain as the
  754. * current repo.
  755. * @returns Firebase reference.
  756. */
  757. refFromURL(url) {
  758. const apiName = 'database.refFromURL';
  759. util.validateArgCount(apiName, 1, 1, arguments.length);
  760. const childRef = database.refFromURL(this._delegate, url);
  761. return new Reference(this, childRef);
  762. }
  763. // Make individual repo go offline.
  764. goOffline() {
  765. util.validateArgCount('database.goOffline', 0, 0, arguments.length);
  766. return database.goOffline(this._delegate);
  767. }
  768. goOnline() {
  769. util.validateArgCount('database.goOnline', 0, 0, arguments.length);
  770. return database.goOnline(this._delegate);
  771. }
  772. }
  773. Database.ServerValue = {
  774. TIMESTAMP: database.serverTimestamp(),
  775. increment: (delta) => database.increment(delta)
  776. };
  777. /**
  778. * Used by console to create a database based on the app,
  779. * passed database URL and a custom auth implementation.
  780. *
  781. * @param app - A valid FirebaseApp-like object
  782. * @param url - A valid Firebase databaseURL
  783. * @param version - custom version e.g. firebase-admin version
  784. * @param customAuthImpl - custom auth implementation
  785. */
  786. function initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, namespace, nodeAdmin = false }) {
  787. database._setSDKVersion(version);
  788. const container = new component.ComponentContainer('database-standalone');
  789. /**
  790. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  791. * any actual function.
  792. */
  793. const authProvider = new component.Provider('auth-internal', container);
  794. authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  795. let appCheckProvider = undefined;
  796. if (customAppCheckImpl) {
  797. appCheckProvider = new component.Provider('app-check-internal', container);
  798. appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  799. }
  800. return {
  801. instance: new Database(database._repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin), app),
  802. namespace
  803. };
  804. }
  805. var INTERNAL = /*#__PURE__*/Object.freeze({
  806. __proto__: null,
  807. initStandalone: initStandalone
  808. });
  809. /**
  810. * @license
  811. * Copyright 2021 Google LLC
  812. *
  813. * Licensed under the Apache License, Version 2.0 (the "License");
  814. * you may not use this file except in compliance with the License.
  815. * You may obtain a copy of the License at
  816. *
  817. * http://www.apache.org/licenses/LICENSE-2.0
  818. *
  819. * Unless required by applicable law or agreed to in writing, software
  820. * distributed under the License is distributed on an "AS IS" BASIS,
  821. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  822. * See the License for the specific language governing permissions and
  823. * limitations under the License.
  824. */
  825. const ServerValue = Database.ServerValue;
  826. function registerDatabase(instance) {
  827. // Register the Database Service with the 'firebase' namespace.
  828. instance.INTERNAL.registerComponent(new component.Component('database-compat', (container, { instanceIdentifier: url }) => {
  829. /* Dependencies */
  830. // getImmediate for FirebaseApp will always succeed
  831. const app = container.getProvider('app-compat').getImmediate();
  832. const databaseExp = container
  833. .getProvider('database')
  834. .getImmediate({ identifier: url });
  835. return new Database(databaseExp, app);
  836. }, "PUBLIC" /* ComponentType.PUBLIC */)
  837. .setServiceProps(
  838. // firebase.database namespace properties
  839. {
  840. Reference,
  841. Query,
  842. Database,
  843. DataSnapshot,
  844. enableLogging: database.enableLogging,
  845. INTERNAL,
  846. ServerValue
  847. })
  848. .setMultipleInstances(true));
  849. instance.registerVersion(name, version, 'node');
  850. }
  851. registerDatabase(firebase__default["default"]);
  852. //# sourceMappingURL=index.js.map