From 92c713b07563b17f6217c2e873755e19aacc5e99 Mon Sep 17 00:00:00 2001 From: Jacob Levine Date: Sun, 6 Jan 2019 13:18:01 -0600 Subject: [PATCH] folder move fix --- functions/index.js | 8 - functions/node_modules/.bin/acorn | 15 - functions/node_modules/.bin/acorn.cmd | 7 - functions/node_modules/.bin/atob | 15 - functions/node_modules/.bin/atob.cmd | 7 - functions/node_modules/.bin/gcs-upload | 15 - functions/node_modules/.bin/gcs-upload.cmd | 7 - functions/node_modules/.bin/gp12-pem | 15 - functions/node_modules/.bin/gp12-pem.cmd | 7 - functions/node_modules/.bin/mime | 15 - functions/node_modules/.bin/mime.cmd | 7 - functions/node_modules/.bin/pbjs | 15 - functions/node_modules/.bin/pbjs.cmd | 7 - functions/node_modules/.bin/pbts | 15 - functions/node_modules/.bin/pbts.cmd | 7 - functions/node_modules/.bin/sshpk-conv | 15 - functions/node_modules/.bin/sshpk-conv.cmd | 7 - functions/node_modules/.bin/sshpk-sign | 15 - functions/node_modules/.bin/sshpk-sign.cmd | 7 - functions/node_modules/.bin/sshpk-verify | 15 - functions/node_modules/.bin/sshpk-verify.cmd | 7 - functions/node_modules/.bin/uuid | 15 - functions/node_modules/.bin/uuid.cmd | 7 - functions/node_modules/.bin/window-size | 15 - functions/node_modules/.bin/window-size.cmd | 7 - .../@firebase/app-types/README.md | 3 - .../@firebase/app-types/index.d.ts | 105 - .../@firebase/app-types/package.json | 54 - .../@firebase/app-types/private.d.ts | 159 - .../node_modules/@firebase/app/README.md | 6 - .../@firebase/app/dist/index.cjs.js | 398 - .../@firebase/app/dist/index.d.ts | 18 - .../@firebase/app/dist/index.esm.js | 394 - .../@firebase/app/dist/index.node.cjs.js | 412 - .../@firebase/app/dist/index.node.d.ts | 18 - .../@firebase/app/dist/index.rn.cjs.js | 412 - .../@firebase/app/dist/index.rn.d.ts | 18 - .../@firebase/app/dist/src/firebaseApp.d.ts | 24 - .../app/dist/test/firebaseApp.test.d.ts | 1 - .../node_modules/@firebase/app/package.json | 104 - .../@firebase/database-types/README.md | 3 - .../@firebase/database-types/index.d.ts | 133 - .../@firebase/database-types/package.json | 56 - .../node_modules/@firebase/database/README.md | 5 - .../@firebase/database/dist/index.cjs.js | 15354 --------- .../@firebase/database/dist/index.d.ts | 28 - .../@firebase/database/dist/index.esm.js | 15341 --------- .../@firebase/database/dist/index.node.cjs.js | 15553 --------- .../@firebase/database/dist/index.node.d.ts | 54 - .../dist/packages/database/index.d.ts | 28 - .../packages/database/src/api/internal.d.ts | 16 - .../database/src/api/test_access.d.ts | 46 - .../src/core/PersistentConnection.d.ts | 194 - .../database/src/core/ReadonlyRestClient.d.ts | 56 - .../database/src/core/RepoManager.d.ts | 64 - .../database/src/core/Repo_transaction.d.ts | 17 - .../database/src/core/ServerActions.d.ts | 80 - .../database/src/core/util/EventEmitter.d.ts | 29 - .../database/src/core/util/OnlineMonitor.d.ts | 24 - .../packages/database/src/core/util/Tree.d.ts | 118 - .../src/core/util/VisibilityMonitor.d.ts | 29 - .../database/src/core/view/QueryParams.d.ts | 154 - .../src/core/view/filter/LimitedFilter.d.ts | 78 - .../src/core/view/filter/NodeFilter.d.ts | 74 - .../src/core/view/filter/RangedFilter.d.ts | 108 - .../packages/database/src/nodePatches.d.ts | 1 - .../src/realtime/BrowserPollConnection.d.ts | 194 - .../database/src/realtime/Connection.d.ts | 101 - .../database/src/realtime/Transport.d.ts | 64 - .../src/realtime/TransportManager.d.ts | 54 - .../src/realtime/WebSocketConnection.d.ts | 129 - .../src/realtime/polling/PacketReceiver.d.ts | 25 - .../test/browser/crawler_support.test.d.ts | 1 - .../database/test/compound_write.test.d.ts | 1 - .../database/test/connection.test.d.ts | 1 - .../packages/database/test/database.test.d.ts | 1 - .../database/test/datasnapshot.test.d.ts | 1 - .../test/helpers/EventAccumulator.d.ts | 33 - .../database/test/helpers/events.d.ts | 21 - .../packages/database/test/helpers/util.d.ts | 44 - .../packages/database/test/info.test.d.ts | 1 - .../packages/database/test/node.test.d.ts | 1 - .../packages/database/test/order.test.d.ts | 1 - .../packages/database/test/order_by.test.d.ts | 1 - .../packages/database/test/path.test.d.ts | 1 - .../packages/database/test/promise.test.d.ts | 1 - .../packages/database/test/query.test.d.ts | 1 - .../packages/database/test/repoinfo.test.d.ts | 1 - .../database/test/sortedmap.test.d.ts | 1 - .../test/sparsesnapshottree.test.d.ts | 1 - .../database/test/transaction.test.d.ts | 1 - .../database/dist/src/api/DataSnapshot.d.ts | 83 - .../database/dist/src/api/Database.d.ts | 57 - .../database/dist/src/api/Query.d.ts | 170 - .../database/dist/src/api/Reference.d.ts | 105 - .../dist/src/api/TransactionResult.d.ts | 29 - .../database/dist/src/api/internal.d.ts | 16 - .../database/dist/src/api/onDisconnect.d.ts | 43 - .../database/dist/src/api/test_access.d.ts | 46 - .../dist/src/core/AuthTokenProvider.d.ts | 35 - .../database/dist/src/core/CompoundWrite.d.ts | 104 - .../dist/src/core/PersistentConnection.d.ts | 194 - .../dist/src/core/ReadonlyRestClient.d.ts | 56 - .../database/dist/src/core/Repo.d.ts | 168 - .../database/dist/src/core/RepoInfo.d.ts | 40 - .../database/dist/src/core/RepoManager.d.ts | 64 - .../dist/src/core/Repo_transaction.d.ts | 17 - .../database/dist/src/core/ServerActions.d.ts | 80 - .../dist/src/core/SnapshotHolder.d.ts | 12 - .../dist/src/core/SparseSnapshotTree.d.ts | 70 - .../database/dist/src/core/SyncPoint.d.ts | 98 - .../database/dist/src/core/SyncTree.d.ts | 303 - .../database/dist/src/core/WriteTree.d.ts | 307 - .../dist/src/core/operation/AckUserWrite.d.ts | 26 - .../src/core/operation/ListenComplete.d.ts | 31 - .../dist/src/core/operation/Merge.d.ts | 45 - .../dist/src/core/operation/Operation.d.ts | 62 - .../dist/src/core/operation/Overwrite.d.ts | 34 - .../dist/src/core/snap/ChildrenNode.d.ts | 164 - .../database/dist/src/core/snap/IndexMap.d.ts | 55 - .../database/dist/src/core/snap/LeafNode.d.ts | 89 - .../database/dist/src/core/snap/Node.d.ts | 147 - .../database/dist/src/core/snap/childSet.d.ts | 18 - .../dist/src/core/snap/comparators.d.ts | 3 - .../dist/src/core/snap/indexes/Index.d.ts | 68 - .../dist/src/core/snap/indexes/KeyIndex.d.ts | 52 - .../dist/src/core/snap/indexes/PathIndex.d.ts | 38 - .../src/core/snap/indexes/PriorityIndex.d.ts | 57 - .../src/core/snap/indexes/ValueIndex.d.ts | 55 - .../dist/src/core/snap/nodeFromJSON.d.ts | 9 - .../database/dist/src/core/snap/snap.d.ts | 13 - .../dist/src/core/stats/StatsCollection.d.ts | 12 - .../dist/src/core/stats/StatsListener.d.ts | 15 - .../dist/src/core/stats/StatsManager.d.ts | 23 - .../dist/src/core/stats/StatsReporter.d.ts | 17 - .../src/core/storage/DOMStorageWrapper.d.ts | 39 - .../dist/src/core/storage/MemoryStorage.d.ts | 13 - .../dist/src/core/storage/storage.d.ts | 21 - .../dist/src/core/util/CountedSet.d.ts | 52 - .../dist/src/core/util/EventEmitter.d.ts | 29 - .../dist/src/core/util/ImmutableTree.d.ts | 156 - .../dist/src/core/util/NextPushId.d.ts | 15 - .../dist/src/core/util/OnlineMonitor.d.ts | 24 - .../database/dist/src/core/util/Path.d.ts | 116 - .../dist/src/core/util/ServerValues.d.ts | 41 - .../dist/src/core/util/SortedMap.d.ts | 361 - .../database/dist/src/core/util/Tree.d.ts | 118 - .../dist/src/core/util/VisibilityMonitor.d.ts | 29 - .../dist/src/core/util/libs/parser.d.ts | 40 - .../database/dist/src/core/util/util.d.ts | 223 - .../dist/src/core/util/validation.d.ts | 107 - .../dist/src/core/view/CacheNode.d.ts | 58 - .../database/dist/src/core/view/Change.d.ts | 73 - .../src/core/view/ChildChangeAccumulator.d.ts | 15 - .../src/core/view/CompleteChildSource.d.ts | 75 - .../database/dist/src/core/view/Event.d.ts | 85 - .../dist/src/core/view/EventGenerator.d.ts | 76 - .../dist/src/core/view/EventQueue.d.ts | 98 - .../dist/src/core/view/EventRegistration.d.ts | 153 - .../dist/src/core/view/QueryParams.d.ts | 154 - .../database/dist/src/core/view/View.d.ts | 81 - .../dist/src/core/view/ViewCache.d.ts | 54 - .../dist/src/core/view/ViewProcessor.d.ts | 165 - .../src/core/view/filter/IndexedFilter.d.ts | 38 - .../src/core/view/filter/LimitedFilter.d.ts | 78 - .../dist/src/core/view/filter/NodeFilter.d.ts | 74 - .../src/core/view/filter/RangedFilter.d.ts | 108 - .../src/realtime/BrowserPollConnection.d.ts | 194 - .../dist/src/realtime/Connection.d.ts | 101 - .../database/dist/src/realtime/Constants.d.ts | 24 - .../database/dist/src/realtime/Transport.d.ts | 64 - .../dist/src/realtime/TransportManager.d.ts | 54 - .../src/realtime/WebSocketConnection.d.ts | 129 - .../src/realtime/polling/PacketReceiver.d.ts | 25 - .../test/browser/crawler_support.test.d.ts | 1 - .../dist/test/compound_write.test.d.ts | 1 - .../database/dist/test/connection.test.d.ts | 1 - .../database/dist/test/database.test.d.ts | 1 - .../database/dist/test/datasnapshot.test.d.ts | 1 - .../dist/test/helpers/EventAccumulator.d.ts | 33 - .../database/dist/test/helpers/events.d.ts | 21 - .../database/dist/test/helpers/util.d.ts | 44 - .../database/dist/test/info.test.d.ts | 1 - .../database/dist/test/node.test.d.ts | 1 - .../database/dist/test/order.test.d.ts | 1 - .../database/dist/test/order_by.test.d.ts | 1 - .../database/dist/test/path.test.d.ts | 1 - .../database/dist/test/promise.test.d.ts | 1 - .../database/dist/test/query.test.d.ts | 1 - .../database/dist/test/repoinfo.test.d.ts | 1 - .../database/dist/test/sortedmap.test.d.ts | 1 - .../dist/test/sparsesnapshottree.test.d.ts | 1 - .../database/dist/test/transaction.test.d.ts | 1 - .../@firebase/database/package.json | 105 - .../node_modules/@firebase/logger/README.md | 40 - .../@firebase/logger/dist/index.cjs.js | 186 - .../@firebase/logger/dist/index.d.ts | 18 - .../@firebase/logger/dist/index.esm.js | 193 - .../@firebase/logger/dist/src/logger.d.ts | 72 - .../logger/dist/test/logger.test.d.ts | 1 - .../@firebase/logger/package.json | 90 - .../node_modules/@firebase/util/README.md | 32 - .../@firebase/util/dist/index.cjs.js | 1776 - .../@firebase/util/dist/index.d.ts | 30 - .../@firebase/util/dist/index.esm.js | 1723 - .../@firebase/util/dist/index.node.cjs.js | 1778 - .../@firebase/util/dist/index.node.d.ts | 15 - .../@firebase/util/dist/src/assert.d.ts | 12 - .../@firebase/util/dist/src/constants.d.ts | 23 - .../@firebase/util/dist/src/crypt.d.ts | 31 - .../@firebase/util/dist/src/deepCopy.d.ts | 33 - .../@firebase/util/dist/src/deferred.d.ts | 29 - .../@firebase/util/dist/src/environment.d.ts | 26 - .../@firebase/util/dist/src/errors.d.ts | 85 - .../@firebase/util/dist/src/hash.d.ts | 35 - .../@firebase/util/dist/src/json.d.ts | 28 - .../@firebase/util/dist/src/jwt.d.ts | 61 - .../@firebase/util/dist/src/obj.d.ts | 62 - .../@firebase/util/dist/src/query.d.ts | 16 - .../@firebase/util/dist/src/sha1.d.ts | 88 - .../@firebase/util/dist/src/subscribe.d.ts | 48 - .../@firebase/util/dist/src/utf8.d.ts | 11 - .../@firebase/util/dist/src/validation.d.ts | 43 - .../@firebase/util/dist/test/base64.test.d.ts | 1 - .../util/dist/test/deepCopy.test.d.ts | 1 - .../@firebase/util/dist/test/errors.test.d.ts | 1 - .../util/dist/test/subscribe.test.d.ts | 1 - .../node_modules/@firebase/util/package.json | 94 - .../@google-cloud/common/CONTRIBUTORS | 19 - .../node_modules/@google-cloud/common/LICENSE | 202 - .../@google-cloud/common/README.md | 79 - .../node_modules/retry-request/index.d.ts | 22 - .../node_modules/retry-request/index.js | 209 - .../common/node_modules/retry-request/license | 20 - .../node_modules/retry-request/package.json | 70 - .../node_modules/retry-request/readme.md | 152 - .../@google-cloud/common/package.json | 166 - .../@google-cloud/common/src/index.js | 51 - .../@google-cloud/common/src/logger.js | 71 - .../@google-cloud/common/src/operation.js | 193 - .../@google-cloud/common/src/paginator.js | 267 - .../common/src/service-object.js | 392 - .../@google-cloud/common/src/service.js | 200 - .../@google-cloud/common/src/util.js | 830 - .../@google-cloud/firestore/LICENSE | 202 - .../@google-cloud/firestore/README.md | 141 - .../firestore/build/protos/README.md | 33 - .../build/protos/firestore_proto_api.d.ts | 10582 ------ .../build/protos/firestore_proto_api.js | 26706 ---------------- .../protos/google/firestore/v1beta1/.DS_Store | Bin 6148 -> 0 bytes .../google/firestore/v1beta1/common.proto | 83 - .../google/firestore/v1beta1/document.proto | 150 - .../google/firestore/v1beta1/firestore.proto | 760 - .../google/firestore/v1beta1/query.proto | 235 - .../google/firestore/v1beta1/write.proto | 214 - .../firestore/build/src/backoff.js | 197 - .../firestore/build/src/convert.js | 213 - .../firestore/build/src/document-change.js | 173 - .../firestore/build/src/document.js | 1025 - .../firestore/build/src/field-value.js | 324 - .../firestore/build/src/geo-point.js | 108 - .../firestore/build/src/index.js | 1275 - .../firestore/build/src/logger.js | 60 - .../firestore/build/src/order.js | 238 - .../@google-cloud/firestore/build/src/path.js | 510 - .../@google-cloud/firestore/build/src/pool.js | 124 - .../firestore/build/src/reference.js | 1782 -- .../firestore/build/src/serializer.js | 228 - .../firestore/build/src/timestamp.js | 225 - .../firestore/build/src/transaction.js | 311 - .../firestore/build/src/types.js | 17 - .../@google-cloud/firestore/build/src/util.js | 46 - .../google/firestore/v1beta1/doc_common.js | 107 - .../google/firestore/v1beta1/doc_document.js | 183 - .../google/firestore/v1beta1/doc_firestore.js | 881 - .../doc/google/firestore/v1beta1/doc_query.js | 379 - .../doc/google/firestore/v1beta1/doc_write.js | 262 - .../v1beta1/doc/google/protobuf/doc_any.js | 130 - .../v1beta1/doc/google/protobuf/doc_empty.js | 33 - .../doc/google/protobuf/doc_timestamp.js | 115 - .../doc/google/protobuf/doc_wrappers.js | 151 - .../src/v1beta1/doc/google/rpc/doc_status.js | 92 - .../build/src/v1beta1/firestore_client.js | 1398 - .../src/v1beta1/firestore_client_config.json | 100 - .../firestore/build/src/v1beta1/index.js | 29 - .../firestore/build/src/validate.js | 184 - .../firestore/build/src/watch.js | 664 - .../firestore/build/src/write-batch.js | 510 - .../@google-cloud/firestore/package.json | 145 - .../firestore/types/firestore.d.ts | 1244 - .../@google-cloud/projectify/CHANGELOG.md | 58 - .../@google-cloud/projectify/LICENSE | 202 - .../@google-cloud/projectify/README.md | 15 - .../projectify/build/src/index.d.ts | 31 - .../projectify/build/src/index.js | 64 - .../@google-cloud/projectify/package.json | 86 - .../@google-cloud/storage/CONTRIBUTORS | 26 - .../@google-cloud/storage/LICENSE | 202 - .../@google-cloud/storage/README.md | 134 - .../@google-cloud/storage/package.json | 209 - .../@google-cloud/storage/src/acl.js | 766 - .../@google-cloud/storage/src/bucket.js | 2458 -- .../@google-cloud/storage/src/channel.js | 116 - .../@google-cloud/storage/src/file.js | 2475 -- .../@google-cloud/storage/src/iam.js | 300 - .../@google-cloud/storage/src/index.js | 591 - .../@google-cloud/storage/src/notification.js | 350 - .../node_modules/@grpc/proto-loader/README.md | 51 - .../@grpc/proto-loader/build/src/index.d.ts | 70 - .../@grpc/proto-loader/build/src/index.js | 157 - .../node_modules/@types/node/LICENSE | 21 - .../node_modules/@types/node/README.md | 16 - .../node_modules/@types/node/index.d.ts | 7802 ----- .../node_modules/@types/node/inspector.d.ts | 2530 -- .../node_modules/@types/node/package.json | 152 - .../@grpc/proto-loader/package.json | 82 - .../@mrmlnc/readdir-enhanced/CHANGELOG.md | 49 - .../@mrmlnc/readdir-enhanced/LICENSE | 23 - .../@mrmlnc/readdir-enhanced/README.md | 347 - .../readdir-enhanced/lib/async/for-each.js | 29 - .../readdir-enhanced/lib/async/index.js | 48 - .../@mrmlnc/readdir-enhanced/lib/call.js | 54 - .../readdir-enhanced/lib/directory-reader.js | 380 - .../@mrmlnc/readdir-enhanced/lib/index.js | 85 - .../readdir-enhanced/lib/normalize-options.js | 177 - .../@mrmlnc/readdir-enhanced/lib/stat.js | 74 - .../readdir-enhanced/lib/stream/index.js | 25 - .../readdir-enhanced/lib/sync/for-each.js | 22 - .../@mrmlnc/readdir-enhanced/lib/sync/fs.js | 64 - .../readdir-enhanced/lib/sync/index.js | 34 - .../@mrmlnc/readdir-enhanced/package.json | 89 - .../@mrmlnc/readdir-enhanced/types.d.ts | 67 - .../@nodelib/fs.stat/package.json | 57 - functions/package-lock.json | 3878 --- functions/package.json | 16 - 335 files changed, 144108 deletions(-) delete mode 100644 functions/index.js delete mode 100644 functions/node_modules/.bin/acorn delete mode 100644 functions/node_modules/.bin/acorn.cmd delete mode 100644 functions/node_modules/.bin/atob delete mode 100644 functions/node_modules/.bin/atob.cmd delete mode 100644 functions/node_modules/.bin/gcs-upload delete mode 100644 functions/node_modules/.bin/gcs-upload.cmd delete mode 100644 functions/node_modules/.bin/gp12-pem delete mode 100644 functions/node_modules/.bin/gp12-pem.cmd delete mode 100644 functions/node_modules/.bin/mime delete mode 100644 functions/node_modules/.bin/mime.cmd delete mode 100644 functions/node_modules/.bin/pbjs delete mode 100644 functions/node_modules/.bin/pbjs.cmd delete mode 100644 functions/node_modules/.bin/pbts delete mode 100644 functions/node_modules/.bin/pbts.cmd delete mode 100644 functions/node_modules/.bin/sshpk-conv delete mode 100644 functions/node_modules/.bin/sshpk-conv.cmd delete mode 100644 functions/node_modules/.bin/sshpk-sign delete mode 100644 functions/node_modules/.bin/sshpk-sign.cmd delete mode 100644 functions/node_modules/.bin/sshpk-verify delete mode 100644 functions/node_modules/.bin/sshpk-verify.cmd delete mode 100644 functions/node_modules/.bin/uuid delete mode 100644 functions/node_modules/.bin/uuid.cmd delete mode 100644 functions/node_modules/.bin/window-size delete mode 100644 functions/node_modules/.bin/window-size.cmd delete mode 100644 functions/node_modules/@firebase/app-types/README.md delete mode 100644 functions/node_modules/@firebase/app-types/index.d.ts delete mode 100644 functions/node_modules/@firebase/app-types/package.json delete mode 100644 functions/node_modules/@firebase/app-types/private.d.ts delete mode 100644 functions/node_modules/@firebase/app/README.md delete mode 100644 functions/node_modules/@firebase/app/dist/index.cjs.js delete mode 100644 functions/node_modules/@firebase/app/dist/index.d.ts delete mode 100644 functions/node_modules/@firebase/app/dist/index.esm.js delete mode 100644 functions/node_modules/@firebase/app/dist/index.node.cjs.js delete mode 100644 functions/node_modules/@firebase/app/dist/index.node.d.ts delete mode 100644 functions/node_modules/@firebase/app/dist/index.rn.cjs.js delete mode 100644 functions/node_modules/@firebase/app/dist/index.rn.d.ts delete mode 100644 functions/node_modules/@firebase/app/dist/src/firebaseApp.d.ts delete mode 100644 functions/node_modules/@firebase/app/dist/test/firebaseApp.test.d.ts delete mode 100644 functions/node_modules/@firebase/app/package.json delete mode 100644 functions/node_modules/@firebase/database-types/README.md delete mode 100644 functions/node_modules/@firebase/database-types/index.d.ts delete mode 100644 functions/node_modules/@firebase/database-types/package.json delete mode 100644 functions/node_modules/@firebase/database/README.md delete mode 100644 functions/node_modules/@firebase/database/dist/index.cjs.js delete mode 100644 functions/node_modules/@firebase/database/dist/index.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/index.esm.js delete mode 100644 functions/node_modules/@firebase/database/dist/index.node.cjs.js delete mode 100644 functions/node_modules/@firebase/database/dist/index.node.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/index.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/api/internal.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/api/test_access.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/PersistentConnection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/ReadonlyRestClient.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/RepoManager.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/Repo_transaction.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/ServerActions.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/util/EventEmitter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/util/OnlineMonitor.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/util/Tree.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/util/VisibilityMonitor.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/view/QueryParams.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/LimitedFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/NodeFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/RangedFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/nodePatches.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/realtime/BrowserPollConnection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Connection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Transport.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/realtime/TransportManager.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/realtime/WebSocketConnection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/src/realtime/polling/PacketReceiver.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/browser/crawler_support.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/compound_write.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/connection.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/database.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/datasnapshot.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/helpers/EventAccumulator.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/helpers/events.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/helpers/util.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/info.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/node.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/order.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/order_by.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/path.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/promise.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/query.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/repoinfo.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/sortedmap.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/sparsesnapshottree.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/packages/database/test/transaction.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/DataSnapshot.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/Database.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/Query.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/Reference.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/TransactionResult.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/internal.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/onDisconnect.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/api/test_access.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/Repo.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/RepoManager.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/Repo_transaction.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/CountedSet.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/Path.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/util.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/util/validation.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/Change.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/Event.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/View.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/browser/crawler_support.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/compound_write.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/connection.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/database.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/datasnapshot.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/helpers/events.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/helpers/util.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/info.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/node.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/order.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/order_by.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/path.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/promise.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/query.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/repoinfo.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/sortedmap.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/sparsesnapshottree.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/dist/test/transaction.test.d.ts delete mode 100644 functions/node_modules/@firebase/database/package.json delete mode 100644 functions/node_modules/@firebase/logger/README.md delete mode 100644 functions/node_modules/@firebase/logger/dist/index.cjs.js delete mode 100644 functions/node_modules/@firebase/logger/dist/index.d.ts delete mode 100644 functions/node_modules/@firebase/logger/dist/index.esm.js delete mode 100644 functions/node_modules/@firebase/logger/dist/src/logger.d.ts delete mode 100644 functions/node_modules/@firebase/logger/dist/test/logger.test.d.ts delete mode 100644 functions/node_modules/@firebase/logger/package.json delete mode 100644 functions/node_modules/@firebase/util/README.md delete mode 100644 functions/node_modules/@firebase/util/dist/index.cjs.js delete mode 100644 functions/node_modules/@firebase/util/dist/index.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/index.esm.js delete mode 100644 functions/node_modules/@firebase/util/dist/index.node.cjs.js delete mode 100644 functions/node_modules/@firebase/util/dist/index.node.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/assert.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/constants.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/crypt.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/deepCopy.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/deferred.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/environment.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/errors.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/hash.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/json.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/jwt.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/obj.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/query.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/sha1.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/subscribe.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/utf8.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/src/validation.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/test/base64.test.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/test/errors.test.d.ts delete mode 100644 functions/node_modules/@firebase/util/dist/test/subscribe.test.d.ts delete mode 100644 functions/node_modules/@firebase/util/package.json delete mode 100644 functions/node_modules/@google-cloud/common/CONTRIBUTORS delete mode 100644 functions/node_modules/@google-cloud/common/LICENSE delete mode 100644 functions/node_modules/@google-cloud/common/README.md delete mode 100644 functions/node_modules/@google-cloud/common/node_modules/retry-request/index.d.ts delete mode 100644 functions/node_modules/@google-cloud/common/node_modules/retry-request/index.js delete mode 100644 functions/node_modules/@google-cloud/common/node_modules/retry-request/license delete mode 100644 functions/node_modules/@google-cloud/common/node_modules/retry-request/package.json delete mode 100644 functions/node_modules/@google-cloud/common/node_modules/retry-request/readme.md delete mode 100644 functions/node_modules/@google-cloud/common/package.json delete mode 100644 functions/node_modules/@google-cloud/common/src/index.js delete mode 100644 functions/node_modules/@google-cloud/common/src/logger.js delete mode 100644 functions/node_modules/@google-cloud/common/src/operation.js delete mode 100644 functions/node_modules/@google-cloud/common/src/paginator.js delete mode 100644 functions/node_modules/@google-cloud/common/src/service-object.js delete mode 100644 functions/node_modules/@google-cloud/common/src/service.js delete mode 100644 functions/node_modules/@google-cloud/common/src/util.js delete mode 100644 functions/node_modules/@google-cloud/firestore/LICENSE delete mode 100644 functions/node_modules/@google-cloud/firestore/README.md delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/README.md delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.d.ts delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/.DS_Store delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/common.proto delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/document.proto delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto delete mode 100644 functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/backoff.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/convert.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/document-change.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/document.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/field-value.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/geo-point.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/index.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/logger.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/order.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/path.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/pool.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/reference.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/serializer.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/timestamp.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/transaction.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/types.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/util.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_common.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_document.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_firestore.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_query.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_write.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_any.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_empty.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_timestamp.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_wrappers.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/rpc/doc_status.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/validate.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/watch.js delete mode 100644 functions/node_modules/@google-cloud/firestore/build/src/write-batch.js delete mode 100644 functions/node_modules/@google-cloud/firestore/package.json delete mode 100644 functions/node_modules/@google-cloud/firestore/types/firestore.d.ts delete mode 100644 functions/node_modules/@google-cloud/projectify/CHANGELOG.md delete mode 100644 functions/node_modules/@google-cloud/projectify/LICENSE delete mode 100644 functions/node_modules/@google-cloud/projectify/README.md delete mode 100644 functions/node_modules/@google-cloud/projectify/build/src/index.d.ts delete mode 100644 functions/node_modules/@google-cloud/projectify/build/src/index.js delete mode 100644 functions/node_modules/@google-cloud/projectify/package.json delete mode 100644 functions/node_modules/@google-cloud/storage/CONTRIBUTORS delete mode 100644 functions/node_modules/@google-cloud/storage/LICENSE delete mode 100644 functions/node_modules/@google-cloud/storage/README.md delete mode 100644 functions/node_modules/@google-cloud/storage/package.json delete mode 100644 functions/node_modules/@google-cloud/storage/src/acl.js delete mode 100644 functions/node_modules/@google-cloud/storage/src/bucket.js delete mode 100644 functions/node_modules/@google-cloud/storage/src/channel.js delete mode 100644 functions/node_modules/@google-cloud/storage/src/file.js delete mode 100644 functions/node_modules/@google-cloud/storage/src/iam.js delete mode 100644 functions/node_modules/@google-cloud/storage/src/index.js delete mode 100644 functions/node_modules/@google-cloud/storage/src/notification.js delete mode 100644 functions/node_modules/@grpc/proto-loader/README.md delete mode 100644 functions/node_modules/@grpc/proto-loader/build/src/index.d.ts delete mode 100644 functions/node_modules/@grpc/proto-loader/build/src/index.js delete mode 100644 functions/node_modules/@grpc/proto-loader/node_modules/@types/node/LICENSE delete mode 100644 functions/node_modules/@grpc/proto-loader/node_modules/@types/node/README.md delete mode 100644 functions/node_modules/@grpc/proto-loader/node_modules/@types/node/index.d.ts delete mode 100644 functions/node_modules/@grpc/proto-loader/node_modules/@types/node/inspector.d.ts delete mode 100644 functions/node_modules/@grpc/proto-loader/node_modules/@types/node/package.json delete mode 100644 functions/node_modules/@grpc/proto-loader/package.json delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/CHANGELOG.md delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/LICENSE delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/README.md delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/for-each.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/index.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/call.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/directory-reader.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/index.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/normalize-options.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/stat.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/stream/index.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/for-each.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/fs.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/index.js delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/package.json delete mode 100644 functions/node_modules/@mrmlnc/readdir-enhanced/types.d.ts delete mode 100644 functions/node_modules/@nodelib/fs.stat/package.json delete mode 100644 functions/package-lock.json delete mode 100644 functions/package.json diff --git a/functions/index.js b/functions/index.js deleted file mode 100644 index bd698a23..00000000 --- a/functions/index.js +++ /dev/null @@ -1,8 +0,0 @@ -const functions = require('firebase-functions'); - -// // Create and Deploy Your First Cloud Functions -// // https://firebase.google.com/docs/functions/write-firebase-functions -// -// exports.helloWorld = functions.https.onRequest((request, response) => { -// response.send("Hello from Firebase!"); -// }); diff --git a/functions/node_modules/.bin/acorn b/functions/node_modules/.bin/acorn deleted file mode 100644 index 558ebb98..00000000 --- a/functions/node_modules/.bin/acorn +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" - ret=$? -else - node "$basedir/../acorn/bin/acorn" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/acorn.cmd b/functions/node_modules/.bin/acorn.cmd deleted file mode 100644 index 45c0c3d0..00000000 --- a/functions/node_modules/.bin/acorn.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\acorn\bin\acorn" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\acorn\bin\acorn" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/atob b/functions/node_modules/.bin/atob deleted file mode 100644 index 50896794..00000000 --- a/functions/node_modules/.bin/atob +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../atob/bin/atob.js" "$@" - ret=$? -else - node "$basedir/../atob/bin/atob.js" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/atob.cmd b/functions/node_modules/.bin/atob.cmd deleted file mode 100644 index 34edc9aa..00000000 --- a/functions/node_modules/.bin/atob.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\atob\bin\atob.js" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\atob\bin\atob.js" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/gcs-upload b/functions/node_modules/.bin/gcs-upload deleted file mode 100644 index 165fd8f9..00000000 --- a/functions/node_modules/.bin/gcs-upload +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../gcs-resumable-upload/build/src/cli.js" "$@" - ret=$? -else - node "$basedir/../gcs-resumable-upload/build/src/cli.js" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/gcs-upload.cmd b/functions/node_modules/.bin/gcs-upload.cmd deleted file mode 100644 index 052f7df3..00000000 --- a/functions/node_modules/.bin/gcs-upload.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\gcs-resumable-upload\build\src\cli.js" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\gcs-resumable-upload\build\src\cli.js" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/gp12-pem b/functions/node_modules/.bin/gp12-pem deleted file mode 100644 index a473f8f9..00000000 --- a/functions/node_modules/.bin/gp12-pem +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../google-p12-pem/build/src/bin/gp12-pem.js" "$@" - ret=$? -else - node "$basedir/../google-p12-pem/build/src/bin/gp12-pem.js" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/gp12-pem.cmd b/functions/node_modules/.bin/gp12-pem.cmd deleted file mode 100644 index 83fabf17..00000000 --- a/functions/node_modules/.bin/gp12-pem.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\google-p12-pem\build\src\bin\gp12-pem.js" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\google-p12-pem\build\src\bin\gp12-pem.js" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/mime b/functions/node_modules/.bin/mime deleted file mode 100644 index 0dbddf07..00000000 --- a/functions/node_modules/.bin/mime +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../mime/cli.js" "$@" - ret=$? -else - node "$basedir/../mime/cli.js" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/mime.cmd b/functions/node_modules/.bin/mime.cmd deleted file mode 100644 index 81695620..00000000 --- a/functions/node_modules/.bin/mime.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\mime\cli.js" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\mime\cli.js" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/pbjs b/functions/node_modules/.bin/pbjs deleted file mode 100644 index a786ae9d..00000000 --- a/functions/node_modules/.bin/pbjs +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../protobufjs/bin/pbjs" "$@" - ret=$? -else - node "$basedir/../protobufjs/bin/pbjs" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/pbjs.cmd b/functions/node_modules/.bin/pbjs.cmd deleted file mode 100644 index 6a94ef94..00000000 --- a/functions/node_modules/.bin/pbjs.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\protobufjs\bin\pbjs" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\protobufjs\bin\pbjs" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/pbts b/functions/node_modules/.bin/pbts deleted file mode 100644 index 8dd2c444..00000000 --- a/functions/node_modules/.bin/pbts +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../protobufjs/bin/pbts" "$@" - ret=$? -else - node "$basedir/../protobufjs/bin/pbts" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/pbts.cmd b/functions/node_modules/.bin/pbts.cmd deleted file mode 100644 index d9381f9c..00000000 --- a/functions/node_modules/.bin/pbts.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\protobufjs\bin\pbts" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\protobufjs\bin\pbts" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/sshpk-conv b/functions/node_modules/.bin/sshpk-conv deleted file mode 100644 index c9c2987e..00000000 --- a/functions/node_modules/.bin/sshpk-conv +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../sshpk/bin/sshpk-conv" "$@" - ret=$? -else - node "$basedir/../sshpk/bin/sshpk-conv" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/sshpk-conv.cmd b/functions/node_modules/.bin/sshpk-conv.cmd deleted file mode 100644 index dde70b02..00000000 --- a/functions/node_modules/.bin/sshpk-conv.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-conv" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\sshpk\bin\sshpk-conv" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/sshpk-sign b/functions/node_modules/.bin/sshpk-sign deleted file mode 100644 index 1a921248..00000000 --- a/functions/node_modules/.bin/sshpk-sign +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../sshpk/bin/sshpk-sign" "$@" - ret=$? -else - node "$basedir/../sshpk/bin/sshpk-sign" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/sshpk-sign.cmd b/functions/node_modules/.bin/sshpk-sign.cmd deleted file mode 100644 index 45025ec1..00000000 --- a/functions/node_modules/.bin/sshpk-sign.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-sign" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\sshpk\bin\sshpk-sign" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/sshpk-verify b/functions/node_modules/.bin/sshpk-verify deleted file mode 100644 index 597a66b8..00000000 --- a/functions/node_modules/.bin/sshpk-verify +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../sshpk/bin/sshpk-verify" "$@" - ret=$? -else - node "$basedir/../sshpk/bin/sshpk-verify" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/sshpk-verify.cmd b/functions/node_modules/.bin/sshpk-verify.cmd deleted file mode 100644 index 1b5fc0c1..00000000 --- a/functions/node_modules/.bin/sshpk-verify.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-verify" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\sshpk\bin\sshpk-verify" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/uuid b/functions/node_modules/.bin/uuid deleted file mode 100644 index f3bfcf46..00000000 --- a/functions/node_modules/.bin/uuid +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../uuid/bin/uuid" "$@" - ret=$? -else - node "$basedir/../uuid/bin/uuid" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/uuid.cmd b/functions/node_modules/.bin/uuid.cmd deleted file mode 100644 index da52d68a..00000000 --- a/functions/node_modules/.bin/uuid.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\uuid\bin\uuid" %* -) \ No newline at end of file diff --git a/functions/node_modules/.bin/window-size b/functions/node_modules/.bin/window-size deleted file mode 100644 index d422c13d..00000000 --- a/functions/node_modules/.bin/window-size +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../window-size/cli.js" "$@" - ret=$? -else - node "$basedir/../window-size/cli.js" "$@" - ret=$? -fi -exit $ret diff --git a/functions/node_modules/.bin/window-size.cmd b/functions/node_modules/.bin/window-size.cmd deleted file mode 100644 index e1cf6266..00000000 --- a/functions/node_modules/.bin/window-size.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@IF EXIST "%~dp0\node.exe" ( - "%~dp0\node.exe" "%~dp0\..\window-size\cli.js" %* -) ELSE ( - @SETLOCAL - @SET PATHEXT=%PATHEXT:;.JS;=;% - node "%~dp0\..\window-size\cli.js" %* -) \ No newline at end of file diff --git a/functions/node_modules/@firebase/app-types/README.md b/functions/node_modules/@firebase/app-types/README.md deleted file mode 100644 index 931932c2..00000000 --- a/functions/node_modules/@firebase/app-types/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# @firebase/app-types - -**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/functions/node_modules/@firebase/app-types/index.d.ts b/functions/node_modules/@firebase/app-types/index.d.ts deleted file mode 100644 index d1c4368e..00000000 --- a/functions/node_modules/@firebase/app-types/index.d.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export type FirebaseOptions = { - apiKey?: string; - authDomain?: string; - databaseURL?: string; - projectId?: string; - storageBucket?: string; - messagingSenderId?: string; - [name: string]: any; -}; - -export interface FirebaseAppConfig { - name?: string; - automaticDataCollectionEnabled?: boolean; -} - -export class FirebaseApp { - /** - * The (read-only) name (identifier) for this App. '[DEFAULT]' is the default - * App. - */ - name: string; - - /** - * The (read-only) configuration options from the app initialization. - */ - options: FirebaseOptions; - - /** - * The settable config flag for GDPR opt-in/opt-out - */ - automaticDataCollectionEnabled: boolean; - - /** - * Make the given App unusable and free resources. - */ - delete(): Promise; -} - -export interface FirebaseNamespace { - /** - * Create (and initialize) a FirebaseApp. - * - * @param options Options to configure the services used in the App. - * @param config The optional config for your firebase app - */ - initializeApp( - options: FirebaseOptions, - config?: FirebaseAppConfig - ): FirebaseApp; - /** - * Create (and initialize) a FirebaseApp. - * - * @param options Options to configure the services used in the App. - * @param name The optional name of the app to initialize ('[DEFAULT]' if - * omitted) - */ - initializeApp(options: FirebaseOptions, name?: string): FirebaseApp; - - app: { - /** - * Retrieve an instance of a FirebaseApp. - * - * Usage: firebase.app() - * - * @param name The optional name of the app to return ('[DEFAULT]' if omitted) - */ - (name?: string): FirebaseApp; - - /** - * For testing FirebaseApp instances: - * app() instanceof firebase.app.App - * - * DO NOT call this constuctor directly (use firebase.app() instead). - */ - App: typeof FirebaseApp; - }; - - /** - * A (read-only) array of all the initialized Apps. - */ - apps: FirebaseApp[]; - - // Inherit the type information of our exported Promise implementation from - // es6-promises. - Promise: typeof Promise; - - // The current SDK version. - SDK_VERSION: string; -} diff --git a/functions/node_modules/@firebase/app-types/package.json b/functions/node_modules/@firebase/app-types/package.json deleted file mode 100644 index 1be59e22..00000000 --- a/functions/node_modules/@firebase/app-types/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "_from": "@firebase/app-types@0.3.2", - "_id": "@firebase/app-types@0.3.2", - "_inBundle": false, - "_integrity": "sha512-ZD8lTgW07NGgo75bTyBJA8Lt9+NweNzot7lrsBtIvfciwUzaFJLsv2EShqjBeuhF7RpG6YFucJ6m67w5buCtzw==", - "_location": "/@firebase/app-types", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "@firebase/app-types@0.3.2", - "name": "@firebase/app-types", - "escapedName": "@firebase%2fapp-types", - "scope": "@firebase", - "rawSpec": "0.3.2", - "saveSpec": null, - "fetchSpec": "0.3.2" - }, - "_requiredBy": [ - "/@firebase/app" - ], - "_resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.3.2.tgz", - "_shasum": "a92dc544290e2893bd8c02a81e684dae3d8e7c85", - "_spec": "@firebase/app-types@0.3.2", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@firebase\\app", - "author": { - "name": "Firebase", - "email": "firebase-support@google.com", - "url": "https://firebase.google.com/" - }, - "bugs": { - "url": "https://github.com/firebase/firebase-js-sdk/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "@firebase/app Types", - "devDependencies": { - "typescript": "2.8.1" - }, - "files": [ - "index.d.ts", - "private.d.ts" - ], - "license": "Apache-2.0", - "name": "@firebase/app-types", - "repository": { - "type": "git", - "url": "https://github.com/firebase/firebase-js-sdk/tree/master/packages/app-types" - }, - "scripts": { - "test": "tsc" - }, - "version": "0.3.2" -} diff --git a/functions/node_modules/@firebase/app-types/private.d.ts b/functions/node_modules/@firebase/app-types/private.d.ts deleted file mode 100644 index 1f2a77ad..00000000 --- a/functions/node_modules/@firebase/app-types/private.d.ts +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * THIS FILE IS FOR INTERNAL USAGE ONLY, IF YOU ARE NOT DEVELOPING THE FIREBASE - * SDKs, PLEASE DO NOT REFERENCE THIS FILE AS IT MAY CHANGE WITHOUT WARNING - */ - -import { FirebaseApp, FirebaseNamespace } from '@firebase/app-types'; -import { Observer, Subscribe } from '@firebase/util'; -import { FirebaseError } from '@firebase/util'; - -export interface FirebaseServiceInternals { - /** - * Delete the service and free it's resources - called from - * app.delete(). - */ - delete(): Promise; -} - -// Services are exposed through instances - each of which is associated with a -// FirebaseApp. -export interface FirebaseService { - app: FirebaseApp; - INTERNAL?: FirebaseServiceInternals; -} - -export type AppHook = (event: string, app: FirebaseApp) => void; - -/** - * Firebase Services create instances given a Firebase App instance and can - * optionally add properties and methods to each FirebaseApp via the extendApp() - * function. - */ -export interface FirebaseServiceFactory { - ( - app: FirebaseApp, - extendApp?: (props: { [prop: string]: any }) => void, - instanceString?: string - ): FirebaseService; -} - -/** - * All ServiceNamespaces extend from FirebaseServiceNamespace - */ -export interface FirebaseServiceNamespace { - (app?: FirebaseApp): T; -} - -export interface FirebaseErrorFactory { - create(code: T, data?: { [prop: string]: any }): FirebaseError; -} - -export interface FirebaseErrorFactoryClass { - new ( - service: string, - serviceName: string, - errors: { [code: string]: string } - ): FirebaseErrorFactory; -} - -export interface FirebaseAuthTokenData { - accessToken: string; -} - -export interface FirebaseAppInternals { - getToken(refreshToken?: boolean): Promise; - getUid(): string | null; - addAuthTokenListener(fn: (token: string | null) => void): void; - removeAuthTokenListener(fn: (token: string | null) => void): void; -} - -export interface _FirebaseApp extends FirebaseApp { - INTERNAL: FirebaseAppInternals; -} -export interface _FirebaseNamespace extends FirebaseNamespace { - INTERNAL: { - /** - * Internal API to register a Firebase Service into the firebase namespace. - * - * Each service will create a child namespace (firebase.) which acts as - * both a namespace for service specific properties, and also as a service - * accessor function (firebase.() or firebase.(app)). - * - * @param name The Firebase Service being registered. - * @param createService Factory function to create a service instance. - * @param serviceProperties Properties to copy to the service's namespace. - * @param appHook All appHooks called before initializeApp returns to caller. - * @param allowMultipleInstances Whether the registered service supports - * multiple instances per app. If not specified, the default is false. - */ - registerService( - name: string, - createService: FirebaseServiceFactory, - serviceProperties?: { [prop: string]: any }, - appHook?: AppHook, - allowMultipleInstances?: boolean - ): FirebaseServiceNamespace; - - /** - * Just used for testing to start from a fresh namespace. - */ - createFirebaseNamespace(): FirebaseNamespace; - - /** - * Internal API to install properties on the top-level firebase namespace. - * @prop props The top level properties of this object are copied to the - * namespace. - */ - extendNamespace(props: { [prop: string]: any }): void; - - /** - * Create a Subscribe function. A proxy Observer is created so that - * events can be sent to single Observer to be fanned out automatically. - */ - createSubscribe( - executor: (observer: Observer) => void, - onNoObservers?: (observer: Observer) => void - ): Subscribe; - - /** - * Utility exposed for internal testing. - */ - deepExtend(target: any, source: any): any; - - /** - * Internal API to remove an app from the list of registered apps. - */ - removeApp(name: string): void; - - /** - * Service factories for each registered service. - */ - factories: { [name: string]: FirebaseServiceFactory }; - - /* - * Convert service name to factory name to use. - */ - useAsService(app: FirebaseApp, serviceName: string): string | null; - - /** - * Use to construct all thrown FirebaseError's. - */ - ErrorFactory: FirebaseErrorFactoryClass; - }; -} diff --git a/functions/node_modules/@firebase/app/README.md b/functions/node_modules/@firebase/app/README.md deleted file mode 100644 index 04ece1cb..00000000 --- a/functions/node_modules/@firebase/app/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# @firebase/app - -This package coordinates the communication between the different Firebase components and -exposes the API surface to the user - -**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/functions/node_modules/@firebase/app/dist/index.cjs.js b/functions/node_modules/@firebase/app/dist/index.cjs.js deleted file mode 100644 index 3cb7d836..00000000 --- a/functions/node_modules/@firebase/app/dist/index.cjs.js +++ /dev/null @@ -1,398 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var util = require('@firebase/util'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var DEFAULT_ENTRY_NAME = '[DEFAULT]'; -// An array to capture listeners before the true auth functions -// exist -var tokenListeners = []; -/** - * Global context object for a collection of services using - * a shared authentication state. - */ -var FirebaseAppImpl = /** @class */ (function () { - function FirebaseAppImpl(options, config, firebase_) { - this.firebase_ = firebase_; - this.isDeleted_ = false; - this.services_ = {}; - this.name_ = config.name; - this._automaticDataCollectionEnabled = - config.automaticDataCollectionEnabled || false; - this.options_ = util.deepCopy(options); - this.INTERNAL = { - getUid: function () { return null; }, - getToken: function () { return Promise.resolve(null); }, - addAuthTokenListener: function (callback) { - tokenListeners.push(callback); - // Make sure callback is called, asynchronously, in the absence of the auth module - setTimeout(function () { return callback(null); }, 0); - }, - removeAuthTokenListener: function (callback) { - tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; }); - } - }; - } - Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", { - get: function () { - this.checkDestroyed_(); - return this._automaticDataCollectionEnabled; - }, - set: function (val) { - this.checkDestroyed_(); - this._automaticDataCollectionEnabled = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "name", { - get: function () { - this.checkDestroyed_(); - return this.name_; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "options", { - get: function () { - this.checkDestroyed_(); - return this.options_; - }, - enumerable: true, - configurable: true - }); - FirebaseAppImpl.prototype.delete = function () { - var _this = this; - return new Promise(function (resolve) { - _this.checkDestroyed_(); - resolve(); - }) - .then(function () { - _this.firebase_.INTERNAL.removeApp(_this.name_); - var services = []; - Object.keys(_this.services_).forEach(function (serviceKey) { - Object.keys(_this.services_[serviceKey]).forEach(function (instanceKey) { - services.push(_this.services_[serviceKey][instanceKey]); - }); - }); - return Promise.all(services.map(function (service) { - return service.INTERNAL.delete(); - })); - }) - .then(function () { - _this.isDeleted_ = true; - _this.services_ = {}; - }); - }; - /** - * Return a service instance associated with this app (creating it - * on demand), identified by the passed instanceIdentifier. - * - * NOTE: Currently storage is the only one that is leveraging this - * functionality. They invoke it by calling: - * - * ```javascript - * firebase.app().storage('STORAGE BUCKET ID') - * ``` - * - * The service name is passed to this already - * @internal - */ - FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) { - if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; } - this.checkDestroyed_(); - if (!this.services_[name]) { - this.services_[name] = {}; - } - if (!this.services_[name][instanceIdentifier]) { - /** - * If a custom instance has been defined (i.e. not '[DEFAULT]') - * then we will pass that instance on, otherwise we pass `null` - */ - var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME - ? instanceIdentifier - : undefined; - var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier); - this.services_[name][instanceIdentifier] = service; - } - return this.services_[name][instanceIdentifier]; - }; - /** - * Callback function used to extend an App instance at the time - * of service instance creation. - */ - FirebaseAppImpl.prototype.extendApp = function (props) { - var _this = this; - // Copy the object onto the FirebaseAppImpl prototype - util.deepExtend(this, props); - /** - * If the app has overwritten the addAuthTokenListener stub, forward - * the active token listeners on to the true fxn. - * - * TODO: This function is required due to our current module - * structure. Once we are able to rely strictly upon a single module - * implementation, this code should be refactored and Auth should - * provide these stubs and the upgrade logic - */ - if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) { - tokenListeners.forEach(function (listener) { - _this.INTERNAL.addAuthTokenListener(listener); - }); - tokenListeners = []; - } - }; - /** - * This function will throw an Error if the App has already been deleted - - * use before performing API actions on the App. - */ - FirebaseAppImpl.prototype.checkDestroyed_ = function () { - if (this.isDeleted_) { - error('app-deleted', { name: this.name_ }); - } - }; - return FirebaseAppImpl; -}()); -// Prevent dead-code elimination of these methods w/o invalid property -// copying. -(FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) || - FirebaseAppImpl.prototype.delete || - console.log('dc'); -/** - * Return a firebase namespace object. - * - * In production, this will be called exactly once and the result - * assigned to the 'firebase' global. It may be called multiple times - * in unit tests. - */ -function createFirebaseNamespace() { - var apps_ = {}; - var factories = {}; - var appHooks = {}; - // A namespace is a plain JavaScript Object. - var namespace = { - // Hack to prevent Babel from modifying the object returned - // as the firebase namespace. - __esModule: true, - initializeApp: initializeApp, - app: app, - apps: null, - Promise: Promise, - SDK_VERSION: '5.5.9', - INTERNAL: { - registerService: registerService, - createFirebaseNamespace: createFirebaseNamespace, - extendNamespace: extendNamespace, - createSubscribe: util.createSubscribe, - ErrorFactory: util.ErrorFactory, - removeApp: removeApp, - factories: factories, - useAsService: useAsService, - Promise: Promise, - deepExtend: util.deepExtend - } - }; - // Inject a circular default export to allow Babel users who were previously - // using: - // - // import firebase from 'firebase'; - // which becomes: var firebase = require('firebase').default; - // - // instead of - // - // import * as firebase from 'firebase'; - // which becomes: var firebase = require('firebase'); - util.patchProperty(namespace, 'default', namespace); - // firebase.apps is a read-only getter. - Object.defineProperty(namespace, 'apps', { - get: getApps - }); - /** - * Called by App.delete() - but before any services associated with the App - * are deleted. - */ - function removeApp(name) { - var app = apps_[name]; - callAppHooks(app, 'delete'); - delete apps_[name]; - } - /** - * Get the App object for a given name (or DEFAULT). - */ - function app(name) { - name = name || DEFAULT_ENTRY_NAME; - if (!contains(apps_, name)) { - error('no-app', { name: name }); - } - return apps_[name]; - } - util.patchProperty(app, 'App', FirebaseAppImpl); - function initializeApp(options, rawConfig) { - if (rawConfig === void 0) { rawConfig = {}; } - if (typeof rawConfig !== 'object' || rawConfig === null) { - var name_1 = rawConfig; - rawConfig = { name: name_1 }; - } - var config = rawConfig; - if (config.name === undefined) { - config.name = DEFAULT_ENTRY_NAME; - } - var name = config.name; - if (typeof name !== 'string' || !name) { - error('bad-app-name', { name: name + '' }); - } - if (contains(apps_, name)) { - error('duplicate-app', { name: name }); - } - var app = new FirebaseAppImpl(options, config, namespace); - apps_[name] = app; - callAppHooks(app, 'create'); - return app; - } - /* - * Return an array of all the non-deleted FirebaseApps. - */ - function getApps() { - // Make a copy so caller cannot mutate the apps list. - return Object.keys(apps_).map(function (name) { return apps_[name]; }); - } - /* - * Register a Firebase Service. - * - * firebase.INTERNAL.registerService() - * - * TODO: Implement serviceProperties. - */ - function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) { - // Cannot re-register a service that already exists - if (factories[name]) { - error('duplicate-service', { name: name }); - } - // Capture the service factory for later service instantiation - factories[name] = createService; - // Capture the appHook, if passed - if (appHook) { - appHooks[name] = appHook; - // Run the **new** app hook on all existing apps - getApps().forEach(function (app) { - appHook('create', app); - }); - } - // The Service namespace is an accessor function ... - var serviceNamespace = function (appArg) { - if (appArg === void 0) { appArg = app(); } - if (typeof appArg[name] !== 'function') { - // Invalid argument. - // This happens in the following case: firebase.storage('gs:/') - error('invalid-app-argument', { name: name }); - } - // Forward service instance lookup to the FirebaseApp. - return appArg[name](); - }; - // ... and a container for service-level properties. - if (serviceProperties !== undefined) { - util.deepExtend(serviceNamespace, serviceProperties); - } - // Monkey-patch the serviceNamespace onto the firebase namespace - namespace[name] = serviceNamespace; - // Patch the FirebaseAppImpl prototype - FirebaseAppImpl.prototype[name] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var serviceFxn = this._getService.bind(this, name); - return serviceFxn.apply(this, allowMultipleInstances ? args : []); - }; - return serviceNamespace; - } - /** - * Patch the top-level firebase namespace with additional properties. - * - * firebase.INTERNAL.extendNamespace() - */ - function extendNamespace(props) { - util.deepExtend(namespace, props); - } - function callAppHooks(app, eventName) { - Object.keys(factories).forEach(function (serviceName) { - // Ignore virtual services - var factoryName = useAsService(app, serviceName); - if (factoryName === null) { - return; - } - if (appHooks[factoryName]) { - appHooks[factoryName](eventName, app); - } - }); - } - // Map the requested service to a registered service name - // (used to map auth to serverAuth service when needed). - function useAsService(app, name) { - if (name === 'serverAuth') { - return null; - } - var useService = name; - var options = app.options; - return useService; - } - return namespace; -} -function error(code, args) { - throw appErrors.create(code, args); -} -// TypeScript does not support non-string indexes! -// let errors: {[code: AppError: string} = { -var errors = { - 'no-app': "No Firebase App '{$name}' has been created - " + - 'call Firebase App.initializeApp()', - 'bad-app-name': "Illegal App name: '{$name}", - 'duplicate-app': "Firebase App named '{$name}' already exists", - 'app-deleted': "Firebase App named '{$name}' already deleted", - 'duplicate-service': "Firebase service named '{$name}' already registered", - 'sa-not-supported': 'Initializing the Firebase SDK with a service ' + - 'account is only allowed in a Node.js environment. On client ' + - 'devices, you should instead initialize the SDK with an api key and ' + - 'auth domain', - 'invalid-app-argument': 'firebase.{$name}() takes either no argument or a ' + - 'Firebase App instance.' -}; -var appErrors = new util.ErrorFactory('app', 'Firebase', errors); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var firebase = createFirebaseNamespace(); - -exports.firebase = firebase; -exports.default = firebase; diff --git a/functions/node_modules/@firebase/app/dist/index.d.ts b/functions/node_modules/@firebase/app/dist/index.d.ts deleted file mode 100644 index b1a5b19b..00000000 --- a/functions/node_modules/@firebase/app/dist/index.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseNamespace } from '@firebase/app-types'; -export declare const firebase: FirebaseNamespace; -export default firebase; diff --git a/functions/node_modules/@firebase/app/dist/index.esm.js b/functions/node_modules/@firebase/app/dist/index.esm.js deleted file mode 100644 index d72fb039..00000000 --- a/functions/node_modules/@firebase/app/dist/index.esm.js +++ /dev/null @@ -1,394 +0,0 @@ -import { createSubscribe, deepCopy, deepExtend, ErrorFactory, patchProperty } from '@firebase/util'; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var DEFAULT_ENTRY_NAME = '[DEFAULT]'; -// An array to capture listeners before the true auth functions -// exist -var tokenListeners = []; -/** - * Global context object for a collection of services using - * a shared authentication state. - */ -var FirebaseAppImpl = /** @class */ (function () { - function FirebaseAppImpl(options, config, firebase_) { - this.firebase_ = firebase_; - this.isDeleted_ = false; - this.services_ = {}; - this.name_ = config.name; - this._automaticDataCollectionEnabled = - config.automaticDataCollectionEnabled || false; - this.options_ = deepCopy(options); - this.INTERNAL = { - getUid: function () { return null; }, - getToken: function () { return Promise.resolve(null); }, - addAuthTokenListener: function (callback) { - tokenListeners.push(callback); - // Make sure callback is called, asynchronously, in the absence of the auth module - setTimeout(function () { return callback(null); }, 0); - }, - removeAuthTokenListener: function (callback) { - tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; }); - } - }; - } - Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", { - get: function () { - this.checkDestroyed_(); - return this._automaticDataCollectionEnabled; - }, - set: function (val) { - this.checkDestroyed_(); - this._automaticDataCollectionEnabled = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "name", { - get: function () { - this.checkDestroyed_(); - return this.name_; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "options", { - get: function () { - this.checkDestroyed_(); - return this.options_; - }, - enumerable: true, - configurable: true - }); - FirebaseAppImpl.prototype.delete = function () { - var _this = this; - return new Promise(function (resolve) { - _this.checkDestroyed_(); - resolve(); - }) - .then(function () { - _this.firebase_.INTERNAL.removeApp(_this.name_); - var services = []; - Object.keys(_this.services_).forEach(function (serviceKey) { - Object.keys(_this.services_[serviceKey]).forEach(function (instanceKey) { - services.push(_this.services_[serviceKey][instanceKey]); - }); - }); - return Promise.all(services.map(function (service) { - return service.INTERNAL.delete(); - })); - }) - .then(function () { - _this.isDeleted_ = true; - _this.services_ = {}; - }); - }; - /** - * Return a service instance associated with this app (creating it - * on demand), identified by the passed instanceIdentifier. - * - * NOTE: Currently storage is the only one that is leveraging this - * functionality. They invoke it by calling: - * - * ```javascript - * firebase.app().storage('STORAGE BUCKET ID') - * ``` - * - * The service name is passed to this already - * @internal - */ - FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) { - if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; } - this.checkDestroyed_(); - if (!this.services_[name]) { - this.services_[name] = {}; - } - if (!this.services_[name][instanceIdentifier]) { - /** - * If a custom instance has been defined (i.e. not '[DEFAULT]') - * then we will pass that instance on, otherwise we pass `null` - */ - var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME - ? instanceIdentifier - : undefined; - var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier); - this.services_[name][instanceIdentifier] = service; - } - return this.services_[name][instanceIdentifier]; - }; - /** - * Callback function used to extend an App instance at the time - * of service instance creation. - */ - FirebaseAppImpl.prototype.extendApp = function (props) { - var _this = this; - // Copy the object onto the FirebaseAppImpl prototype - deepExtend(this, props); - /** - * If the app has overwritten the addAuthTokenListener stub, forward - * the active token listeners on to the true fxn. - * - * TODO: This function is required due to our current module - * structure. Once we are able to rely strictly upon a single module - * implementation, this code should be refactored and Auth should - * provide these stubs and the upgrade logic - */ - if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) { - tokenListeners.forEach(function (listener) { - _this.INTERNAL.addAuthTokenListener(listener); - }); - tokenListeners = []; - } - }; - /** - * This function will throw an Error if the App has already been deleted - - * use before performing API actions on the App. - */ - FirebaseAppImpl.prototype.checkDestroyed_ = function () { - if (this.isDeleted_) { - error('app-deleted', { name: this.name_ }); - } - }; - return FirebaseAppImpl; -}()); -// Prevent dead-code elimination of these methods w/o invalid property -// copying. -(FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) || - FirebaseAppImpl.prototype.delete || - console.log('dc'); -/** - * Return a firebase namespace object. - * - * In production, this will be called exactly once and the result - * assigned to the 'firebase' global. It may be called multiple times - * in unit tests. - */ -function createFirebaseNamespace() { - var apps_ = {}; - var factories = {}; - var appHooks = {}; - // A namespace is a plain JavaScript Object. - var namespace = { - // Hack to prevent Babel from modifying the object returned - // as the firebase namespace. - __esModule: true, - initializeApp: initializeApp, - app: app, - apps: null, - Promise: Promise, - SDK_VERSION: '5.5.9', - INTERNAL: { - registerService: registerService, - createFirebaseNamespace: createFirebaseNamespace, - extendNamespace: extendNamespace, - createSubscribe: createSubscribe, - ErrorFactory: ErrorFactory, - removeApp: removeApp, - factories: factories, - useAsService: useAsService, - Promise: Promise, - deepExtend: deepExtend - } - }; - // Inject a circular default export to allow Babel users who were previously - // using: - // - // import firebase from 'firebase'; - // which becomes: var firebase = require('firebase').default; - // - // instead of - // - // import * as firebase from 'firebase'; - // which becomes: var firebase = require('firebase'); - patchProperty(namespace, 'default', namespace); - // firebase.apps is a read-only getter. - Object.defineProperty(namespace, 'apps', { - get: getApps - }); - /** - * Called by App.delete() - but before any services associated with the App - * are deleted. - */ - function removeApp(name) { - var app = apps_[name]; - callAppHooks(app, 'delete'); - delete apps_[name]; - } - /** - * Get the App object for a given name (or DEFAULT). - */ - function app(name) { - name = name || DEFAULT_ENTRY_NAME; - if (!contains(apps_, name)) { - error('no-app', { name: name }); - } - return apps_[name]; - } - patchProperty(app, 'App', FirebaseAppImpl); - function initializeApp(options, rawConfig) { - if (rawConfig === void 0) { rawConfig = {}; } - if (typeof rawConfig !== 'object' || rawConfig === null) { - var name_1 = rawConfig; - rawConfig = { name: name_1 }; - } - var config = rawConfig; - if (config.name === undefined) { - config.name = DEFAULT_ENTRY_NAME; - } - var name = config.name; - if (typeof name !== 'string' || !name) { - error('bad-app-name', { name: name + '' }); - } - if (contains(apps_, name)) { - error('duplicate-app', { name: name }); - } - var app = new FirebaseAppImpl(options, config, namespace); - apps_[name] = app; - callAppHooks(app, 'create'); - return app; - } - /* - * Return an array of all the non-deleted FirebaseApps. - */ - function getApps() { - // Make a copy so caller cannot mutate the apps list. - return Object.keys(apps_).map(function (name) { return apps_[name]; }); - } - /* - * Register a Firebase Service. - * - * firebase.INTERNAL.registerService() - * - * TODO: Implement serviceProperties. - */ - function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) { - // Cannot re-register a service that already exists - if (factories[name]) { - error('duplicate-service', { name: name }); - } - // Capture the service factory for later service instantiation - factories[name] = createService; - // Capture the appHook, if passed - if (appHook) { - appHooks[name] = appHook; - // Run the **new** app hook on all existing apps - getApps().forEach(function (app) { - appHook('create', app); - }); - } - // The Service namespace is an accessor function ... - var serviceNamespace = function (appArg) { - if (appArg === void 0) { appArg = app(); } - if (typeof appArg[name] !== 'function') { - // Invalid argument. - // This happens in the following case: firebase.storage('gs:/') - error('invalid-app-argument', { name: name }); - } - // Forward service instance lookup to the FirebaseApp. - return appArg[name](); - }; - // ... and a container for service-level properties. - if (serviceProperties !== undefined) { - deepExtend(serviceNamespace, serviceProperties); - } - // Monkey-patch the serviceNamespace onto the firebase namespace - namespace[name] = serviceNamespace; - // Patch the FirebaseAppImpl prototype - FirebaseAppImpl.prototype[name] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var serviceFxn = this._getService.bind(this, name); - return serviceFxn.apply(this, allowMultipleInstances ? args : []); - }; - return serviceNamespace; - } - /** - * Patch the top-level firebase namespace with additional properties. - * - * firebase.INTERNAL.extendNamespace() - */ - function extendNamespace(props) { - deepExtend(namespace, props); - } - function callAppHooks(app, eventName) { - Object.keys(factories).forEach(function (serviceName) { - // Ignore virtual services - var factoryName = useAsService(app, serviceName); - if (factoryName === null) { - return; - } - if (appHooks[factoryName]) { - appHooks[factoryName](eventName, app); - } - }); - } - // Map the requested service to a registered service name - // (used to map auth to serverAuth service when needed). - function useAsService(app, name) { - if (name === 'serverAuth') { - return null; - } - var useService = name; - var options = app.options; - return useService; - } - return namespace; -} -function error(code, args) { - throw appErrors.create(code, args); -} -// TypeScript does not support non-string indexes! -// let errors: {[code: AppError: string} = { -var errors = { - 'no-app': "No Firebase App '{$name}' has been created - " + - 'call Firebase App.initializeApp()', - 'bad-app-name': "Illegal App name: '{$name}", - 'duplicate-app': "Firebase App named '{$name}' already exists", - 'app-deleted': "Firebase App named '{$name}' already deleted", - 'duplicate-service': "Firebase service named '{$name}' already registered", - 'sa-not-supported': 'Initializing the Firebase SDK with a service ' + - 'account is only allowed in a Node.js environment. On client ' + - 'devices, you should instead initialize the SDK with an api key and ' + - 'auth domain', - 'invalid-app-argument': 'firebase.{$name}() takes either no argument or a ' + - 'Firebase App instance.' -}; -var appErrors = new ErrorFactory('app', 'Firebase', errors); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var firebase = createFirebaseNamespace(); - -export default firebase; -export { firebase }; diff --git a/functions/node_modules/@firebase/app/dist/index.node.cjs.js b/functions/node_modules/@firebase/app/dist/index.node.cjs.js deleted file mode 100644 index 7f2f1013..00000000 --- a/functions/node_modules/@firebase/app/dist/index.node.cjs.js +++ /dev/null @@ -1,412 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var util = require('@firebase/util'); -var Storage = _interopDefault(require('dom-storage')); -var xmlhttprequest = require('xmlhttprequest'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var DEFAULT_ENTRY_NAME = '[DEFAULT]'; -// An array to capture listeners before the true auth functions -// exist -var tokenListeners = []; -/** - * Global context object for a collection of services using - * a shared authentication state. - */ -var FirebaseAppImpl = /** @class */ (function () { - function FirebaseAppImpl(options, config, firebase_) { - this.firebase_ = firebase_; - this.isDeleted_ = false; - this.services_ = {}; - this.name_ = config.name; - this._automaticDataCollectionEnabled = - config.automaticDataCollectionEnabled || false; - this.options_ = util.deepCopy(options); - this.INTERNAL = { - getUid: function () { return null; }, - getToken: function () { return Promise.resolve(null); }, - addAuthTokenListener: function (callback) { - tokenListeners.push(callback); - // Make sure callback is called, asynchronously, in the absence of the auth module - setTimeout(function () { return callback(null); }, 0); - }, - removeAuthTokenListener: function (callback) { - tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; }); - } - }; - } - Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", { - get: function () { - this.checkDestroyed_(); - return this._automaticDataCollectionEnabled; - }, - set: function (val) { - this.checkDestroyed_(); - this._automaticDataCollectionEnabled = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "name", { - get: function () { - this.checkDestroyed_(); - return this.name_; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "options", { - get: function () { - this.checkDestroyed_(); - return this.options_; - }, - enumerable: true, - configurable: true - }); - FirebaseAppImpl.prototype.delete = function () { - var _this = this; - return new Promise(function (resolve) { - _this.checkDestroyed_(); - resolve(); - }) - .then(function () { - _this.firebase_.INTERNAL.removeApp(_this.name_); - var services = []; - Object.keys(_this.services_).forEach(function (serviceKey) { - Object.keys(_this.services_[serviceKey]).forEach(function (instanceKey) { - services.push(_this.services_[serviceKey][instanceKey]); - }); - }); - return Promise.all(services.map(function (service) { - return service.INTERNAL.delete(); - })); - }) - .then(function () { - _this.isDeleted_ = true; - _this.services_ = {}; - }); - }; - /** - * Return a service instance associated with this app (creating it - * on demand), identified by the passed instanceIdentifier. - * - * NOTE: Currently storage is the only one that is leveraging this - * functionality. They invoke it by calling: - * - * ```javascript - * firebase.app().storage('STORAGE BUCKET ID') - * ``` - * - * The service name is passed to this already - * @internal - */ - FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) { - if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; } - this.checkDestroyed_(); - if (!this.services_[name]) { - this.services_[name] = {}; - } - if (!this.services_[name][instanceIdentifier]) { - /** - * If a custom instance has been defined (i.e. not '[DEFAULT]') - * then we will pass that instance on, otherwise we pass `null` - */ - var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME - ? instanceIdentifier - : undefined; - var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier); - this.services_[name][instanceIdentifier] = service; - } - return this.services_[name][instanceIdentifier]; - }; - /** - * Callback function used to extend an App instance at the time - * of service instance creation. - */ - FirebaseAppImpl.prototype.extendApp = function (props) { - var _this = this; - // Copy the object onto the FirebaseAppImpl prototype - util.deepExtend(this, props); - /** - * If the app has overwritten the addAuthTokenListener stub, forward - * the active token listeners on to the true fxn. - * - * TODO: This function is required due to our current module - * structure. Once we are able to rely strictly upon a single module - * implementation, this code should be refactored and Auth should - * provide these stubs and the upgrade logic - */ - if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) { - tokenListeners.forEach(function (listener) { - _this.INTERNAL.addAuthTokenListener(listener); - }); - tokenListeners = []; - } - }; - /** - * This function will throw an Error if the App has already been deleted - - * use before performing API actions on the App. - */ - FirebaseAppImpl.prototype.checkDestroyed_ = function () { - if (this.isDeleted_) { - error('app-deleted', { name: this.name_ }); - } - }; - return FirebaseAppImpl; -}()); -// Prevent dead-code elimination of these methods w/o invalid property -// copying. -(FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) || - FirebaseAppImpl.prototype.delete || - console.log('dc'); -/** - * Return a firebase namespace object. - * - * In production, this will be called exactly once and the result - * assigned to the 'firebase' global. It may be called multiple times - * in unit tests. - */ -function createFirebaseNamespace() { - var apps_ = {}; - var factories = {}; - var appHooks = {}; - // A namespace is a plain JavaScript Object. - var namespace = { - // Hack to prevent Babel from modifying the object returned - // as the firebase namespace. - __esModule: true, - initializeApp: initializeApp, - app: app, - apps: null, - Promise: Promise, - SDK_VERSION: '5.5.9', - INTERNAL: { - registerService: registerService, - createFirebaseNamespace: createFirebaseNamespace, - extendNamespace: extendNamespace, - createSubscribe: util.createSubscribe, - ErrorFactory: util.ErrorFactory, - removeApp: removeApp, - factories: factories, - useAsService: useAsService, - Promise: Promise, - deepExtend: util.deepExtend - } - }; - // Inject a circular default export to allow Babel users who were previously - // using: - // - // import firebase from 'firebase'; - // which becomes: var firebase = require('firebase').default; - // - // instead of - // - // import * as firebase from 'firebase'; - // which becomes: var firebase = require('firebase'); - util.patchProperty(namespace, 'default', namespace); - // firebase.apps is a read-only getter. - Object.defineProperty(namespace, 'apps', { - get: getApps - }); - /** - * Called by App.delete() - but before any services associated with the App - * are deleted. - */ - function removeApp(name) { - var app = apps_[name]; - callAppHooks(app, 'delete'); - delete apps_[name]; - } - /** - * Get the App object for a given name (or DEFAULT). - */ - function app(name) { - name = name || DEFAULT_ENTRY_NAME; - if (!contains(apps_, name)) { - error('no-app', { name: name }); - } - return apps_[name]; - } - util.patchProperty(app, 'App', FirebaseAppImpl); - function initializeApp(options, rawConfig) { - if (rawConfig === void 0) { rawConfig = {}; } - if (typeof rawConfig !== 'object' || rawConfig === null) { - var name_1 = rawConfig; - rawConfig = { name: name_1 }; - } - var config = rawConfig; - if (config.name === undefined) { - config.name = DEFAULT_ENTRY_NAME; - } - var name = config.name; - if (typeof name !== 'string' || !name) { - error('bad-app-name', { name: name + '' }); - } - if (contains(apps_, name)) { - error('duplicate-app', { name: name }); - } - var app = new FirebaseAppImpl(options, config, namespace); - apps_[name] = app; - callAppHooks(app, 'create'); - return app; - } - /* - * Return an array of all the non-deleted FirebaseApps. - */ - function getApps() { - // Make a copy so caller cannot mutate the apps list. - return Object.keys(apps_).map(function (name) { return apps_[name]; }); - } - /* - * Register a Firebase Service. - * - * firebase.INTERNAL.registerService() - * - * TODO: Implement serviceProperties. - */ - function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) { - // Cannot re-register a service that already exists - if (factories[name]) { - error('duplicate-service', { name: name }); - } - // Capture the service factory for later service instantiation - factories[name] = createService; - // Capture the appHook, if passed - if (appHook) { - appHooks[name] = appHook; - // Run the **new** app hook on all existing apps - getApps().forEach(function (app) { - appHook('create', app); - }); - } - // The Service namespace is an accessor function ... - var serviceNamespace = function (appArg) { - if (appArg === void 0) { appArg = app(); } - if (typeof appArg[name] !== 'function') { - // Invalid argument. - // This happens in the following case: firebase.storage('gs:/') - error('invalid-app-argument', { name: name }); - } - // Forward service instance lookup to the FirebaseApp. - return appArg[name](); - }; - // ... and a container for service-level properties. - if (serviceProperties !== undefined) { - util.deepExtend(serviceNamespace, serviceProperties); - } - // Monkey-patch the serviceNamespace onto the firebase namespace - namespace[name] = serviceNamespace; - // Patch the FirebaseAppImpl prototype - FirebaseAppImpl.prototype[name] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var serviceFxn = this._getService.bind(this, name); - return serviceFxn.apply(this, allowMultipleInstances ? args : []); - }; - return serviceNamespace; - } - /** - * Patch the top-level firebase namespace with additional properties. - * - * firebase.INTERNAL.extendNamespace() - */ - function extendNamespace(props) { - util.deepExtend(namespace, props); - } - function callAppHooks(app, eventName) { - Object.keys(factories).forEach(function (serviceName) { - // Ignore virtual services - var factoryName = useAsService(app, serviceName); - if (factoryName === null) { - return; - } - if (appHooks[factoryName]) { - appHooks[factoryName](eventName, app); - } - }); - } - // Map the requested service to a registered service name - // (used to map auth to serverAuth service when needed). - function useAsService(app, name) { - if (name === 'serverAuth') { - return null; - } - var useService = name; - var options = app.options; - return useService; - } - return namespace; -} -function error(code, args) { - throw appErrors.create(code, args); -} -// TypeScript does not support non-string indexes! -// let errors: {[code: AppError: string} = { -var errors = { - 'no-app': "No Firebase App '{$name}' has been created - " + - 'call Firebase App.initializeApp()', - 'bad-app-name': "Illegal App name: '{$name}", - 'duplicate-app': "Firebase App named '{$name}' already exists", - 'app-deleted': "Firebase App named '{$name}' already deleted", - 'duplicate-service': "Firebase service named '{$name}' already registered", - 'sa-not-supported': 'Initializing the Firebase SDK with a service ' + - 'account is only allowed in a Node.js environment. On client ' + - 'devices, you should instead initialize the SDK with an api key and ' + - 'auth domain', - 'invalid-app-argument': 'firebase.{$name}() takes either no argument or a ' + - 'Firebase App instance.' -}; -var appErrors = new util.ErrorFactory('app', 'Firebase', errors); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var _firebase = createFirebaseNamespace(); -_firebase.INTERNAL.extendNamespace({ - INTERNAL: { - node: { - localStorage: new Storage(null, { strict: true }), - sessionStorage: new Storage(null, { strict: true }), - XMLHttpRequest: xmlhttprequest.XMLHttpRequest - } - } -}); -var firebase = _firebase; - -exports.firebase = firebase; -exports.default = firebase; diff --git a/functions/node_modules/@firebase/app/dist/index.node.d.ts b/functions/node_modules/@firebase/app/dist/index.node.d.ts deleted file mode 100644 index b1a5b19b..00000000 --- a/functions/node_modules/@firebase/app/dist/index.node.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseNamespace } from '@firebase/app-types'; -export declare const firebase: FirebaseNamespace; -export default firebase; diff --git a/functions/node_modules/@firebase/app/dist/index.rn.cjs.js b/functions/node_modules/@firebase/app/dist/index.rn.cjs.js deleted file mode 100644 index bd06f2bb..00000000 --- a/functions/node_modules/@firebase/app/dist/index.rn.cjs.js +++ /dev/null @@ -1,412 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var util = require('@firebase/util'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var DEFAULT_ENTRY_NAME = '[DEFAULT]'; -// An array to capture listeners before the true auth functions -// exist -var tokenListeners = []; -/** - * Global context object for a collection of services using - * a shared authentication state. - */ -var FirebaseAppImpl = /** @class */ (function () { - function FirebaseAppImpl(options, config, firebase_) { - this.firebase_ = firebase_; - this.isDeleted_ = false; - this.services_ = {}; - this.name_ = config.name; - this._automaticDataCollectionEnabled = - config.automaticDataCollectionEnabled || false; - this.options_ = util.deepCopy(options); - this.INTERNAL = { - getUid: function () { return null; }, - getToken: function () { return Promise.resolve(null); }, - addAuthTokenListener: function (callback) { - tokenListeners.push(callback); - // Make sure callback is called, asynchronously, in the absence of the auth module - setTimeout(function () { return callback(null); }, 0); - }, - removeAuthTokenListener: function (callback) { - tokenListeners = tokenListeners.filter(function (listener) { return listener !== callback; }); - } - }; - } - Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", { - get: function () { - this.checkDestroyed_(); - return this._automaticDataCollectionEnabled; - }, - set: function (val) { - this.checkDestroyed_(); - this._automaticDataCollectionEnabled = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "name", { - get: function () { - this.checkDestroyed_(); - return this.name_; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(FirebaseAppImpl.prototype, "options", { - get: function () { - this.checkDestroyed_(); - return this.options_; - }, - enumerable: true, - configurable: true - }); - FirebaseAppImpl.prototype.delete = function () { - var _this = this; - return new Promise(function (resolve) { - _this.checkDestroyed_(); - resolve(); - }) - .then(function () { - _this.firebase_.INTERNAL.removeApp(_this.name_); - var services = []; - Object.keys(_this.services_).forEach(function (serviceKey) { - Object.keys(_this.services_[serviceKey]).forEach(function (instanceKey) { - services.push(_this.services_[serviceKey][instanceKey]); - }); - }); - return Promise.all(services.map(function (service) { - return service.INTERNAL.delete(); - })); - }) - .then(function () { - _this.isDeleted_ = true; - _this.services_ = {}; - }); - }; - /** - * Return a service instance associated with this app (creating it - * on demand), identified by the passed instanceIdentifier. - * - * NOTE: Currently storage is the only one that is leveraging this - * functionality. They invoke it by calling: - * - * ```javascript - * firebase.app().storage('STORAGE BUCKET ID') - * ``` - * - * The service name is passed to this already - * @internal - */ - FirebaseAppImpl.prototype._getService = function (name, instanceIdentifier) { - if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; } - this.checkDestroyed_(); - if (!this.services_[name]) { - this.services_[name] = {}; - } - if (!this.services_[name][instanceIdentifier]) { - /** - * If a custom instance has been defined (i.e. not '[DEFAULT]') - * then we will pass that instance on, otherwise we pass `null` - */ - var instanceSpecifier = instanceIdentifier !== DEFAULT_ENTRY_NAME - ? instanceIdentifier - : undefined; - var service = this.firebase_.INTERNAL.factories[name](this, this.extendApp.bind(this), instanceSpecifier); - this.services_[name][instanceIdentifier] = service; - } - return this.services_[name][instanceIdentifier]; - }; - /** - * Callback function used to extend an App instance at the time - * of service instance creation. - */ - FirebaseAppImpl.prototype.extendApp = function (props) { - var _this = this; - // Copy the object onto the FirebaseAppImpl prototype - util.deepExtend(this, props); - /** - * If the app has overwritten the addAuthTokenListener stub, forward - * the active token listeners on to the true fxn. - * - * TODO: This function is required due to our current module - * structure. Once we are able to rely strictly upon a single module - * implementation, this code should be refactored and Auth should - * provide these stubs and the upgrade logic - */ - if (props.INTERNAL && props.INTERNAL.addAuthTokenListener) { - tokenListeners.forEach(function (listener) { - _this.INTERNAL.addAuthTokenListener(listener); - }); - tokenListeners = []; - } - }; - /** - * This function will throw an Error if the App has already been deleted - - * use before performing API actions on the App. - */ - FirebaseAppImpl.prototype.checkDestroyed_ = function () { - if (this.isDeleted_) { - error('app-deleted', { name: this.name_ }); - } - }; - return FirebaseAppImpl; -}()); -// Prevent dead-code elimination of these methods w/o invalid property -// copying. -(FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) || - FirebaseAppImpl.prototype.delete || - console.log('dc'); -/** - * Return a firebase namespace object. - * - * In production, this will be called exactly once and the result - * assigned to the 'firebase' global. It may be called multiple times - * in unit tests. - */ -function createFirebaseNamespace() { - var apps_ = {}; - var factories = {}; - var appHooks = {}; - // A namespace is a plain JavaScript Object. - var namespace = { - // Hack to prevent Babel from modifying the object returned - // as the firebase namespace. - __esModule: true, - initializeApp: initializeApp, - app: app, - apps: null, - Promise: Promise, - SDK_VERSION: '5.5.9', - INTERNAL: { - registerService: registerService, - createFirebaseNamespace: createFirebaseNamespace, - extendNamespace: extendNamespace, - createSubscribe: util.createSubscribe, - ErrorFactory: util.ErrorFactory, - removeApp: removeApp, - factories: factories, - useAsService: useAsService, - Promise: Promise, - deepExtend: util.deepExtend - } - }; - // Inject a circular default export to allow Babel users who were previously - // using: - // - // import firebase from 'firebase'; - // which becomes: var firebase = require('firebase').default; - // - // instead of - // - // import * as firebase from 'firebase'; - // which becomes: var firebase = require('firebase'); - util.patchProperty(namespace, 'default', namespace); - // firebase.apps is a read-only getter. - Object.defineProperty(namespace, 'apps', { - get: getApps - }); - /** - * Called by App.delete() - but before any services associated with the App - * are deleted. - */ - function removeApp(name) { - var app = apps_[name]; - callAppHooks(app, 'delete'); - delete apps_[name]; - } - /** - * Get the App object for a given name (or DEFAULT). - */ - function app(name) { - name = name || DEFAULT_ENTRY_NAME; - if (!contains(apps_, name)) { - error('no-app', { name: name }); - } - return apps_[name]; - } - util.patchProperty(app, 'App', FirebaseAppImpl); - function initializeApp(options, rawConfig) { - if (rawConfig === void 0) { rawConfig = {}; } - if (typeof rawConfig !== 'object' || rawConfig === null) { - var name_1 = rawConfig; - rawConfig = { name: name_1 }; - } - var config = rawConfig; - if (config.name === undefined) { - config.name = DEFAULT_ENTRY_NAME; - } - var name = config.name; - if (typeof name !== 'string' || !name) { - error('bad-app-name', { name: name + '' }); - } - if (contains(apps_, name)) { - error('duplicate-app', { name: name }); - } - var app = new FirebaseAppImpl(options, config, namespace); - apps_[name] = app; - callAppHooks(app, 'create'); - return app; - } - /* - * Return an array of all the non-deleted FirebaseApps. - */ - function getApps() { - // Make a copy so caller cannot mutate the apps list. - return Object.keys(apps_).map(function (name) { return apps_[name]; }); - } - /* - * Register a Firebase Service. - * - * firebase.INTERNAL.registerService() - * - * TODO: Implement serviceProperties. - */ - function registerService(name, createService, serviceProperties, appHook, allowMultipleInstances) { - // Cannot re-register a service that already exists - if (factories[name]) { - error('duplicate-service', { name: name }); - } - // Capture the service factory for later service instantiation - factories[name] = createService; - // Capture the appHook, if passed - if (appHook) { - appHooks[name] = appHook; - // Run the **new** app hook on all existing apps - getApps().forEach(function (app) { - appHook('create', app); - }); - } - // The Service namespace is an accessor function ... - var serviceNamespace = function (appArg) { - if (appArg === void 0) { appArg = app(); } - if (typeof appArg[name] !== 'function') { - // Invalid argument. - // This happens in the following case: firebase.storage('gs:/') - error('invalid-app-argument', { name: name }); - } - // Forward service instance lookup to the FirebaseApp. - return appArg[name](); - }; - // ... and a container for service-level properties. - if (serviceProperties !== undefined) { - util.deepExtend(serviceNamespace, serviceProperties); - } - // Monkey-patch the serviceNamespace onto the firebase namespace - namespace[name] = serviceNamespace; - // Patch the FirebaseAppImpl prototype - FirebaseAppImpl.prototype[name] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var serviceFxn = this._getService.bind(this, name); - return serviceFxn.apply(this, allowMultipleInstances ? args : []); - }; - return serviceNamespace; - } - /** - * Patch the top-level firebase namespace with additional properties. - * - * firebase.INTERNAL.extendNamespace() - */ - function extendNamespace(props) { - util.deepExtend(namespace, props); - } - function callAppHooks(app, eventName) { - Object.keys(factories).forEach(function (serviceName) { - // Ignore virtual services - var factoryName = useAsService(app, serviceName); - if (factoryName === null) { - return; - } - if (appHooks[factoryName]) { - appHooks[factoryName](eventName, app); - } - }); - } - // Map the requested service to a registered service name - // (used to map auth to serverAuth service when needed). - function useAsService(app, name) { - if (name === 'serverAuth') { - return null; - } - var useService = name; - var options = app.options; - return useService; - } - return namespace; -} -function error(code, args) { - throw appErrors.create(code, args); -} -// TypeScript does not support non-string indexes! -// let errors: {[code: AppError: string} = { -var errors = { - 'no-app': "No Firebase App '{$name}' has been created - " + - 'call Firebase App.initializeApp()', - 'bad-app-name': "Illegal App name: '{$name}", - 'duplicate-app': "Firebase App named '{$name}' already exists", - 'app-deleted': "Firebase App named '{$name}' already deleted", - 'duplicate-service': "Firebase service named '{$name}' already registered", - 'sa-not-supported': 'Initializing the Firebase SDK with a service ' + - 'account is only allowed in a Node.js environment. On client ' + - 'devices, you should instead initialize the SDK with an api key and ' + - 'auth domain', - 'invalid-app-argument': 'firebase.{$name}() takes either no argument or a ' + - 'Firebase App instance.' -}; -var appErrors = new util.ErrorFactory('app', 'Firebase', errors); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * To avoid having to include the @types/react-native package, which breaks - * some of our tests because of duplicate symbols, we are using require syntax - * here - */ -var AsyncStorage = require('react-native').AsyncStorage; -var _firebase = createFirebaseNamespace(); -_firebase.INTERNAL.extendNamespace({ - INTERNAL: { - reactNative: { - AsyncStorage: AsyncStorage - } - } -}); -var firebase = _firebase; - -exports.firebase = firebase; -exports.default = firebase; diff --git a/functions/node_modules/@firebase/app/dist/index.rn.d.ts b/functions/node_modules/@firebase/app/dist/index.rn.d.ts deleted file mode 100644 index b1a5b19b..00000000 --- a/functions/node_modules/@firebase/app/dist/index.rn.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseNamespace } from '@firebase/app-types'; -export declare const firebase: FirebaseNamespace; -export default firebase; diff --git a/functions/node_modules/@firebase/app/dist/src/firebaseApp.d.ts b/functions/node_modules/@firebase/app/dist/src/firebaseApp.d.ts deleted file mode 100644 index 507f1bb5..00000000 --- a/functions/node_modules/@firebase/app/dist/src/firebaseApp.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseNamespace } from '@firebase/app-types'; -/** - * Return a firebase namespace object. - * - * In production, this will be called exactly once and the result - * assigned to the 'firebase' global. It may be called multiple times - * in unit tests. - */ -export declare function createFirebaseNamespace(): FirebaseNamespace; diff --git a/functions/node_modules/@firebase/app/dist/test/firebaseApp.test.d.ts b/functions/node_modules/@firebase/app/dist/test/firebaseApp.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/app/dist/test/firebaseApp.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/app/package.json b/functions/node_modules/@firebase/app/package.json deleted file mode 100644 index 08b700a2..00000000 --- a/functions/node_modules/@firebase/app/package.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "_from": "@firebase/app@^0.3.1", - "_id": "@firebase/app@0.3.5", - "_inBundle": false, - "_integrity": "sha512-DaAlb74yzwXbkFXvfsUVFeurSETPJAvKNtVpAKlS6RThyD+Y+ci1/8JVw4INm2hihbj/edxlAUelg9eoOZNCKA==", - "_location": "/@firebase/app", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@firebase/app@^0.3.1", - "name": "@firebase/app", - "escapedName": "@firebase%2fapp", - "scope": "@firebase", - "rawSpec": "^0.3.1", - "saveSpec": null, - "fetchSpec": "^0.3.1" - }, - "_requiredBy": [ - "/firebase-admin" - ], - "_resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.3.5.tgz", - "_shasum": "7011ab5a16604d6c1b2964d513b88c61a0a5387c", - "_spec": "@firebase/app@^0.3.1", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\firebase-admin", - "author": { - "name": "Firebase", - "email": "firebase-support@google.com", - "url": "https://firebase.google.com/" - }, - "browser": "dist/index.cjs.js", - "bugs": { - "url": "https://github.com/firebase/firebase-js-sdk/issues" - }, - "bundleDependencies": false, - "dependencies": { - "@firebase/app-types": "0.3.2", - "@firebase/util": "0.2.3", - "dom-storage": "2.1.0", - "tslib": "1.9.0", - "xmlhttprequest": "1.8.0" - }, - "deprecated": false, - "description": "The primary entrypoint to the Firebase JS SDK", - "devDependencies": { - "@types/chai": "4.1.2", - "@types/mocha": "5.0.0", - "@types/sinon": "4.3.1", - "chai": "4.1.2", - "karma": "2.0.0", - "karma-chrome-launcher": "2.2.0", - "karma-cli": "1.0.1", - "karma-coverage-istanbul-reporter": "1.4.2", - "karma-firefox-launcher": "1.1.0", - "karma-mocha": "1.3.0", - "karma-sauce-launcher": "1.2.0", - "karma-sourcemap-loader": "0.3.7", - "karma-spec-reporter": "0.0.32", - "karma-webpack": "2.0.9", - "mocha": "5.2.0", - "npm-run-all": "4.1.2", - "nyc": "11.6.0", - "rollup": "0.57.1", - "rollup-plugin-commonjs": "9.1.0", - "rollup-plugin-node-resolve": "3.3.0", - "rollup-plugin-replace": "2.0.0", - "rollup-plugin-typescript2": "0.12.0", - "sinon": "4.5.0", - "source-map-loader": "0.2.3", - "ts-loader": "3.5.0", - "ts-node": "5.0.1", - "typescript": "2.8.1", - "webpack": "3.11.0" - }, - "files": [ - "dist" - ], - "license": "Apache-2.0", - "main": "dist/index.node.cjs.js", - "module": "dist/index.esm.js", - "name": "@firebase/app", - "nyc": { - "extension": [ - ".ts" - ], - "reportDir": "./coverage/node" - }, - "react-native": "dist/index.rn.cjs.js", - "repository": { - "type": "git", - "url": "https://github.com/firebase/firebase-js-sdk/tree/master/packages/app" - }, - "scripts": { - "build": "rollup -c", - "dev": "rollup -c -w", - "prepare": "npm run build", - "test": "run-p test:browser test:node", - "test:browser": "karma start --single-run", - "test:browser:debug": "karma start --browsers Chrome --auto-watch", - "test:node": "TS_NODE_CACHE=NO nyc --reporter lcovonly -- mocha test/**/*.test.* --compilers ts:ts-node/register/type-check --exit" - }, - "typings": "dist/index.d.ts", - "version": "0.3.5" -} diff --git a/functions/node_modules/@firebase/database-types/README.md b/functions/node_modules/@firebase/database-types/README.md deleted file mode 100644 index 681f6b3b..00000000 --- a/functions/node_modules/@firebase/database-types/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# @firebase/database-types - -**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/functions/node_modules/@firebase/database-types/index.d.ts b/functions/node_modules/@firebase/database-types/index.d.ts deleted file mode 100644 index 708cb066..00000000 --- a/functions/node_modules/@firebase/database-types/index.d.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { FirebaseApp } from '@firebase/app-types'; - -export interface DataSnapshot { - child(path: string): DataSnapshot; - exists(): boolean; - exportVal(): any; - forEach(action: (a: DataSnapshot) => boolean | void): boolean; - getPriority(): string | number | null; - hasChild(path: string): boolean; - hasChildren(): boolean; - key: string | null; - numChildren(): number; - ref: Reference; - toJSON(): Object | null; - val(): any; -} - -export class FirebaseDatabase { - private constructor(); - - app: FirebaseApp; - goOffline(): void; - goOnline(): void; - ref(path?: string | Reference): Reference; - refFromURL(url: string): Reference; -} - -export interface OnDisconnect { - cancel(onComplete?: (a: Error | null) => any): Promise; - remove(onComplete?: (a: Error | null) => any): Promise; - set(value: any, onComplete?: (a: Error | null) => any): Promise; - setWithPriority( - value: any, - priority: number | string | null, - onComplete?: (a: Error | null) => any - ): Promise; - update(values: Object, onComplete?: (a: Error | null) => any): Promise; -} - -type EventType = - | 'value' - | 'child_added' - | 'child_changed' - | 'child_moved' - | 'child_removed'; - -export interface Query { - endAt(value: number | string | boolean | null, key?: string): Query; - equalTo(value: number | string | boolean | null, key?: string): Query; - isEqual(other: Query | null): boolean; - limitToFirst(limit: number): Query; - limitToLast(limit: number): Query; - off( - eventType?: EventType, - callback?: (a: DataSnapshot, b?: string | null) => any, - context?: Object | null - ): any; - on( - eventType: EventType, - callback: (a: DataSnapshot | null, b?: string) => any, - cancelCallbackOrContext?: Object | null, - context?: Object | null - ): (a: DataSnapshot | null, b?: string) => any; - once( - eventType: EventType, - successCallback?: (a: DataSnapshot, b?: string) => any, - failureCallbackOrContext?: Object | null, - context?: Object | null - ): Promise; - orderByChild(path: string): Query; - orderByKey(): Query; - orderByPriority(): Query; - orderByValue(): Query; - ref: Reference; - startAt(value: number | string | boolean | null, key?: string): Query; - toJSON(): Object; - toString(): string; -} - -export interface Reference extends Query { - child(path: string): Reference; - key: string | null; - onDisconnect(): OnDisconnect; - parent: Reference | null; - push(value?: any, onComplete?: (a: Error | null) => any): ThenableReference; - remove(onComplete?: (a: Error | null) => any): Promise; - root: Reference; - set(value: any, onComplete?: (a: Error | null) => any): Promise; - setPriority( - priority: string | number | null, - onComplete: (a: Error | null) => any - ): Promise; - setWithPriority( - newVal: any, - newPriority: string | number | null, - onComplete?: (a: Error | null) => any - ): Promise; - transaction( - transactionUpdate: (a: any) => any, - onComplete?: (a: Error | null, b: boolean, c: DataSnapshot | null) => any, - applyLocally?: boolean - ): Promise; - update(values: Object, onComplete?: (a: Error | null) => any): Promise; -} - -export interface ServerValue { - TIMESTAMP: { - '.sv': string; - }; -} - -export interface ThenableReference extends Reference, PromiseLike {} - -export function enableLogging( - logger?: boolean | ((a: string) => any), - persistent?: boolean -): any; diff --git a/functions/node_modules/@firebase/database-types/package.json b/functions/node_modules/@firebase/database-types/package.json deleted file mode 100644 index 9ea91595..00000000 --- a/functions/node_modules/@firebase/database-types/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "_from": "@firebase/database-types@0.3.2", - "_id": "@firebase/database-types@0.3.2", - "_inBundle": false, - "_integrity": "sha512-9ZYdvYQ6r3aaHJarhUM5Hf6lQWu3ZJme+RR0o8qfBb9L04TL3uNjt+AJFku1ysVPntTn+9GqJjiIB2/OC3JtwA==", - "_location": "/@firebase/database-types", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "@firebase/database-types@0.3.2", - "name": "@firebase/database-types", - "escapedName": "@firebase%2fdatabase-types", - "scope": "@firebase", - "rawSpec": "0.3.2", - "saveSpec": null, - "fetchSpec": "0.3.2" - }, - "_requiredBy": [ - "/@firebase/database" - ], - "_resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-0.3.2.tgz", - "_shasum": "70611a64dd460e0e253c7427f860d56a1afd86fe", - "_spec": "@firebase/database-types@0.3.2", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@firebase\\database", - "author": { - "name": "Firebase", - "email": "firebase-support@google.com", - "url": "https://firebase.google.com/" - }, - "bugs": { - "url": "https://github.com/firebase/firebase-js-sdk/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "@firebase/database Types", - "devDependencies": { - "typescript": "2.8.1" - }, - "files": [ - "index.d.ts" - ], - "license": "Apache-2.0", - "name": "@firebase/database-types", - "peerDependencies": { - "@firebase/app-types": "0.x" - }, - "repository": { - "type": "git", - "url": "https://github.com/firebase/firebase-js-sdk/tree/master/packages/database-types" - }, - "scripts": { - "test": "tsc" - }, - "version": "0.3.2" -} diff --git a/functions/node_modules/@firebase/database/README.md b/functions/node_modules/@firebase/database/README.md deleted file mode 100644 index 5fc92ccc..00000000 --- a/functions/node_modules/@firebase/database/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# @firebase/database - -This is the Firebase Realtime Database component of the Firebase JS SDK. - -**This package is not intended for direct usage, and should only be used via the officially supported [firebase](https://www.npmjs.com/package/firebase) package.** diff --git a/functions/node_modules/@firebase/database/dist/index.cjs.js b/functions/node_modules/@firebase/database/dist/index.cjs.js deleted file mode 100644 index 672cc2bb..00000000 --- a/functions/node_modules/@firebase/database/dist/index.cjs.js +++ /dev/null @@ -1,15354 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var util = require('@firebase/util'); -var logger = require('@firebase/logger'); -var tslib_1 = require('tslib'); -var firebase = _interopDefault(require('@firebase/app')); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Wraps a DOM Storage object and: - * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. - * - prefixes names with "firebase:" to avoid collisions with app data. - * - * We automatically (see storage.js) create two such wrappers, one for sessionStorage, - * and one for localStorage. - * - * @constructor - */ -var DOMStorageWrapper = /** @class */ (function () { - /** - * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage) - */ - function DOMStorageWrapper(domStorage_) { - this.domStorage_ = domStorage_; - // Use a prefix to avoid collisions with other stuff saved by the app. - this.prefix_ = 'firebase:'; - } - /** - * @param {string} key The key to save the value under - * @param {?Object} value The value being stored, or null to remove the key. - */ - DOMStorageWrapper.prototype.set = function (key, value) { - if (value == null) { - this.domStorage_.removeItem(this.prefixedName_(key)); - } - else { - this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); - } - }; - /** - * @param {string} key - * @return {*} The value that was stored under this key, or null - */ - DOMStorageWrapper.prototype.get = function (key) { - var storedVal = this.domStorage_.getItem(this.prefixedName_(key)); - if (storedVal == null) { - return null; - } - else { - return util.jsonEval(storedVal); - } - }; - /** - * @param {string} key - */ - DOMStorageWrapper.prototype.remove = function (key) { - this.domStorage_.removeItem(this.prefixedName_(key)); - }; - /** - * @param {string} name - * @return {string} - */ - DOMStorageWrapper.prototype.prefixedName_ = function (name) { - return this.prefix_ + name; - }; - DOMStorageWrapper.prototype.toString = function () { - return this.domStorage_.toString(); - }; - return DOMStorageWrapper; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An in-memory storage implementation that matches the API of DOMStorageWrapper - * (TODO: create interface for both to implement). - * - * @constructor - */ -var MemoryStorage = /** @class */ (function () { - function MemoryStorage() { - this.cache_ = {}; - this.isInMemoryStorage = true; - } - MemoryStorage.prototype.set = function (key, value) { - if (value == null) { - delete this.cache_[key]; - } - else { - this.cache_[key] = value; - } - }; - MemoryStorage.prototype.get = function (key) { - if (util.contains(this.cache_, key)) { - return this.cache_[key]; - } - return null; - }; - MemoryStorage.prototype.remove = function (key) { - delete this.cache_[key]; - }; - return MemoryStorage; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. - * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change - * to reflect this type - * - * @param {string} domStorageName Name of the underlying storage object - * (e.g. 'localStorage' or 'sessionStorage'). - * @return {?} Turning off type information until a common interface is defined. - */ -var createStoragefor = function (domStorageName) { - try { - // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, - // so it must be inside the try/catch. - if (typeof window !== 'undefined' && - typeof window[domStorageName] !== 'undefined') { - // Need to test cache. Just because it's here doesn't mean it works - var domStorage = window[domStorageName]; - domStorage.setItem('firebase:sentinel', 'cache'); - domStorage.removeItem('firebase:sentinel'); - return new DOMStorageWrapper(domStorage); - } - } - catch (e) { } - // Failed to create wrapper. Just return in-memory storage. - // TODO: log? - return new MemoryStorage(); -}; -/** A storage object that lasts across sessions */ -var PersistentStorage = createStoragefor('localStorage'); -/** A storage object that only lasts one session */ -var SessionStorage = createStoragefor('sessionStorage'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var logClient = new logger.Logger('@firebase/database'); -/** - * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). - * @type {function(): number} Generated ID. - */ -var LUIDGenerator = (function () { - var id = 1; - return function () { - return id++; - }; -})(); -/** - * Sha1 hash of the input string - * @param {!string} str The string to hash - * @return {!string} The resulting hash - */ -var sha1 = function (str) { - var utf8Bytes = util.stringToByteArray(str); - var sha1 = new util.Sha1(); - sha1.update(utf8Bytes); - var sha1Bytes = sha1.digest(); - return util.base64.encodeByteArray(sha1Bytes); -}; -/** - * @param {...*} var_args - * @return {string} - * @private - */ -var buildLogMessage_ = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = ''; - for (var i = 0; i < var_args.length; i++) { - if (Array.isArray(var_args[i]) || - (var_args[i] && - typeof var_args[i] === 'object' && - typeof var_args[i].length === 'number')) { - message += buildLogMessage_.apply(null, var_args[i]); - } - else if (typeof var_args[i] === 'object') { - message += util.stringify(var_args[i]); - } - else { - message += var_args[i]; - } - message += ' '; - } - return message; -}; -/** - * Use this for all debug messages in Firebase. - * @type {?function(string)} - */ -var logger$1 = null; -/** - * Flag to check for log availability on first log message - * @type {boolean} - * @private - */ -var firstLog_ = true; -/** - * The implementation of Firebase.enableLogging (defined here to break dependencies) - * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger - * @param {boolean=} persistent Whether or not to persist logging settings across refreshes - */ -var enableLogging = function (logger_, persistent) { - util.assert(!persistent || (logger_ === true || logger_ === false), "Can't turn on custom loggers persistently."); - if (logger_ === true) { - logClient.logLevel = logger.LogLevel.VERBOSE; - logger$1 = logClient.log.bind(logClient); - if (persistent) - SessionStorage.set('logging_enabled', true); - } - else if (typeof logger_ === 'function') { - logger$1 = logger_; - } - else { - logger$1 = null; - SessionStorage.remove('logging_enabled'); - } -}; -/** - * - * @param {...(string|Arguments)} var_args - */ -var log = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - if (firstLog_ === true) { - firstLog_ = false; - if (logger$1 === null && SessionStorage.get('logging_enabled') === true) - enableLogging(true); - } - if (logger$1) { - var message = buildLogMessage_.apply(null, var_args); - logger$1(message); - } -}; -/** - * @param {!string} prefix - * @return {function(...[*])} - */ -var logWrapper = function (prefix) { - return function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - log.apply(void 0, [prefix].concat(var_args)); - }; -}; -/** - * @param {...string} var_args - */ -var error = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args); - logClient.error(message); -}; -/** - * @param {...string} var_args - */ -var fatal = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = "FIREBASE FATAL ERROR: " + buildLogMessage_.apply(void 0, var_args); - logClient.error(message); - throw new Error(message); -}; -/** - * @param {...*} var_args - */ -var warn = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args); - logClient.warn(message); -}; -/** - * Logs a warning if the containing page uses https. Called when a call to new Firebase - * does not use https. - */ -var warnIfPageIsSecure = function () { - // Be very careful accessing browser globals. Who knows what may or may not exist. - if (typeof window !== 'undefined' && - window.location && - window.location.protocol && - window.location.protocol.indexOf('https:') !== -1) { - warn('Insecure Firebase access from a secure page. ' + - 'Please use https in calls to new Firebase().'); - } -}; -/** - * Returns true if data is NaN, or +/- Infinity. - * @param {*} data - * @return {boolean} - */ -var isInvalidJSONNumber = function (data) { - return (typeof data === 'number' && - (data != data || // NaN - data == Number.POSITIVE_INFINITY || - data == Number.NEGATIVE_INFINITY)); -}; -/** - * @param {function()} fn - */ -var executeWhenDOMReady = function (fn) { - if (util.isNodeSdk() || document.readyState === 'complete') { - fn(); - } - else { - // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which - // fire before onload), but fall back to onload. - var called_1 = false; - var wrappedFn_1 = function () { - if (!document.body) { - setTimeout(wrappedFn_1, Math.floor(10)); - return; - } - if (!called_1) { - called_1 = true; - fn(); - } - }; - if (document.addEventListener) { - document.addEventListener('DOMContentLoaded', wrappedFn_1, false); - // fallback to onload. - window.addEventListener('load', wrappedFn_1, false); - } - else if (document.attachEvent) { - // IE. - document.attachEvent('onreadystatechange', function () { - if (document.readyState === 'complete') - wrappedFn_1(); - }); - // fallback to onload. - window.attachEvent('onload', wrappedFn_1); - // jQuery has an extra hack for IE that we could employ (based on - // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. - // I'm hoping we don't need it. - } - } -}; -/** - * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names - * @type {!string} - */ -var MIN_NAME = '[MIN_NAME]'; -/** - * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names - * @type {!string} - */ -var MAX_NAME = '[MAX_NAME]'; -/** - * Compares valid Firebase key names, plus min and max name - * @param {!string} a - * @param {!string} b - * @return {!number} - */ -var nameCompare = function (a, b) { - if (a === b) { - return 0; - } - else if (a === MIN_NAME || b === MAX_NAME) { - return -1; - } - else if (b === MIN_NAME || a === MAX_NAME) { - return 1; - } - else { - var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); - if (aAsInt !== null) { - if (bAsInt !== null) { - return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt; - } - else { - return -1; - } - } - else if (bAsInt !== null) { - return 1; - } - else { - return a < b ? -1 : 1; - } - } -}; -/** - * @param {!string} a - * @param {!string} b - * @return {!number} comparison result. - */ -var stringCompare = function (a, b) { - if (a === b) { - return 0; - } - else if (a < b) { - return -1; - } - else { - return 1; - } -}; -/** - * @param {string} key - * @param {Object} obj - * @return {*} - */ -var requireKey = function (key, obj) { - if (obj && key in obj) { - return obj[key]; - } - else { - throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); - } -}; -/** - * @param {*} obj - * @return {string} - */ -var ObjectToUniqueKey = function (obj) { - if (typeof obj !== 'object' || obj === null) - return util.stringify(obj); - var keys = []; - for (var k in obj) { - keys.push(k); - } - // Export as json, but with the keys sorted. - keys.sort(); - var key = '{'; - for (var i = 0; i < keys.length; i++) { - if (i !== 0) - key += ','; - key += util.stringify(keys[i]); - key += ':'; - key += ObjectToUniqueKey(obj[keys[i]]); - } - key += '}'; - return key; -}; -/** - * Splits a string into a number of smaller segments of maximum size - * @param {!string} str The string - * @param {!number} segsize The maximum number of chars in the string. - * @return {Array.} The string, split into appropriately-sized chunks - */ -var splitStringBySize = function (str, segsize) { - var len = str.length; - if (len <= segsize) { - return [str]; - } - var dataSegs = []; - for (var c = 0; c < len; c += segsize) { - if (c + segsize > len) { - dataSegs.push(str.substring(c, len)); - } - else { - dataSegs.push(str.substring(c, c + segsize)); - } - } - return dataSegs; -}; -/** - * Apply a function to each (key, value) pair in an object or - * apply a function to each (index, value) pair in an array - * @param {!(Object|Array)} obj The object or array to iterate over - * @param {function(?, ?)} fn The function to apply - */ -var each = function (obj, fn) { - if (Array.isArray(obj)) { - for (var i = 0; i < obj.length; ++i) { - fn(i, obj[i]); - } - } - else { - /** - * in the conversion of code we removed the goog.object.forEach - * function which did a value,key callback. We standardized on - * a single impl that does a key, value callback. So we invert - * to not have to touch the `each` code points - */ - util.forEach(obj, function (key, val) { return fn(val, key); }); - } -}; -/** - * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) - * I made one modification at the end and removed the NaN / Infinity - * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. - * @param {!number} v A double - * @return {string} - */ -var doubleToIEEE754String = function (v) { - util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL - var ebits = 11, fbits = 52; - var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str; - // Compute sign, exponent, fraction - // Skip NaN / Infinity handling --MJL. - if (v === 0) { - e = 0; - f = 0; - s = 1 / v === -Infinity ? 1 : 0; - } - else { - s = v < 0; - v = Math.abs(v); - if (v >= Math.pow(2, 1 - bias)) { - // Normalized - ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); - e = ln + bias; - f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); - } - else { - // Denormalized - e = 0; - f = Math.round(v / Math.pow(2, 1 - bias - fbits)); - } - } - // Pack sign, exponent, fraction - bits = []; - for (i = fbits; i; i -= 1) { - bits.push(f % 2 ? 1 : 0); - f = Math.floor(f / 2); - } - for (i = ebits; i; i -= 1) { - bits.push(e % 2 ? 1 : 0); - e = Math.floor(e / 2); - } - bits.push(s ? 1 : 0); - bits.reverse(); - str = bits.join(''); - // Return the data as a hex string. --MJL - var hexByteString = ''; - for (i = 0; i < 64; i += 8) { - var hexByte = parseInt(str.substr(i, 8), 2).toString(16); - if (hexByte.length === 1) - hexByte = '0' + hexByte; - hexByteString = hexByteString + hexByte; - } - return hexByteString.toLowerCase(); -}; -/** - * Used to detect if we're in a Chrome content script (which executes in an - * isolated environment where long-polling doesn't work). - * @return {boolean} - */ -var isChromeExtensionContentScript = function () { - return !!(typeof window === 'object' && - window['chrome'] && - window['chrome']['extension'] && - !/^chrome/.test(window.location.href)); -}; -/** - * Used to detect if we're in a Windows 8 Store app. - * @return {boolean} - */ -var isWindowsStoreApp = function () { - // Check for the presence of a couple WinRT globals - return typeof Windows === 'object' && typeof Windows.UI === 'object'; -}; -/** - * Converts a server error code to a Javascript Error - * @param {!string} code - * @param {!Query} query - * @return {Error} - */ -var errorForServerCode = function (code, query) { - var reason = 'Unknown Error'; - if (code === 'too_big') { - reason = - 'The data requested exceeds the maximum size ' + - 'that can be accessed with a single request.'; - } - else if (code == 'permission_denied') { - reason = "Client doesn't have permission to access the desired data."; - } - else if (code == 'unavailable') { - reason = 'The service is unavailable'; - } - var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason); - error.code = code.toUpperCase(); - return error; -}; -/** - * Used to test for integer-looking strings - * @type {RegExp} - * @private - */ -var INTEGER_REGEXP_ = new RegExp('^-?\\d{1,10}$'); -/** - * If the string contains a 32-bit integer, return it. Else return null. - * @param {!string} str - * @return {?number} - */ -var tryParseInt = function (str) { - if (INTEGER_REGEXP_.test(str)) { - var intVal = Number(str); - if (intVal >= -2147483648 && intVal <= 2147483647) { - return intVal; - } - } - return null; -}; -/** - * Helper to run some code but catch any exceptions and re-throw them later. - * Useful for preventing user callbacks from breaking internal code. - * - * Re-throwing the exception from a setTimeout is a little evil, but it's very - * convenient (we don't have to try to figure out when is a safe point to - * re-throw it), and the behavior seems reasonable: - * - * * If you aren't pausing on exceptions, you get an error in the console with - * the correct stack trace. - * * If you're pausing on all exceptions, the debugger will pause on your - * exception and then again when we rethrow it. - * * If you're only pausing on uncaught exceptions, the debugger will only pause - * on us re-throwing it. - * - * @param {!function()} fn The code to guard. - */ -var exceptionGuard = function (fn) { - try { - fn(); - } - catch (e) { - // Re-throw exception when it's safe. - setTimeout(function () { - // It used to be that "throw e" would result in a good console error with - // relevant context, but as of Chrome 39, you just get the firebase.js - // file/line number where we re-throw it, which is useless. So we log - // e.stack explicitly. - var stack = e.stack || ''; - warn('Exception was thrown by user callback.', stack); - throw e; - }, Math.floor(0)); - } -}; -/** - * @return {boolean} true if we think we're currently being crawled. - */ -var beingCrawled = function () { - var userAgent = (typeof window === 'object' && - window['navigator'] && - window['navigator']['userAgent']) || - ''; - // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we - // believe to support JavaScript/AJAX rendering. - // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website - // would have seen the page" is flaky if we don't treat it as a crawler. - return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); -}; -/** - * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. - * - * It is removed with clearTimeout() as normal. - * - * @param {Function} fn Function to run. - * @param {number} time Milliseconds to wait before running. - * @return {number|Object} The setTimeout() return value. - */ -var setTimeoutNonBlocking = function (fn, time) { - var timeout = setTimeout(fn, time); - if (typeof timeout === 'object' && timeout['unref']) { - timeout['unref'](); - } - return timeout; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An immutable object representing a parsed path. It's immutable so that you - * can pass them around to other functions without worrying about them changing - * it. - */ -var Path = /** @class */ (function () { - /** - * @param {string|Array.} pathOrString Path string to parse, - * or another path, or the raw tokens array - * @param {number=} pieceNum - */ - function Path(pathOrString, pieceNum) { - if (pieceNum === void 0) { - this.pieces_ = pathOrString.split('/'); - // Remove empty pieces. - var copyTo = 0; - for (var i = 0; i < this.pieces_.length; i++) { - if (this.pieces_[i].length > 0) { - this.pieces_[copyTo] = this.pieces_[i]; - copyTo++; - } - } - this.pieces_.length = copyTo; - this.pieceNum_ = 0; - } - else { - this.pieces_ = pathOrString; - this.pieceNum_ = pieceNum; - } - } - Object.defineProperty(Path, "Empty", { - /** - * Singleton to represent an empty path - * - * @const - */ - get: function () { - return new Path(''); - }, - enumerable: true, - configurable: true - }); - Path.prototype.getFront = function () { - if (this.pieceNum_ >= this.pieces_.length) - return null; - return this.pieces_[this.pieceNum_]; - }; - /** - * @return {number} The number of segments in this path - */ - Path.prototype.getLength = function () { - return this.pieces_.length - this.pieceNum_; - }; - /** - * @return {!Path} - */ - Path.prototype.popFront = function () { - var pieceNum = this.pieceNum_; - if (pieceNum < this.pieces_.length) { - pieceNum++; - } - return new Path(this.pieces_, pieceNum); - }; - /** - * @return {?string} - */ - Path.prototype.getBack = function () { - if (this.pieceNum_ < this.pieces_.length) - return this.pieces_[this.pieces_.length - 1]; - return null; - }; - Path.prototype.toString = function () { - var pathString = ''; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) { - if (this.pieces_[i] !== '') - pathString += '/' + this.pieces_[i]; - } - return pathString || '/'; - }; - Path.prototype.toUrlEncodedString = function () { - var pathString = ''; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) { - if (this.pieces_[i] !== '') - pathString += '/' + encodeURIComponent(String(this.pieces_[i])); - } - return pathString || '/'; - }; - /** - * Shallow copy of the parts of the path. - * - * @param {number=} begin - * @return {!Array} - */ - Path.prototype.slice = function (begin) { - if (begin === void 0) { begin = 0; } - return this.pieces_.slice(this.pieceNum_ + begin); - }; - /** - * @return {?Path} - */ - Path.prototype.parent = function () { - if (this.pieceNum_ >= this.pieces_.length) - return null; - var pieces = []; - for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++) - pieces.push(this.pieces_[i]); - return new Path(pieces, 0); - }; - /** - * @param {string|!Path} childPathObj - * @return {!Path} - */ - Path.prototype.child = function (childPathObj) { - var pieces = []; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) - pieces.push(this.pieces_[i]); - if (childPathObj instanceof Path) { - for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { - pieces.push(childPathObj.pieces_[i]); - } - } - else { - var childPieces = childPathObj.split('/'); - for (var i = 0; i < childPieces.length; i++) { - if (childPieces[i].length > 0) - pieces.push(childPieces[i]); - } - } - return new Path(pieces, 0); - }; - /** - * @return {boolean} True if there are no segments in this path - */ - Path.prototype.isEmpty = function () { - return this.pieceNum_ >= this.pieces_.length; - }; - /** - * @param {!Path} outerPath - * @param {!Path} innerPath - * @return {!Path} The path from outerPath to innerPath - */ - Path.relativePath = function (outerPath, innerPath) { - var outer = outerPath.getFront(), inner = innerPath.getFront(); - if (outer === null) { - return innerPath; - } - else if (outer === inner) { - return Path.relativePath(outerPath.popFront(), innerPath.popFront()); - } - else { - throw new Error('INTERNAL ERROR: innerPath (' + - innerPath + - ') is not within ' + - 'outerPath (' + - outerPath + - ')'); - } - }; - /** - * @param {!Path} left - * @param {!Path} right - * @return {number} -1, 0, 1 if left is less, equal, or greater than the right. - */ - Path.comparePaths = function (left, right) { - var leftKeys = left.slice(); - var rightKeys = right.slice(); - for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) { - var cmp = nameCompare(leftKeys[i], rightKeys[i]); - if (cmp !== 0) - return cmp; - } - if (leftKeys.length === rightKeys.length) - return 0; - return leftKeys.length < rightKeys.length ? -1 : 1; - }; - /** - * - * @param {Path} other - * @return {boolean} true if paths are the same. - */ - Path.prototype.equals = function (other) { - if (this.getLength() !== other.getLength()) { - return false; - } - for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) { - if (this.pieces_[i] !== other.pieces_[j]) { - return false; - } - } - return true; - }; - /** - * - * @param {!Path} other - * @return {boolean} True if this path is a parent (or the same as) other - */ - Path.prototype.contains = function (other) { - var i = this.pieceNum_; - var j = other.pieceNum_; - if (this.getLength() > other.getLength()) { - return false; - } - while (i < this.pieces_.length) { - if (this.pieces_[i] !== other.pieces_[j]) { - return false; - } - ++i; - ++j; - } - return true; - }; - return Path; -}()); // end Path -/** - * Dynamic (mutable) path used to count path lengths. - * - * This class is used to efficiently check paths for valid - * length (in UTF8 bytes) and depth (used in path validation). - * - * Throws Error exception if path is ever invalid. - * - * The definition of a path always begins with '/'. - */ -var ValidationPath = /** @class */ (function () { - /** - * @param {!Path} path Initial Path. - * @param {string} errorPrefix_ Prefix for any error messages. - */ - function ValidationPath(path, errorPrefix_) { - this.errorPrefix_ = errorPrefix_; - /** @type {!Array} */ - this.parts_ = path.slice(); - /** @type {number} Initialize to number of '/' chars needed in path. */ - this.byteLength_ = Math.max(1, this.parts_.length); - for (var i = 0; i < this.parts_.length; i++) { - this.byteLength_ += util.stringLength(this.parts_[i]); - } - this.checkValid_(); - } - Object.defineProperty(ValidationPath, "MAX_PATH_DEPTH", { - /** @const {number} Maximum key depth. */ - get: function () { - return 32; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ValidationPath, "MAX_PATH_LENGTH_BYTES", { - /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */ - get: function () { - return 768; - }, - enumerable: true, - configurable: true - }); - /** @param {string} child */ - ValidationPath.prototype.push = function (child) { - // Count the needed '/' - if (this.parts_.length > 0) { - this.byteLength_ += 1; - } - this.parts_.push(child); - this.byteLength_ += util.stringLength(child); - this.checkValid_(); - }; - ValidationPath.prototype.pop = function () { - var last = this.parts_.pop(); - this.byteLength_ -= util.stringLength(last); - // Un-count the previous '/' - if (this.parts_.length > 0) { - this.byteLength_ -= 1; - } - }; - ValidationPath.prototype.checkValid_ = function () { - if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) { - throw new Error(this.errorPrefix_ + - 'has a key path longer than ' + - ValidationPath.MAX_PATH_LENGTH_BYTES + - ' bytes (' + - this.byteLength_ + - ').'); - } - if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) { - throw new Error(this.errorPrefix_ + - 'path specified exceeds the maximum depth that can be written (' + - ValidationPath.MAX_PATH_DEPTH + - ') or object contains a cycle ' + - this.toErrorString()); - } - }; - /** - * String for use in error messages - uses '.' notation for path. - * - * @return {string} - */ - ValidationPath.prototype.toErrorString = function () { - if (this.parts_.length == 0) { - return ''; - } - return "in property '" + this.parts_.join('.') + "'"; - }; - return ValidationPath; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var PROTOCOL_VERSION = '5'; -var VERSION_PARAM = 'v'; -var TRANSPORT_SESSION_PARAM = 's'; -var REFERER_PARAM = 'r'; -var FORGE_REF = 'f'; -var FORGE_DOMAIN = 'firebaseio.com'; -var LAST_SESSION_PARAM = 'ls'; -var WEBSOCKET = 'websocket'; -var LONG_POLLING = 'long_polling'; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A class that holds metadata about a Repo object - * - * @constructor - */ -var RepoInfo = /** @class */ (function () { - /** - * @param {string} host Hostname portion of the url for the repo - * @param {boolean} secure Whether or not this repo is accessed over ssl - * @param {string} namespace The namespace represented by the repo - * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest). - * @param {string=} persistenceKey Override the default session persistence storage key - */ - function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) { - if (persistenceKey === void 0) { persistenceKey = ''; } - this.secure = secure; - this.namespace = namespace; - this.webSocketOnly = webSocketOnly; - this.persistenceKey = persistenceKey; - this.host = host.toLowerCase(); - this.domain = this.host.substr(this.host.indexOf('.') + 1); - this.internalHost = PersistentStorage.get('host:' + host) || this.host; - } - RepoInfo.prototype.needsQueryParam = function () { - return this.host !== this.internalHost || this.isCustomHost(); - }; - RepoInfo.prototype.isCacheableHost = function () { - return this.internalHost.substr(0, 2) === 's-'; - }; - RepoInfo.prototype.isDemoHost = function () { - return this.domain === 'firebaseio-demo.com'; - }; - RepoInfo.prototype.isCustomHost = function () { - return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com'); - }; - RepoInfo.prototype.updateHost = function (newHost) { - if (newHost !== this.internalHost) { - this.internalHost = newHost; - if (this.isCacheableHost()) { - PersistentStorage.set('host:' + this.host, this.internalHost); - } - } - }; - /** - * Returns the websocket URL for this repo - * @param {string} type of connection - * @param {Object} params list - * @return {string} The URL for this repo - */ - RepoInfo.prototype.connectionURL = function (type, params) { - util.assert(typeof type === 'string', 'typeof type must == string'); - util.assert(typeof params === 'object', 'typeof params must == object'); - var connURL; - if (type === WEBSOCKET) { - connURL = - (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?'; - } - else if (type === LONG_POLLING) { - connURL = - (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?'; - } - else { - throw new Error('Unknown connection type: ' + type); - } - if (this.needsQueryParam()) { - params['ns'] = this.namespace; - } - var pairs = []; - util.forEach(params, function (key, value) { - pairs.push(key + '=' + value); - }); - return connURL + pairs.join('&'); - }; - /** @return {string} */ - RepoInfo.prototype.toString = function () { - var str = this.toURLString(); - if (this.persistenceKey) { - str += '<' + this.persistenceKey + '>'; - } - return str; - }; - /** @return {string} */ - RepoInfo.prototype.toURLString = function () { - return (this.secure ? 'https://' : 'http://') + this.host; - }; - return RepoInfo; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!string} pathString - * @return {string} - */ -function decodePath(pathString) { - var pathStringDecoded = ''; - var pieces = pathString.split('/'); - for (var i = 0; i < pieces.length; i++) { - if (pieces[i].length > 0) { - var piece = pieces[i]; - try { - piece = decodeURIComponent(piece.replace(/\+/g, ' ')); - } - catch (e) { } - pathStringDecoded += '/' + piece; - } - } - return pathStringDecoded; -} -/** - * @param {!string} queryString - * @return {!{[key:string]:string}} key value hash - */ -function decodeQuery(queryString) { - var results = {}; - if (queryString.charAt(0) === '?') { - queryString = queryString.substring(1); - } - for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) { - var segment = _a[_i]; - if (segment.length === 0) { - continue; - } - var kv = segment.split('='); - if (kv.length === 2) { - results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); - } - else { - warn("Invalid query segment '" + segment + "' in query '" + queryString + "'"); - } - } - return results; -} -/** - * - * @param {!string} dataURL - * @return {{repoInfo: !RepoInfo, path: !Path}} - */ -var parseRepoInfo = function (dataURL) { - var parsedUrl = parseURL(dataURL), namespace = parsedUrl.subdomain; - if (parsedUrl.domain === 'firebase') { - fatal(parsedUrl.host + - ' is no longer supported. ' + - 'Please use .firebaseio.com instead'); - } - // Catch common error of uninitialized namespace value. - if ((!namespace || namespace == 'undefined') && - parsedUrl.domain !== 'localhost') { - fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); - } - if (!parsedUrl.secure) { - warnIfPageIsSecure(); - } - var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; - return { - repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly), - path: new Path(parsedUrl.pathString) - }; -}; -/** - * - * @param {!string} dataURL - * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}} - */ -var parseURL = function (dataURL) { - // Default to empty strings in the event of a malformed string. - var host = '', domain = '', subdomain = '', pathString = ''; - // Always default to SSL, unless otherwise specified. - var secure = true, scheme = 'https', port = 443; - // Don't do any validation here. The caller is responsible for validating the result of parsing. - if (typeof dataURL === 'string') { - // Parse scheme. - var colonInd = dataURL.indexOf('//'); - if (colonInd >= 0) { - scheme = dataURL.substring(0, colonInd - 1); - dataURL = dataURL.substring(colonInd + 2); - } - // Parse host, path, and query string. - var slashInd = dataURL.indexOf('/'); - if (slashInd === -1) { - slashInd = dataURL.length; - } - var questionMarkInd = dataURL.indexOf('?'); - if (questionMarkInd === -1) { - questionMarkInd = dataURL.length; - } - host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); - if (slashInd < questionMarkInd) { - // For pathString, questionMarkInd will always come after slashInd - pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); - } - var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); - // If we have a port, use scheme for determining if it's secure. - colonInd = host.indexOf(':'); - if (colonInd >= 0) { - secure = scheme === 'https' || scheme === 'wss'; - port = parseInt(host.substring(colonInd + 1), 10); - } - else { - colonInd = dataURL.length; - } - var parts = host.split('.'); - if (parts.length === 3) { - // Normalize namespaces to lowercase to share storage / connection. - domain = parts[1]; - subdomain = parts[0].toLowerCase(); - } - else if (parts.length === 2) { - domain = parts[0]; - } - else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') { - domain = 'localhost'; - } - // Support `ns` query param if subdomain not already set - if (subdomain === '' && 'ns' in queryParams) { - subdomain = queryParams['ns']; - } - } - return { - host: host, - port: port, - domain: domain, - subdomain: subdomain, - secure: secure, - scheme: scheme, - pathString: pathString - }; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * True for invalid Firebase keys - * @type {RegExp} - * @private - */ -var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; -/** - * True for invalid Firebase paths. - * Allows '/' in paths. - * @type {RegExp} - * @private - */ -var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; -/** - * Maximum number of characters to allow in leaf value - * @type {number} - * @private - */ -var MAX_LEAF_SIZE_ = 10 * 1024 * 1024; -/** - * @param {*} key - * @return {boolean} - */ -var isValidKey = function (key) { - return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); -}; -/** - * @param {string} pathString - * @return {boolean} - */ -var isValidPathString = function (pathString) { - return (typeof pathString === 'string' && - pathString.length !== 0 && - !INVALID_PATH_REGEX_.test(pathString)); -}; -/** - * @param {string} pathString - * @return {boolean} - */ -var isValidRootPathString = function (pathString) { - if (pathString) { - // Allow '/.info/' at the beginning. - pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); - } - return isValidPathString(pathString); -}; -/** - * @param {*} priority - * @return {boolean} - */ -var isValidPriority = function (priority) { - return (priority === null || - typeof priority === 'string' || - (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || - (priority && typeof priority === 'object' && util.contains(priority, '.sv'))); -}; -/** - * Pre-validate a datum passed as an argument to Firebase function. - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -var validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) { - if (optional && data === undefined) - return; - validateFirebaseData(util.errorPrefix(fnName, argumentNumber, optional), data, path); -}; -/** - * Validate a data object client-side before sending to server. - * - * @param {string} errorPrefix - * @param {*} data - * @param {!Path|!ValidationPath} path_ - */ -var validateFirebaseData = function (errorPrefix, data, path_) { - var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; - if (data === undefined) { - throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString()); - } - if (typeof data === 'function') { - throw new Error(errorPrefix + - 'contains a function ' + - path.toErrorString() + - ' with contents = ' + - data.toString()); - } - if (isInvalidJSONNumber(data)) { - throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString()); - } - // Check max leaf size, but try to avoid the utf8 conversion if we can. - if (typeof data === 'string' && - data.length > MAX_LEAF_SIZE_ / 3 && - util.stringLength(data) > MAX_LEAF_SIZE_) { - throw new Error(errorPrefix + - 'contains a string greater than ' + - MAX_LEAF_SIZE_ + - ' utf8 bytes ' + - path.toErrorString() + - " ('" + - data.substring(0, 50) + - "...')"); - } - // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON - // to save extra walking of large objects. - if (data && typeof data === 'object') { - var hasDotValue_1 = false, hasActualChild_1 = false; - util.forEach(data, function (key, value) { - if (key === '.value') { - hasDotValue_1 = true; - } - else if (key !== '.priority' && key !== '.sv') { - hasActualChild_1 = true; - if (!isValidKey(key)) { - throw new Error(errorPrefix + - ' contains an invalid key (' + - key + - ') ' + - path.toErrorString() + - '. Keys must be non-empty strings ' + - 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); - } - } - path.push(key); - validateFirebaseData(errorPrefix, value, path); - path.pop(); - }); - if (hasDotValue_1 && hasActualChild_1) { - throw new Error(errorPrefix + - ' contains ".value" child ' + - path.toErrorString() + - ' in addition to actual children.'); - } - } -}; -/** - * Pre-validate paths passed in the firebase function. - * - * @param {string} errorPrefix - * @param {Array} mergePaths - */ -var validateFirebaseMergePaths = function (errorPrefix, mergePaths) { - var i, curPath; - for (i = 0; i < mergePaths.length; i++) { - curPath = mergePaths[i]; - var keys = curPath.slice(); - for (var j = 0; j < keys.length; j++) { - if (keys[j] === '.priority' && j === keys.length - 1) { - // .priority is OK - } - else if (!isValidKey(keys[j])) { - throw new Error(errorPrefix + - 'contains an invalid key (' + - keys[j] + - ') in path ' + - curPath.toString() + - '. Keys must be non-empty strings ' + - 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); - } - } - } - // Check that update keys are not descendants of each other. - // We rely on the property that sorting guarantees that ancestors come - // right before descendants. - mergePaths.sort(Path.comparePaths); - var prevPath = null; - for (i = 0; i < mergePaths.length; i++) { - curPath = mergePaths[i]; - if (prevPath !== null && prevPath.contains(curPath)) { - throw new Error(errorPrefix + - 'contains a path ' + - prevPath.toString() + - ' that is ancestor of another path ' + - curPath.toString()); - } - prevPath = curPath; - } -}; -/** - * pre-validate an object passed as an argument to firebase function ( - * must be an object - e.g. for firebase.update()). - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -var validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) { - if (optional && data === undefined) - return; - var errorPrefix = util.errorPrefix(fnName, argumentNumber, optional); - if (!(data && typeof data === 'object') || Array.isArray(data)) { - throw new Error(errorPrefix + ' must be an object containing the children to replace.'); - } - var mergePaths = []; - util.forEach(data, function (key, value) { - var curPath = new Path(key); - validateFirebaseData(errorPrefix, value, path.child(curPath)); - if (curPath.getBack() === '.priority') { - if (!isValidPriority(value)) { - throw new Error(errorPrefix + - "contains an invalid value for '" + - curPath.toString() + - "', which must be a valid " + - 'Firebase priority (a string, finite number, server value, or null).'); - } - } - mergePaths.push(curPath); - }); - validateFirebaseMergePaths(errorPrefix, mergePaths); -}; -var validatePriority = function (fnName, argumentNumber, priority, optional) { - if (optional && priority === undefined) - return; - if (isInvalidJSONNumber(priority)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'is ' + - priority.toString() + - ', but must be a valid Firebase priority (a string, finite number, ' + - 'server value, or null).'); - // Special case to allow importing data with a .sv. - if (!isValidPriority(priority)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid Firebase priority ' + - '(a string, finite number, server value, or null).'); -}; -var validateEventType = function (fnName, argumentNumber, eventType, optional) { - if (optional && eventType === undefined) - return; - switch (eventType) { - case 'value': - case 'child_added': - case 'child_removed': - case 'child_changed': - case 'child_moved': - break; - default: - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid event type = "value", "child_added", "child_removed", ' + - '"child_changed", or "child_moved".'); - } -}; -var validateKey = function (fnName, argumentNumber, key, optional) { - if (optional && key === undefined) - return; - if (!isValidKey(key)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'was an invalid key = "' + - key + - '". Firebase keys must be non-empty strings and ' + - 'can\'t contain ".", "#", "$", "/", "[", or "]").'); -}; -var validatePathString = function (fnName, argumentNumber, pathString, optional) { - if (optional && pathString === undefined) - return; - if (!isValidPathString(pathString)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'was an invalid path = "' + - pathString + - '". Paths must be non-empty strings and ' + - 'can\'t contain ".", "#", "$", "[", or "]"'); -}; -var validateRootPathString = function (fnName, argumentNumber, pathString, optional) { - if (pathString) { - // Allow '/.info/' at the beginning. - pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); - } - validatePathString(fnName, argumentNumber, pathString, optional); -}; -var validateWritablePath = function (fnName, path) { - if (path.getFront() === '.info') { - throw new Error(fnName + " failed = Can't modify data under /.info/"); - } -}; -var validateUrl = function (fnName, argumentNumber, parsedUrl) { - // TODO = Validate server better. - var pathString = parsedUrl.path.toString(); - if (!(typeof parsedUrl.repoInfo.host === 'string') || - parsedUrl.repoInfo.host.length === 0 || - (!isValidKey(parsedUrl.repoInfo.namespace) && - parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || - (pathString.length !== 0 && !isValidRootPathString(pathString))) { - throw new Error(util.errorPrefix(fnName, argumentNumber, false) + - 'must be a valid firebase URL and ' + - 'the path can\'t contain ".", "#", "$", "[", or "]".'); - } -}; -var validateBoolean = function (fnName, argumentNumber, bool, optional) { - if (optional && bool === undefined) - return; - if (typeof bool !== 'boolean') - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.'); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - */ -var OnDisconnect = /** @class */ (function () { - /** - * @param {!Repo} repo_ - * @param {!Path} path_ - */ - function OnDisconnect(repo_, path_) { - this.repo_ = repo_; - this.path_ = path_; - } - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.cancel = function (onComplete) { - util.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); - util.validateCallback('OnDisconnect.cancel', 1, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.remove = function (onComplete) { - util.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); - validateWritablePath('OnDisconnect.remove', this.path_); - util.validateCallback('OnDisconnect.remove', 1, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} value - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.set = function (value, onComplete) { - util.validateArgCount('OnDisconnect.set', 1, 2, arguments.length); - validateWritablePath('OnDisconnect.set', this.path_); - validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false); - util.validateCallback('OnDisconnect.set', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} value - * @param {number|string|null} priority - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) { - util.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); - validateWritablePath('OnDisconnect.setWithPriority', this.path_); - validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false); - validatePriority('OnDisconnect.setWithPriority', 2, priority, false); - util.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.update = function (objectToMerge, onComplete) { - util.validateArgCount('OnDisconnect.update', 1, 2, arguments.length); - validateWritablePath('OnDisconnect.update', this.path_); - if (Array.isArray(objectToMerge)) { - var newObjectToMerge = {}; - for (var i = 0; i < objectToMerge.length; ++i) { - newObjectToMerge['' + i] = objectToMerge[i]; - } - objectToMerge = newObjectToMerge; - warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + - 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); - } - validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false); - util.validateCallback('OnDisconnect.update', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - return OnDisconnect; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var TransactionResult = /** @class */ (function () { - /** - * A type for the resolve value of Firebase.transaction. - * @constructor - * @dict - * @param {boolean} committed - * @param {DataSnapshot} snapshot - */ - function TransactionResult(committed, snapshot) { - this.committed = committed; - this.snapshot = snapshot; - } - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users - TransactionResult.prototype.toJSON = function () { - util.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); - return { committed: this.committed, snapshot: this.snapshot.toJSON() }; - }; - return TransactionResult; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Fancy ID generator that creates 20-character string identifiers with the - * following properties: - * - * 1. They're based on timestamp so that they sort *after* any existing ids. - * 2. They contain 72-bits of random data after the timestamp so that IDs won't - * collide with other clients' IDs. - * 3. They sort *lexicographically* (so the timestamp is converted to characters - * that will sort properly). - * 4. They're monotonically increasing. Even if you generate more than one in - * the same timestamp, the latter ones will sort after the former ones. We do - * this by using the previous random bits but "incrementing" them by 1 (only - * in the case of a timestamp collision). - */ -var nextPushId = (function () { - // Modeled after base64 web-safe chars, but ordered by ASCII. - var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; - // Timestamp of last push, used to prevent local collisions if you push twice - // in one ms. - var lastPushTime = 0; - // We generate 72-bits of randomness which get turned into 12 characters and - // appended to the timestamp to prevent collisions with other clients. We - // store the last characters we generated because in the event of a collision, - // we'll use those same characters except "incremented" by one. - var lastRandChars = []; - return function (now) { - var duplicateTime = now === lastPushTime; - lastPushTime = now; - var i; - var timeStampChars = new Array(8); - for (i = 7; i >= 0; i--) { - timeStampChars[i] = PUSH_CHARS.charAt(now % 64); - // NOTE: Can't use << here because javascript will convert to int and lose - // the upper bits. - now = Math.floor(now / 64); - } - util.assert(now === 0, 'Cannot push at time == 0'); - var id = timeStampChars.join(''); - if (!duplicateTime) { - for (i = 0; i < 12; i++) { - lastRandChars[i] = Math.floor(Math.random() * 64); - } - } - else { - // If the timestamp hasn't changed since last push, use the same random - // number, except incremented by 1. - for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { - lastRandChars[i] = 0; - } - lastRandChars[i]++; - } - for (i = 0; i < 12; i++) { - id += PUSH_CHARS.charAt(lastRandChars[i]); - } - util.assert(id.length === 20, 'nextPushId: Length should be 20.'); - return id; - }; -})(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @param {!string} name - * @param {!Node} node - * @constructor - * @struct - */ -var NamedNode = /** @class */ (function () { - function NamedNode(name, node) { - this.name = name; - this.node = node; - } - /** - * - * @param {!string} name - * @param {!Node} node - * @return {NamedNode} - */ - NamedNode.Wrap = function (name, node) { - return new NamedNode(name, node); - }; - return NamedNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @constructor - */ -var Index = /** @class */ (function () { - function Index() { - } - /** - * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for - * this index - */ - Index.prototype.getCompare = function () { - return this.compare.bind(this); - }; - /** - * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, - * it's possible that the changes are isolated to parts of the snapshot that are not indexed. - * - * @param {!Node} oldNode - * @param {!Node} newNode - * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode - */ - Index.prototype.indexedValueChanged = function (oldNode, newNode) { - var oldWrapped = new NamedNode(MIN_NAME, oldNode); - var newWrapped = new NamedNode(MIN_NAME, newNode); - return this.compare(oldWrapped, newWrapped) !== 0; - }; - /** - * @return {!NamedNode} a node wrapper that will sort equal to or less than - * any other node wrapper, using this index - */ - Index.prototype.minPost = function () { - return NamedNode.MIN; - }; - return Index; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __EMPTY_NODE; -var KeyIndex = /** @class */ (function (_super) { - tslib_1.__extends(KeyIndex, _super); - function KeyIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(KeyIndex, "__EMPTY_NODE", { - get: function () { - return __EMPTY_NODE; - }, - set: function (val) { - __EMPTY_NODE = val; - }, - enumerable: true, - configurable: true - }); - /** - * @inheritDoc - */ - KeyIndex.prototype.compare = function (a, b) { - return nameCompare(a.name, b.name); - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.isDefinedOn = function (node) { - // We could probably return true here (since every node has a key), but it's never called - // so just leaving unimplemented for now. - throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.'); - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return false; // The key for a node never changes. - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.maxPost = function () { - // TODO: This should really be created once and cached in a static property, but - // NamedNode isn't defined yet, so I can't use it in a static. Bleh. - return new NamedNode(MAX_NAME, __EMPTY_NODE); - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - KeyIndex.prototype.makePost = function (indexValue, name) { - util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); - // We just use empty node, but it'll never be compared, since our comparator only looks at name. - return new NamedNode(indexValue, __EMPTY_NODE); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - KeyIndex.prototype.toString = function () { - return '.key'; - }; - return KeyIndex; -}(Index)); -var KEY_INDEX = new KeyIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MAX_NODE; -function setMaxNode(val) { - MAX_NODE = val; -} -/** - * @param {(!string|!number)} priority - * @return {!string} - */ -var priorityHashText = function (priority) { - if (typeof priority === 'number') - return 'number:' + doubleToIEEE754String(priority); - else - return 'string:' + priority; -}; -/** - * Validates that a priority snapshot Node is valid. - * - * @param {!Node} priorityNode - */ -var validatePriorityNode = function (priorityNode) { - if (priorityNode.isLeafNode()) { - var val = priorityNode.val(); - util.assert(typeof val === 'string' || - typeof val === 'number' || - (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.'); - } - else { - util.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.'); - } - // Don't call getPriority() on MAX_NODE to avoid hitting assertion. - util.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __childrenNodeConstructor; -/** - * LeafNode is a class for storing leaf nodes in a DataSnapshot. It - * implements Node and stores the value of the node (a string, - * number, or boolean) accessible via getValue(). - */ -var LeafNode = /** @class */ (function () { - /** - * @implements {Node} - * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node. - * The object type is possible in the event of a deferred value - * @param {!Node=} priorityNode_ The priority of this node. - */ - function LeafNode(value_, priorityNode_) { - if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; } - this.value_ = value_; - this.priorityNode_ = priorityNode_; - this.lazyHash_ = null; - util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); - validatePriorityNode(this.priorityNode_); - } - Object.defineProperty(LeafNode, "__childrenNodeConstructor", { - get: function () { - return __childrenNodeConstructor; - }, - set: function (val) { - __childrenNodeConstructor = val; - }, - enumerable: true, - configurable: true - }); - /** @inheritDoc */ - LeafNode.prototype.isLeafNode = function () { - return true; - }; - /** @inheritDoc */ - LeafNode.prototype.getPriority = function () { - return this.priorityNode_; - }; - /** @inheritDoc */ - LeafNode.prototype.updatePriority = function (newPriorityNode) { - return new LeafNode(this.value_, newPriorityNode); - }; - /** @inheritDoc */ - LeafNode.prototype.getImmediateChild = function (childName) { - // Hack to treat priority as a regular child - if (childName === '.priority') { - return this.priorityNode_; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE; - } - }; - /** @inheritDoc */ - LeafNode.prototype.getChild = function (path) { - if (path.isEmpty()) { - return this; - } - else if (path.getFront() === '.priority') { - return this.priorityNode_; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE; - } - }; - /** - * @inheritDoc - */ - LeafNode.prototype.hasChild = function () { - return false; - }; - /** @inheritDoc */ - LeafNode.prototype.getPredecessorChildName = function (childName, childNode) { - return null; - }; - /** @inheritDoc */ - LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) { - if (childName === '.priority') { - return this.updatePriority(newChildNode); - } - else if (newChildNode.isEmpty() && childName !== '.priority') { - return this; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); - } - }; - /** @inheritDoc */ - LeafNode.prototype.updateChild = function (path, newChildNode) { - var front = path.getFront(); - if (front === null) { - return newChildNode; - } - else if (newChildNode.isEmpty() && front !== '.priority') { - return this; - } - else { - util.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path'); - return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode)); - } - }; - /** @inheritDoc */ - LeafNode.prototype.isEmpty = function () { - return false; - }; - /** @inheritDoc */ - LeafNode.prototype.numChildren = function () { - return 0; - }; - /** @inheritDoc */ - LeafNode.prototype.forEachChild = function (index, action) { - return false; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.val = function (exportFormat) { - if (exportFormat && !this.getPriority().isEmpty()) - return { - '.value': this.getValue(), - '.priority': this.getPriority().val() - }; - else - return this.getValue(); - }; - /** @inheritDoc */ - LeafNode.prototype.hash = function () { - if (this.lazyHash_ === null) { - var toHash = ''; - if (!this.priorityNode_.isEmpty()) - toHash += - 'priority:' + - priorityHashText(this.priorityNode_.val()) + - ':'; - var type = typeof this.value_; - toHash += type + ':'; - if (type === 'number') { - toHash += doubleToIEEE754String(this.value_); - } - else { - toHash += this.value_; - } - this.lazyHash_ = sha1(toHash); - } - return this.lazyHash_; - }; - /** - * Returns the value of the leaf node. - * @return {Object|string|number|boolean} The value of the node. - */ - LeafNode.prototype.getValue = function () { - return this.value_; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.compareTo = function (other) { - if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { - return 1; - } - else if (other instanceof LeafNode.__childrenNodeConstructor) { - return -1; - } - else { - util.assert(other.isLeafNode(), 'Unknown node type'); - return this.compareToLeafNode_(other); - } - }; - /** - * Comparison specifically for two leaf nodes - * @param {!LeafNode} otherLeaf - * @return {!number} - * @private - */ - LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) { - var otherLeafType = typeof otherLeaf.value_; - var thisLeafType = typeof this.value_; - var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); - var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); - util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); - util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); - if (otherIndex === thisIndex) { - // Same type, compare values - if (thisLeafType === 'object') { - // Deferred value nodes are all equal, but we should also never get to this point... - return 0; - } - else { - // Note that this works because true > false, all others are number or string comparisons - if (this.value_ < otherLeaf.value_) { - return -1; - } - else if (this.value_ === otherLeaf.value_) { - return 0; - } - else { - return 1; - } - } - } - else { - return thisIndex - otherIndex; - } - }; - /** - * @inheritDoc - */ - LeafNode.prototype.withIndex = function () { - return this; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.isIndexed = function () { - return true; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.equals = function (other) { - /** - * @inheritDoc - */ - if (other === this) { - return true; - } - else if (other.isLeafNode()) { - var otherLeaf = other; - return (this.value_ === otherLeaf.value_ && - this.priorityNode_.equals(otherLeaf.priorityNode_)); - } - else { - return false; - } - }; - /** - * The sort order for comparing leaf nodes of different types. If two leaf nodes have - * the same type, the comparison falls back to their value - * @type {Array.} - * @const - */ - LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; - return LeafNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var nodeFromJSON; -var MAX_NODE$1; -function setNodeFromJSON(val) { - nodeFromJSON = val; -} -function setMaxNode$1(val) { - MAX_NODE$1 = val; -} -/** - * @constructor - * @extends {Index} - * @private - */ -var PriorityIndex = /** @class */ (function (_super) { - tslib_1.__extends(PriorityIndex, _super); - function PriorityIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - PriorityIndex.prototype.compare = function (a, b) { - var aPriority = a.node.getPriority(); - var bPriority = b.node.getPriority(); - var indexCmp = aPriority.compareTo(bPriority); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.isDefinedOn = function (node) { - return !node.getPriority().isEmpty(); - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return !oldNode.getPriority().equals(newNode.getPriority()); - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.maxPost = function () { - return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - PriorityIndex.prototype.makePost = function (indexValue, name) { - var priorityNode = nodeFromJSON(indexValue); - return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - PriorityIndex.prototype.toString = function () { - return '.priority'; - }; - return PriorityIndex; -}(Index)); -var PRIORITY_INDEX = new PriorityIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An iterator over an LLRBNode. - */ -var SortedMapIterator = /** @class */ (function () { - /** - * @template K, V, T - * @param {LLRBNode|LLRBEmptyNode} node Node to iterate. - * @param {?K} startKey - * @param {function(K, K): number} comparator - * @param {boolean} isReverse_ Whether or not to iterate in reverse - * @param {(function(K, V):T)=} resultGenerator_ - */ - function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) { - if (resultGenerator_ === void 0) { resultGenerator_ = null; } - this.isReverse_ = isReverse_; - this.resultGenerator_ = resultGenerator_; - /** @private - * @type {Array.} - */ - this.nodeStack_ = []; - var cmp = 1; - while (!node.isEmpty()) { - node = node; - cmp = startKey ? comparator(node.key, startKey) : 1; - // flip the comparison if we're going in reverse - if (isReverse_) - cmp *= -1; - if (cmp < 0) { - // This node is less than our start key. ignore it - if (this.isReverse_) { - node = node.left; - } - else { - node = node.right; - } - } - else if (cmp === 0) { - // This node is exactly equal to our start key. Push it on the stack, but stop iterating; - this.nodeStack_.push(node); - break; - } - else { - // This node is greater than our start key, add it to the stack and move to the next one - this.nodeStack_.push(node); - if (this.isReverse_) { - node = node.right; - } - else { - node = node.left; - } - } - } - } - SortedMapIterator.prototype.getNext = function () { - if (this.nodeStack_.length === 0) - return null; - var node = this.nodeStack_.pop(); - var result; - if (this.resultGenerator_) - result = this.resultGenerator_(node.key, node.value); - else - result = { key: node.key, value: node.value }; - if (this.isReverse_) { - node = node.left; - while (!node.isEmpty()) { - this.nodeStack_.push(node); - node = node.right; - } - } - else { - node = node.right; - while (!node.isEmpty()) { - this.nodeStack_.push(node); - node = node.left; - } - } - return result; - }; - SortedMapIterator.prototype.hasNext = function () { - return this.nodeStack_.length > 0; - }; - SortedMapIterator.prototype.peek = function () { - if (this.nodeStack_.length === 0) - return null; - var node = this.nodeStack_[this.nodeStack_.length - 1]; - if (this.resultGenerator_) { - return this.resultGenerator_(node.key, node.value); - } - else { - return { key: node.key, value: node.value }; - } - }; - return SortedMapIterator; -}()); -/** - * Represents a node in a Left-leaning Red-Black tree. - */ -var LLRBNode = /** @class */ (function () { - /** - * @template K, V - * @param {!K} key Key associated with this node. - * @param {!V} value Value associated with this node. - * @param {?boolean} color Whether this node is red. - * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child. - * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child. - */ - function LLRBNode(key, value, color, left, right) { - this.key = key; - this.value = value; - this.color = color != null ? color : LLRBNode.RED; - this.left = - left != null ? left : SortedMap.EMPTY_NODE; - this.right = - right != null ? right : SortedMap.EMPTY_NODE; - } - /** - * Returns a copy of the current node, optionally replacing pieces of it. - * - * @param {?K} key New key for the node, or null. - * @param {?V} value New value for the node, or null. - * @param {?boolean} color New color for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null. - * @return {!LLRBNode} The node copy. - */ - LLRBNode.prototype.copy = function (key, value, color, left, right) { - return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); - }; - /** - * @return {number} The total number of nodes in the tree. - */ - LLRBNode.prototype.count = function () { - return this.left.count() + 1 + this.right.count(); - }; - /** - * @return {boolean} True if the tree is empty. - */ - LLRBNode.prototype.isEmpty = function () { - return false; - }; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - LLRBNode.prototype.inorderTraversal = function (action) { - return (this.left.inorderTraversal(action) || - action(this.key, this.value) || - this.right.inorderTraversal(action)); - }; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!Object, !Object)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} True if traversal was aborted. - */ - LLRBNode.prototype.reverseTraversal = function (action) { - return (this.right.reverseTraversal(action) || - action(this.key, this.value) || - this.left.reverseTraversal(action)); - }; - /** - * @return {!Object} The minimum node in the tree. - * @private - */ - LLRBNode.prototype.min_ = function () { - if (this.left.isEmpty()) { - return this; - } - else { - return this.left.min_(); - } - }; - /** - * @return {!K} The maximum key in the tree. - */ - LLRBNode.prototype.minKey = function () { - return this.min_().key; - }; - /** - * @return {!K} The maximum key in the tree. - */ - LLRBNode.prototype.maxKey = function () { - if (this.right.isEmpty()) { - return this.key; - } - else { - return this.right.maxKey(); - } - }; - /** - * - * @param {!Object} key Key to insert. - * @param {!Object} value Value to insert. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with the key/value added. - */ - LLRBNode.prototype.insert = function (key, value, comparator) { - var cmp, n; - n = this; - cmp = comparator(key, n.key); - if (cmp < 0) { - n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); - } - else if (cmp === 0) { - n = n.copy(null, value, null, null, null); - } - else { - n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); - } - return n.fixUp_(); - }; - /** - * @private - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed. - */ - LLRBNode.prototype.removeMin_ = function () { - if (this.left.isEmpty()) { - return SortedMap.EMPTY_NODE; - } - var n = this; - if (!n.left.isRed_() && !n.left.left.isRed_()) - n = n.moveRedLeft_(); - n = n.copy(null, null, null, n.left.removeMin_(), null); - return n.fixUp_(); - }; - /** - * @param {!Object} key The key of the item to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed. - */ - LLRBNode.prototype.remove = function (key, comparator) { - var n, smallest; - n = this; - if (comparator(key, n.key) < 0) { - if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { - n = n.moveRedLeft_(); - } - n = n.copy(null, null, null, n.left.remove(key, comparator), null); - } - else { - if (n.left.isRed_()) - n = n.rotateRight_(); - if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { - n = n.moveRedRight_(); - } - if (comparator(key, n.key) === 0) { - if (n.right.isEmpty()) { - return SortedMap.EMPTY_NODE; - } - else { - smallest = n.right.min_(); - n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); - } - } - n = n.copy(null, null, null, null, n.right.remove(key, comparator)); - } - return n.fixUp_(); - }; - /** - * @private - * @return {boolean} Whether this is a RED node. - */ - LLRBNode.prototype.isRed_ = function () { - return this.color; - }; - /** - * @private - * @return {!LLRBNode} New tree after performing any needed rotations. - */ - LLRBNode.prototype.fixUp_ = function () { - var n = this; - if (n.right.isRed_() && !n.left.isRed_()) - n = n.rotateLeft_(); - if (n.left.isRed_() && n.left.left.isRed_()) - n = n.rotateRight_(); - if (n.left.isRed_() && n.right.isRed_()) - n = n.colorFlip_(); - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after moveRedLeft. - */ - LLRBNode.prototype.moveRedLeft_ = function () { - var n = this.colorFlip_(); - if (n.right.left.isRed_()) { - n = n.copy(null, null, null, null, n.right.rotateRight_()); - n = n.rotateLeft_(); - n = n.colorFlip_(); - } - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after moveRedRight. - */ - LLRBNode.prototype.moveRedRight_ = function () { - var n = this.colorFlip_(); - if (n.left.left.isRed_()) { - n = n.rotateRight_(); - n = n.colorFlip_(); - } - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after rotateLeft. - */ - LLRBNode.prototype.rotateLeft_ = function () { - var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); - return this.right.copy(null, null, this.color, nl, null); - }; - /** - * @private - * @return {!LLRBNode} New tree, after rotateRight. - */ - LLRBNode.prototype.rotateRight_ = function () { - var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); - return this.left.copy(null, null, this.color, null, nr); - }; - /** - * @private - * @return {!LLRBNode} New tree, after colorFlip. - */ - LLRBNode.prototype.colorFlip_ = function () { - var left = this.left.copy(null, null, !this.left.color, null, null); - var right = this.right.copy(null, null, !this.right.color, null, null); - return this.copy(null, null, !this.color, left, right); - }; - /** - * For testing. - * - * @private - * @return {boolean} True if all is well. - */ - LLRBNode.prototype.checkMaxDepth_ = function () { - var blackDepth = this.check_(); - return Math.pow(2.0, blackDepth) <= this.count() + 1; - }; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - LLRBNode.prototype.check_ = function () { - var blackDepth; - if (this.isRed_() && this.left.isRed_()) { - throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); - } - if (this.right.isRed_()) { - throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); - } - blackDepth = this.left.check_(); - if (blackDepth !== this.right.check_()) { - throw new Error('Black depths differ'); - } - else { - return blackDepth + (this.isRed_() ? 0 : 1); - } - }; - LLRBNode.RED = true; - LLRBNode.BLACK = false; - return LLRBNode; -}()); -/** - * Represents an empty node (a leaf node in the Red-Black Tree). - */ -var LLRBEmptyNode = /** @class */ (function () { - function LLRBEmptyNode() { - } - /** - * Returns a copy of the current node. - * - * @return {!LLRBEmptyNode} The node copy. - */ - LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) { - return this; - }; - /** - * Returns a copy of the tree, with the specified key/value added. - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with item added. - */ - LLRBEmptyNode.prototype.insert = function (key, value, comparator) { - return new LLRBNode(key, value, null); - }; - /** - * Returns a copy of the tree, with the specified key removed. - * - * @param {!K} key The key to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBEmptyNode} New tree, with item removed. - */ - LLRBEmptyNode.prototype.remove = function (key, comparator) { - return this; - }; - /** - * @return {number} The total number of nodes in the tree. - */ - LLRBEmptyNode.prototype.count = function () { - return 0; - }; - /** - * @return {boolean} True if the tree is empty. - */ - LLRBEmptyNode.prototype.isEmpty = function () { - return true; - }; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - LLRBEmptyNode.prototype.inorderTraversal = function (action) { - return false; - }; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - LLRBEmptyNode.prototype.reverseTraversal = function (action) { - return false; - }; - /** - * @return {null} - */ - LLRBEmptyNode.prototype.minKey = function () { - return null; - }; - /** - * @return {null} - */ - LLRBEmptyNode.prototype.maxKey = function () { - return null; - }; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - LLRBEmptyNode.prototype.check_ = function () { - return 0; - }; - /** - * @private - * @return {boolean} Whether this node is red. - */ - LLRBEmptyNode.prototype.isRed_ = function () { - return false; - }; - return LLRBEmptyNode; -}()); -/** - * An immutable sorted map implementation, based on a Left-leaning Red-Black - * tree. - */ -var SortedMap = /** @class */ (function () { - /** - * @template K, V - * @param {function(K, K):number} comparator_ Key comparator. - * @param {LLRBNode=} root_ (Optional) Root node for the map. - */ - function SortedMap(comparator_, root_) { - if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; } - this.comparator_ = comparator_; - this.root_ = root_; - } - /** - * Returns a copy of the map, with the specified key/value added or replaced. - * (TODO: We should perhaps rename this method to 'put') - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @return {!SortedMap.} New map, with item added. - */ - SortedMap.prototype.insert = function (key, value) { - return new SortedMap(this.comparator_, this.root_ - .insert(key, value, this.comparator_) - .copy(null, null, LLRBNode.BLACK, null, null)); - }; - /** - * Returns a copy of the map, with the specified key removed. - * - * @param {!K} key The key to remove. - * @return {!SortedMap.} New map, with item removed. - */ - SortedMap.prototype.remove = function (key) { - return new SortedMap(this.comparator_, this.root_ - .remove(key, this.comparator_) - .copy(null, null, LLRBNode.BLACK, null, null)); - }; - /** - * Returns the value of the node with the given key, or null. - * - * @param {!K} key The key to look up. - * @return {?V} The value of the node with the given key, or null if the - * key doesn't exist. - */ - SortedMap.prototype.get = function (key) { - var cmp; - var node = this.root_; - while (!node.isEmpty()) { - cmp = this.comparator_(key, node.key); - if (cmp === 0) { - return node.value; - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - node = node.right; - } - } - return null; - }; - /** - * Returns the key of the item *before* the specified key, or null if key is the first item. - * @param {K} key The key to find the predecessor of - * @return {?K} The predecessor key. - */ - SortedMap.prototype.getPredecessorKey = function (key) { - var cmp, node = this.root_, rightParent = null; - while (!node.isEmpty()) { - cmp = this.comparator_(key, node.key); - if (cmp === 0) { - if (!node.left.isEmpty()) { - node = node.left; - while (!node.right.isEmpty()) - node = node.right; - return node.key; - } - else if (rightParent) { - return rightParent.key; - } - else { - return null; // first item. - } - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - rightParent = node; - node = node.right; - } - } - throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); - }; - /** - * @return {boolean} True if the map is empty. - */ - SortedMap.prototype.isEmpty = function () { - return this.root_.isEmpty(); - }; - /** - * @return {number} The total number of nodes in the map. - */ - SortedMap.prototype.count = function () { - return this.root_.count(); - }; - /** - * @return {?K} The minimum key in the map. - */ - SortedMap.prototype.minKey = function () { - return this.root_.minKey(); - }; - /** - * @return {?K} The maximum key in the map. - */ - SortedMap.prototype.maxKey = function () { - return this.root_.maxKey(); - }; - /** - * Traverses the map in key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!K, !V):*} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - SortedMap.prototype.inorderTraversal = function (action) { - return this.root_.inorderTraversal(action); - }; - /** - * Traverses the map in reverse key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!Object, !Object)} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} True if the traversal was aborted. - */ - SortedMap.prototype.reverseTraversal = function (action) { - return this.root_.reverseTraversal(action); - }; - /** - * Returns an iterator over the SortedMap. - * @template T - * @param {(function(K, V):T)=} resultGenerator - * @return {SortedMapIterator.} The iterator. - */ - SortedMap.prototype.getIterator = function (resultGenerator) { - return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); - }; - SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) { - return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); - }; - SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) { - return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); - }; - SortedMap.prototype.getReverseIterator = function (resultGenerator) { - return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); - }; - /** - * Always use the same empty node, to reduce memory. - * @const - */ - SortedMap.EMPTY_NODE = new LLRBEmptyNode(); - return SortedMap; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var LOG_2 = Math.log(2); -/** - * @constructor - */ -var Base12Num = /** @class */ (function () { - /** - * @param {number} length - */ - function Base12Num(length) { - var logBase2 = function (num) { - return parseInt((Math.log(num) / LOG_2), 10); - }; - var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); }; - this.count = logBase2(length + 1); - this.current_ = this.count - 1; - var mask = bitMask(this.count); - this.bits_ = (length + 1) & mask; - } - /** - * @return {boolean} - */ - Base12Num.prototype.nextBitIsOne = function () { - //noinspection JSBitwiseOperatorUsage - var result = !(this.bits_ & (0x1 << this.current_)); - this.current_--; - return result; - }; - return Base12Num; -}()); -/** - * Takes a list of child nodes and constructs a SortedSet using the given comparison - * function - * - * Uses the algorithm described in the paper linked here: - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 - * - * @template K, V - * @param {Array.} childList Unsorted list of children - * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used - * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's - * type is not NamedNode - * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map - * @return {SortedMap.} - */ -var buildChildSet = function (childList, cmp, keyFn, mapSortFn) { - childList.sort(cmp); - var buildBalancedTree = function (low, high) { - var length = high - low; - var namedNode; - var key; - if (length == 0) { - return null; - } - else if (length == 1) { - namedNode = childList[low]; - key = keyFn ? keyFn(namedNode) : namedNode; - return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); - } - else { - var middle = parseInt((length / 2), 10) + low; - var left = buildBalancedTree(low, middle); - var right = buildBalancedTree(middle + 1, high); - namedNode = childList[middle]; - key = keyFn ? keyFn(namedNode) : namedNode; - return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); - } - }; - var buildFrom12Array = function (base12) { - var node = null; - var root = null; - var index = childList.length; - var buildPennant = function (chunkSize, color) { - var low = index - chunkSize; - var high = index; - index -= chunkSize; - var childTree = buildBalancedTree(low + 1, high); - var namedNode = childList[low]; - var key = keyFn ? keyFn(namedNode) : namedNode; - attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); - }; - var attachPennant = function (pennant) { - if (node) { - node.left = pennant; - node = pennant; - } - else { - root = pennant; - node = pennant; - } - }; - for (var i = 0; i < base12.count; ++i) { - var isOne = base12.nextBitIsOne(); - // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) - var chunkSize = Math.pow(2, base12.count - (i + 1)); - if (isOne) { - buildPennant(chunkSize, LLRBNode.BLACK); - } - else { - // current == 2 - buildPennant(chunkSize, LLRBNode.BLACK); - buildPennant(chunkSize, LLRBNode.RED); - } - } - return root; - }; - var base12 = new Base12Num(childList.length); - var root = buildFrom12Array(base12); - return new SortedMap(mapSortFn || cmp, root); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var _defaultIndexMap; -var fallbackObject = {}; -/** - * - * @param {Object.>} indexes - * @param {Object.} indexSet - * @constructor - */ -var IndexMap = /** @class */ (function () { - function IndexMap(indexes_, indexSet_) { - this.indexes_ = indexes_; - this.indexSet_ = indexSet_; - } - Object.defineProperty(IndexMap, "Default", { - /** - * The default IndexMap for nodes without a priority - * @type {!IndexMap} - * @const - */ - get: function () { - util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); - _defaultIndexMap = - _defaultIndexMap || - new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); - return _defaultIndexMap; - }, - enumerable: true, - configurable: true - }); - /** - * - * @param {!string} indexKey - * @return {?SortedMap.} - */ - IndexMap.prototype.get = function (indexKey) { - var sortedMap = util.safeGet(this.indexes_, indexKey); - if (!sortedMap) - throw new Error('No index defined for ' + indexKey); - if (sortedMap === fallbackObject) { - // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the - // regular child map - return null; - } - else { - return sortedMap; - } - }; - /** - * @param {!Index} indexDefinition - * @return {boolean} - */ - IndexMap.prototype.hasIndex = function (indexDefinition) { - return util.contains(this.indexSet_, indexDefinition.toString()); - }; - /** - * @param {!Index} indexDefinition - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) { - util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); - var childList = []; - var sawIndexedValue = false; - var iter = existingChildren.getIterator(NamedNode.Wrap); - var next = iter.getNext(); - while (next) { - sawIndexedValue = - sawIndexedValue || indexDefinition.isDefinedOn(next.node); - childList.push(next); - next = iter.getNext(); - } - var newIndex; - if (sawIndexedValue) { - newIndex = buildChildSet(childList, indexDefinition.getCompare()); - } - else { - newIndex = fallbackObject; - } - var indexName = indexDefinition.toString(); - var newIndexSet = util.clone(this.indexSet_); - newIndexSet[indexName] = indexDefinition; - var newIndexes = util.clone(this.indexes_); - newIndexes[indexName] = newIndex; - return new IndexMap(newIndexes, newIndexSet); - }; - /** - * Ensure that this node is properly tracked in any indexes that we're maintaining - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) { - var _this = this; - var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) { - var index = util.safeGet(_this.indexSet_, indexName); - util.assert(index, 'Missing index implementation for ' + indexName); - if (indexedChildren === fallbackObject) { - // Check to see if we need to index everything - if (index.isDefinedOn(namedNode.node)) { - // We need to build this index - var childList = []; - var iter = existingChildren.getIterator(NamedNode.Wrap); - var next = iter.getNext(); - while (next) { - if (next.name != namedNode.name) { - childList.push(next); - } - next = iter.getNext(); - } - childList.push(namedNode); - return buildChildSet(childList, index.getCompare()); - } - else { - // No change, this remains a fallback - return fallbackObject; - } - } - else { - var existingSnap = existingChildren.get(namedNode.name); - var newChildren = indexedChildren; - if (existingSnap) { - newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); - } - return newChildren.insert(namedNode, namedNode.node); - } - }); - return new IndexMap(newIndexes, this.indexSet_); - }; - /** - * Create a new IndexMap instance with the given value removed - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) { - var newIndexes = util.map(this.indexes_, function (indexedChildren) { - if (indexedChildren === fallbackObject) { - // This is the fallback. Just return it, nothing to do in this case - return indexedChildren; - } - else { - var existingSnap = existingChildren.get(namedNode.name); - if (existingSnap) { - return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); - } - else { - // No record of this child - return indexedChildren; - } - } - }); - return new IndexMap(newIndexes, this.indexSet_); - }; - return IndexMap; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function NAME_ONLY_COMPARATOR(left, right) { - return nameCompare(left.name, right.name); -} -function NAME_COMPARATOR(left, right) { - return nameCompare(left, right); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// TODO: For memory savings, don't store priorityNode_ if it's empty. -var EMPTY_NODE; -/** - * ChildrenNode is a class for storing internal nodes in a DataSnapshot - * (i.e. nodes with children). It implements Node and stores the - * list of children in the children property, sorted by child name. - * - * @constructor - * @implements {Node} - */ -var ChildrenNode = /** @class */ (function () { - /** - * - * @param {!SortedMap.} children_ List of children - * of this node.. - * @param {?Node} priorityNode_ The priority of this node (as a snapshot node). - * @param {!IndexMap} indexMap_ - */ - function ChildrenNode(children_, priorityNode_, indexMap_) { - this.children_ = children_; - this.priorityNode_ = priorityNode_; - this.indexMap_ = indexMap_; - this.lazyHash_ = null; - /** - * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use - * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own - * class instead of an empty ChildrenNode. - */ - if (this.priorityNode_) { - validatePriorityNode(this.priorityNode_); - } - if (this.children_.isEmpty()) { - util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); - } - } - Object.defineProperty(ChildrenNode, "EMPTY_NODE", { - get: function () { - return (EMPTY_NODE || - (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); - }, - enumerable: true, - configurable: true - }); - /** @inheritDoc */ - ChildrenNode.prototype.isLeafNode = function () { - return false; - }; - /** @inheritDoc */ - ChildrenNode.prototype.getPriority = function () { - return this.priorityNode_ || EMPTY_NODE; - }; - /** @inheritDoc */ - ChildrenNode.prototype.updatePriority = function (newPriorityNode) { - if (this.children_.isEmpty()) { - // Don't allow priorities on empty nodes - return this; - } - else { - return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.getImmediateChild = function (childName) { - // Hack to treat priority as a regular child - if (childName === '.priority') { - return this.getPriority(); - } - else { - var child = this.children_.get(childName); - return child === null ? EMPTY_NODE : child; - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.getChild = function (path) { - var front = path.getFront(); - if (front === null) - return this; - return this.getImmediateChild(front).getChild(path.popFront()); - }; - /** @inheritDoc */ - ChildrenNode.prototype.hasChild = function (childName) { - return this.children_.get(childName) !== null; - }; - /** @inheritDoc */ - ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) { - util.assert(newChildNode, 'We should always be passing snapshot nodes'); - if (childName === '.priority') { - return this.updatePriority(newChildNode); - } - else { - var namedNode = new NamedNode(childName, newChildNode); - var newChildren = void 0, newIndexMap = void 0, newPriority = void 0; - if (newChildNode.isEmpty()) { - newChildren = this.children_.remove(childName); - newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); - } - else { - newChildren = this.children_.insert(childName, newChildNode); - newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); - } - newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_; - return new ChildrenNode(newChildren, newPriority, newIndexMap); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.updateChild = function (path, newChildNode) { - var front = path.getFront(); - if (front === null) { - return newChildNode; - } - else { - util.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path'); - var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode); - return this.updateImmediateChild(front, newImmediateChild); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.isEmpty = function () { - return this.children_.isEmpty(); - }; - /** @inheritDoc */ - ChildrenNode.prototype.numChildren = function () { - return this.children_.count(); - }; - /** @inheritDoc */ - ChildrenNode.prototype.val = function (exportFormat) { - if (this.isEmpty()) - return null; - var obj = {}; - var numKeys = 0, maxKey = 0, allIntegerKeys = true; - this.forEachChild(PRIORITY_INDEX, function (key, childNode) { - obj[key] = childNode.val(exportFormat); - numKeys++; - if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { - maxKey = Math.max(maxKey, Number(key)); - } - else { - allIntegerKeys = false; - } - }); - if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { - // convert to array. - var array = []; - for (var key in obj) - array[key] = obj[key]; - return array; - } - else { - if (exportFormat && !this.getPriority().isEmpty()) { - obj['.priority'] = this.getPriority().val(); - } - return obj; - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.hash = function () { - if (this.lazyHash_ === null) { - var toHash_1 = ''; - if (!this.getPriority().isEmpty()) - toHash_1 += - 'priority:' + - priorityHashText(this.getPriority().val()) + - ':'; - this.forEachChild(PRIORITY_INDEX, function (key, childNode) { - var childHash = childNode.hash(); - if (childHash !== '') - toHash_1 += ':' + key + ':' + childHash; - }); - this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1); - } - return this.lazyHash_; - }; - /** @inheritDoc */ - ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) { - var idx = this.resolveIndex_(index); - if (idx) { - var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); - return predecessor ? predecessor.name : null; - } - else { - return this.children_.getPredecessorKey(childName); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?string} - */ - ChildrenNode.prototype.getFirstChildName = function (indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - var minKey = idx.minKey(); - return minKey && minKey.name; - } - else { - return this.children_.minKey(); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - ChildrenNode.prototype.getFirstChild = function (indexDefinition) { - var minKey = this.getFirstChildName(indexDefinition); - if (minKey) { - return new NamedNode(minKey, this.children_.get(minKey)); - } - else { - return null; - } - }; - /** - * Given an index, return the key name of the largest value we have, according to that index - * @param {!Index} indexDefinition - * @return {?string} - */ - ChildrenNode.prototype.getLastChildName = function (indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - var maxKey = idx.maxKey(); - return maxKey && maxKey.name; - } - else { - return this.children_.maxKey(); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - ChildrenNode.prototype.getLastChild = function (indexDefinition) { - var maxKey = this.getLastChildName(indexDefinition); - if (maxKey) { - return new NamedNode(maxKey, this.children_.get(maxKey)); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.forEachChild = function (index, action) { - var idx = this.resolveIndex_(index); - if (idx) { - return idx.inorderTraversal(function (wrappedNode) { - return action(wrappedNode.name, wrappedNode.node); - }); - } - else { - return this.children_.inorderTraversal(action); - } - }; - /** - * @param {!Index} indexDefinition - * @return {SortedMapIterator} - */ - ChildrenNode.prototype.getIterator = function (indexDefinition) { - return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); - }; - /** - * - * @param {!NamedNode} startPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - return idx.getIteratorFrom(startPost, function (key) { return key; }); - } - else { - var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); - var next = iterator.peek(); - while (next != null && indexDefinition.compare(next, startPost) < 0) { - iterator.getNext(); - next = iterator.peek(); - } - return iterator; - } - }; - /** - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getReverseIterator = function (indexDefinition) { - return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); - }; - /** - * @param {!NamedNode} endPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - return idx.getReverseIteratorFrom(endPost, function (key) { - return key; - }); - } - else { - var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); - var next = iterator.peek(); - while (next != null && indexDefinition.compare(next, endPost) > 0) { - iterator.getNext(); - next = iterator.peek(); - } - return iterator; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.compareTo = function (other) { - if (this.isEmpty()) { - if (other.isEmpty()) { - return 0; - } - else { - return -1; - } - } - else if (other.isLeafNode() || other.isEmpty()) { - return 1; - } - else if (other === MAX_NODE$2) { - return -1; - } - else { - // Must be another node with children. - return 0; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.withIndex = function (indexDefinition) { - if (indexDefinition === KEY_INDEX || - this.indexMap_.hasIndex(indexDefinition)) { - return this; - } - else { - var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); - return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.isIndexed = function (index) { - return index === KEY_INDEX || this.indexMap_.hasIndex(index); - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.equals = function (other) { - if (other === this) { - return true; - } - else if (other.isLeafNode()) { - return false; - } - else { - var otherChildrenNode = other; - if (!this.getPriority().equals(otherChildrenNode.getPriority())) { - return false; - } - else if (this.children_.count() === otherChildrenNode.children_.count()) { - var thisIter = this.getIterator(PRIORITY_INDEX); - var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); - var thisCurrent = thisIter.getNext(); - var otherCurrent = otherIter.getNext(); - while (thisCurrent && otherCurrent) { - if (thisCurrent.name !== otherCurrent.name || - !thisCurrent.node.equals(otherCurrent.node)) { - return false; - } - thisCurrent = thisIter.getNext(); - otherCurrent = otherIter.getNext(); - } - return thisCurrent === null && otherCurrent === null; - } - else { - return false; - } - } - }; - /** - * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used - * instead. - * - * @private - * @param {!Index} indexDefinition - * @return {?SortedMap.} - */ - ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) { - if (indexDefinition === KEY_INDEX) { - return null; - } - else { - return this.indexMap_.get(indexDefinition.toString()); - } - }; - /** - * @private - * @type {RegExp} - */ - ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; - return ChildrenNode; -}()); -/** - * @constructor - * @extends {ChildrenNode} - * @private - */ -var MaxNode = /** @class */ (function (_super) { - tslib_1.__extends(MaxNode, _super); - function MaxNode() { - return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this; - } - MaxNode.prototype.compareTo = function (other) { - if (other === this) { - return 0; - } - else { - return 1; - } - }; - MaxNode.prototype.equals = function (other) { - // Not that we every compare it, but MAX_NODE is only ever equal to itself - return other === this; - }; - MaxNode.prototype.getPriority = function () { - return this; - }; - MaxNode.prototype.getImmediateChild = function (childName) { - return ChildrenNode.EMPTY_NODE; - }; - MaxNode.prototype.isEmpty = function () { - return false; - }; - return MaxNode; -}(ChildrenNode)); -/** - * Marker that will sort higher than any other snapshot. - * @type {!MAX_NODE} - * @const - */ -var MAX_NODE$2 = new MaxNode(); -Object.defineProperties(NamedNode, { - MIN: { - value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) - }, - MAX: { - value: new NamedNode(MAX_NAME, MAX_NODE$2) - } -}); -/** - * Reference Extensions - */ -KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; -LeafNode.__childrenNodeConstructor = ChildrenNode; -setMaxNode(MAX_NODE$2); -setMaxNode$1(MAX_NODE$2); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var USE_HINZE = true; -/** - * Constructs a snapshot node representing the passed JSON and returns it. - * @param {*} json JSON to create a node for. - * @param {?string|?number=} priority Optional priority to use. This will be ignored if the - * passed JSON contains a .priority property. - * @return {!Node} - */ -function nodeFromJSON$1(json, priority) { - if (priority === void 0) { priority = null; } - if (json === null) { - return ChildrenNode.EMPTY_NODE; - } - if (typeof json === 'object' && '.priority' in json) { - priority = json['.priority']; - } - util.assert(priority === null || - typeof priority === 'string' || - typeof priority === 'number' || - (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); - if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { - json = json['.value']; - } - // Valid leaf nodes include non-objects or server-value wrapper objects - if (typeof json !== 'object' || '.sv' in json) { - var jsonLeaf = json; - return new LeafNode(jsonLeaf, nodeFromJSON$1(priority)); - } - if (!(json instanceof Array) && USE_HINZE) { - var children_1 = []; - var childrenHavePriority_1 = false; - var hinzeJsonObj_1 = json; - util.forEach(hinzeJsonObj_1, function (key, child) { - if (typeof key !== 'string' || key.substring(0, 1) !== '.') { - // Ignore metadata nodes - var childNode = nodeFromJSON$1(hinzeJsonObj_1[key]); - if (!childNode.isEmpty()) { - childrenHavePriority_1 = - childrenHavePriority_1 || !childNode.getPriority().isEmpty(); - children_1.push(new NamedNode(key, childNode)); - } - } - }); - if (children_1.length == 0) { - return ChildrenNode.EMPTY_NODE; - } - var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR); - if (childrenHavePriority_1) { - var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare()); - return new ChildrenNode(childSet, nodeFromJSON$1(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); - } - else { - return new ChildrenNode(childSet, nodeFromJSON$1(priority), IndexMap.Default); - } - } - else { - var node_1 = ChildrenNode.EMPTY_NODE; - var jsonObj_1 = json; - util.forEach(jsonObj_1, function (key, childData) { - if (util.contains(jsonObj_1, key)) { - if (key.substring(0, 1) !== '.') { - // ignore metadata nodes. - var childNode = nodeFromJSON$1(childData); - if (childNode.isLeafNode() || !childNode.isEmpty()) - node_1 = node_1.updateImmediateChild(key, childNode); - } - } - }); - return node_1.updatePriority(nodeFromJSON$1(priority)); - } -} -setNodeFromJSON(nodeFromJSON$1); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @extends {Index} - * @private - */ -var ValueIndex = /** @class */ (function (_super) { - tslib_1.__extends(ValueIndex, _super); - function ValueIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - ValueIndex.prototype.compare = function (a, b) { - var indexCmp = a.node.compareTo(b.node); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.isDefinedOn = function (node) { - return true; - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return !oldNode.equals(newNode); - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.maxPost = function () { - return NamedNode.MAX; - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - ValueIndex.prototype.makePost = function (indexValue, name) { - var valueNode = nodeFromJSON$1(indexValue); - return new NamedNode(name, valueNode); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - ValueIndex.prototype.toString = function () { - return '.value'; - }; - return ValueIndex; -}(Index)); -var VALUE_INDEX = new ValueIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!Path} indexPath - * @constructor - * @extends {Index} - */ -var PathIndex = /** @class */ (function (_super) { - tslib_1.__extends(PathIndex, _super); - function PathIndex(indexPath_) { - var _this = _super.call(this) || this; - _this.indexPath_ = indexPath_; - util.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', "Can't create PathIndex with empty path or .priority key"); - return _this; - } - /** - * @param {!Node} snap - * @return {!Node} - * @protected - */ - PathIndex.prototype.extractChild = function (snap) { - return snap.getChild(this.indexPath_); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.isDefinedOn = function (node) { - return !node.getChild(this.indexPath_).isEmpty(); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.compare = function (a, b) { - var aChild = this.extractChild(a.node); - var bChild = this.extractChild(b.node); - var indexCmp = aChild.compareTo(bChild); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - PathIndex.prototype.makePost = function (indexValue, name) { - var valueNode = nodeFromJSON$1(indexValue); - var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); - return new NamedNode(name, node); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.maxPost = function () { - var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE$2); - return new NamedNode(MAX_NAME, node); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.toString = function () { - return this.indexPath_.slice().join('/'); - }; - return PathIndex; -}(Index)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class representing a firebase data snapshot. It wraps a SnapshotNode and - * surfaces the public methods (val, forEach, etc.) we want to expose. - */ -var DataSnapshot = /** @class */ (function () { - /** - * @param {!Node} node_ A SnapshotNode to wrap. - * @param {!Reference} ref_ The ref of the location this snapshot came from. - * @param {!Index} index_ The iteration order for this snapshot - */ - function DataSnapshot(node_, ref_, index_) { - this.node_ = node_; - this.ref_ = ref_; - this.index_ = index_; - } - /** - * Retrieves the snapshot contents as JSON. Returns null if the snapshot is - * empty. - * - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - DataSnapshot.prototype.val = function () { - util.validateArgCount('DataSnapshot.val', 0, 0, arguments.length); - return this.node_.val(); - }; - /** - * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting - * the entire node contents. - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - DataSnapshot.prototype.exportVal = function () { - util.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); - return this.node_.val(true); - }; - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users - DataSnapshot.prototype.toJSON = function () { - // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content - util.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); - return this.exportVal(); - }; - /** - * Returns whether the snapshot contains a non-null value. - * - * @return {boolean} Whether the snapshot contains a non-null value, or is empty. - */ - DataSnapshot.prototype.exists = function () { - util.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); - return !this.node_.isEmpty(); - }; - /** - * Returns a DataSnapshot of the specified child node's contents. - * - * @param {!string} childPathString Path to a child. - * @return {!DataSnapshot} DataSnapshot for child node. - */ - DataSnapshot.prototype.child = function (childPathString) { - util.validateArgCount('DataSnapshot.child', 0, 1, arguments.length); - // Ensure the childPath is a string (can be a number) - childPathString = String(childPathString); - validatePathString('DataSnapshot.child', 1, childPathString, false); - var childPath = new Path(childPathString); - var childRef = this.ref_.child(childPath); - return new DataSnapshot(this.node_.getChild(childPath), childRef, PRIORITY_INDEX); - }; - /** - * Returns whether the snapshot contains a child at the specified path. - * - * @param {!string} childPathString Path to a child. - * @return {boolean} Whether the child exists. - */ - DataSnapshot.prototype.hasChild = function (childPathString) { - util.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); - validatePathString('DataSnapshot.hasChild', 1, childPathString, false); - var childPath = new Path(childPathString); - return !this.node_.getChild(childPath).isEmpty(); - }; - /** - * Returns the priority of the object, or null if no priority was set. - * - * @return {string|number|null} The priority. - */ - DataSnapshot.prototype.getPriority = function () { - util.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); - // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) - return this.node_.getPriority().val(); - }; - /** - * Iterates through child nodes and calls the specified action for each one. - * - * @param {function(!DataSnapshot)} action Callback function to be called - * for each child. - * @return {boolean} True if forEach was canceled by action returning true for - * one of the child nodes. - */ - DataSnapshot.prototype.forEach = function (action) { - var _this = this; - util.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); - util.validateCallback('DataSnapshot.forEach', 1, action, false); - if (this.node_.isLeafNode()) - return false; - var childrenNode = this.node_; - // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... - return !!childrenNode.forEachChild(this.index_, function (key, node) { - return action(new DataSnapshot(node, _this.ref_.child(key), PRIORITY_INDEX)); - }); - }; - /** - * Returns whether this DataSnapshot has children. - * @return {boolean} True if the DataSnapshot contains 1 or more child nodes. - */ - DataSnapshot.prototype.hasChildren = function () { - util.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); - if (this.node_.isLeafNode()) - return false; - else - return !this.node_.isEmpty(); - }; - Object.defineProperty(DataSnapshot.prototype, "key", { - get: function () { - return this.ref_.getKey(); - }, - enumerable: true, - configurable: true - }); - /** - * Returns the number of children for this DataSnapshot. - * @return {number} The number of children that this DataSnapshot contains. - */ - DataSnapshot.prototype.numChildren = function () { - util.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); - return this.node_.numChildren(); - }; - /** - * @return {Reference} The Firebase reference for the location this snapshot's data came from. - */ - DataSnapshot.prototype.getRef = function () { - util.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); - return this.ref_; - }; - Object.defineProperty(DataSnapshot.prototype, "ref", { - get: function () { - return this.getRef(); - }, - enumerable: true, - configurable: true - }); - return DataSnapshot; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Encapsulates the data needed to raise an event - * @implements {Event} - */ -var DataEvent = /** @class */ (function () { - /** - * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed - * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided - * @param {!DataSnapshot} snapshot The data backing the event - * @param {?string=} prevName Optional, the name of the previous child for child_* events. - */ - function DataEvent(eventType, eventRegistration, snapshot, prevName) { - this.eventType = eventType; - this.eventRegistration = eventRegistration; - this.snapshot = snapshot; - this.prevName = prevName; - } - /** - * @inheritDoc - */ - DataEvent.prototype.getPath = function () { - var ref = this.snapshot.getRef(); - if (this.eventType === 'value') { - return ref.path; - } - else { - return ref.getParent().path; - } - }; - /** - * @inheritDoc - */ - DataEvent.prototype.getEventType = function () { - return this.eventType; - }; - /** - * @inheritDoc - */ - DataEvent.prototype.getEventRunner = function () { - return this.eventRegistration.getEventRunner(this); - }; - /** - * @inheritDoc - */ - DataEvent.prototype.toString = function () { - return (this.getPath().toString() + - ':' + - this.eventType + - ':' + - util.stringify(this.snapshot.exportVal())); - }; - return DataEvent; -}()); -var CancelEvent = /** @class */ (function () { - /** - * @param {EventRegistration} eventRegistration - * @param {Error} error - * @param {!Path} path - */ - function CancelEvent(eventRegistration, error, path) { - this.eventRegistration = eventRegistration; - this.error = error; - this.path = path; - } - /** - * @inheritDoc - */ - CancelEvent.prototype.getPath = function () { - return this.path; - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.getEventType = function () { - return 'cancel'; - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.getEventRunner = function () { - return this.eventRegistration.getEventRunner(this); - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.toString = function () { - return this.path.toString() + ':cancel'; - }; - return CancelEvent; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Represents registration for 'value' events. - */ -var ValueEventRegistration = /** @class */ (function () { - /** - * @param {?function(!DataSnapshot)} callback_ - * @param {?function(Error)} cancelCallback_ - * @param {?Object} context_ - */ - function ValueEventRegistration(callback_, cancelCallback_, context_) { - this.callback_ = callback_; - this.cancelCallback_ = cancelCallback_; - this.context_ = context_; - } - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.respondsTo = function (eventType) { - return eventType === 'value'; - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.createEvent = function (change, query) { - var index = query.getQueryParams().getIndex(); - return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, query.getRef(), index)); - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.getEventRunner = function (eventData) { - var ctx = this.context_; - if (eventData.getEventType() === 'cancel') { - util.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback'); - var cancelCB_1 = this.cancelCallback_; - return function () { - // We know that error exists, we checked above that this is a cancel event - cancelCB_1.call(ctx, eventData.error); - }; - } - else { - var cb_1 = this.callback_; - return function () { - cb_1.call(ctx, eventData.snapshot); - }; - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.createCancelEvent = function (error, path) { - if (this.cancelCallback_) { - return new CancelEvent(this, error, path); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.matches = function (other) { - if (!(other instanceof ValueEventRegistration)) { - return false; - } - else if (!other.callback_ || !this.callback_) { - // If no callback specified, we consider it to match any callback. - return true; - } - else { - return (other.callback_ === this.callback_ && other.context_ === this.context_); - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.hasAnyCallback = function () { - return this.callback_ !== null; - }; - return ValueEventRegistration; -}()); -/** - * Represents the registration of 1 or more child_xxx events. - * - * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you - * register a group of callbacks together in the future. - * - * @constructor - * @implements {EventRegistration} - */ -var ChildEventRegistration = /** @class */ (function () { - /** - * @param {?Object.} callbacks_ - * @param {?function(Error)} cancelCallback_ - * @param {Object=} context_ - */ - function ChildEventRegistration(callbacks_, cancelCallback_, context_) { - this.callbacks_ = callbacks_; - this.cancelCallback_ = cancelCallback_; - this.context_ = context_; - } - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.respondsTo = function (eventType) { - var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; - eventToCheck = - eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; - return util.contains(this.callbacks_, eventToCheck); - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.createCancelEvent = function (error, path) { - if (this.cancelCallback_) { - return new CancelEvent(this, error, path); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.createEvent = function (change, query) { - util.assert(change.childName != null, 'Child events should have a childName.'); - var ref = query.getRef().child(/** @type {!string} */ (change.childName)); - var index = query.getQueryParams().getIndex(); - return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, ref, index), change.prevName); - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.getEventRunner = function (eventData) { - var ctx = this.context_; - if (eventData.getEventType() === 'cancel') { - util.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback'); - var cancelCB_2 = this.cancelCallback_; - return function () { - // We know that error exists, we checked above that this is a cancel event - cancelCB_2.call(ctx, eventData.error); - }; - } - else { - var cb_2 = this.callbacks_[eventData.eventType]; - return function () { - cb_2.call(ctx, eventData.snapshot, eventData.prevName); - }; - } - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.matches = function (other) { - if (other instanceof ChildEventRegistration) { - if (!this.callbacks_ || !other.callbacks_) { - return true; - } - else if (this.context_ === other.context_) { - var otherCount = util.getCount(other.callbacks_); - var thisCount = util.getCount(this.callbacks_); - if (otherCount === thisCount) { - // If count is 1, do an exact match on eventType, if either is defined but null, it's a match. - // If event types don't match, not a match - // If count is not 1, exact match across all - if (otherCount === 1) { - var otherKey /** @type {!string} */ = util.getAnyKey(other.callbacks_); - var thisKey /** @type {!string} */ = util.getAnyKey(this.callbacks_); - return (thisKey === otherKey && - (!other.callbacks_[otherKey] || - !this.callbacks_[thisKey] || - other.callbacks_[otherKey] === this.callbacks_[thisKey])); - } - else { - // Exact match on each key. - return util.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; }); - } - } - } - } - return false; - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.hasAnyCallback = function () { - return this.callbacks_ !== null; - }; - return ChildEventRegistration; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __referenceConstructor; -/** - * A Query represents a filter to be applied to a firebase location. This object purely represents the - * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. - * - * Since every Firebase reference is a query, Firebase inherits from this object. - */ -var Query = /** @class */ (function () { - function Query(repo, path, queryParams_, orderByCalled_) { - this.repo = repo; - this.path = path; - this.queryParams_ = queryParams_; - this.orderByCalled_ = orderByCalled_; - } - Object.defineProperty(Query, "__referenceConstructor", { - get: function () { - util.assert(__referenceConstructor, 'Reference.ts has not been loaded'); - return __referenceConstructor; - }, - set: function (val) { - __referenceConstructor = val; - }, - enumerable: true, - configurable: true - }); - /** - * Validates start/end values for queries. - * @param {!QueryParams} params - * @private - */ - Query.validateQueryEndpoints_ = function (params) { - var startNode = null; - var endNode = null; - if (params.hasStart()) { - startNode = params.getIndexStartValue(); - } - if (params.hasEnd()) { - endNode = params.getIndexEndValue(); - } - if (params.getIndex() === KEY_INDEX) { - var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + - 'startAt(), endAt(), or equalTo().'; - var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' + - 'or equalTo() must be a string.'; - if (params.hasStart()) { - var startName = params.getIndexStartName(); - if (startName != MIN_NAME) { - throw new Error(tooManyArgsError); - } - else if (typeof startNode !== 'string') { - throw new Error(wrongArgTypeError); - } - } - if (params.hasEnd()) { - var endName = params.getIndexEndName(); - if (endName != MAX_NAME) { - throw new Error(tooManyArgsError); - } - else if (typeof endNode !== 'string') { - throw new Error(wrongArgTypeError); - } - } - } - else if (params.getIndex() === PRIORITY_INDEX) { - if ((startNode != null && !isValidPriority(startNode)) || - (endNode != null && !isValidPriority(endNode))) { - throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + - 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).'); - } - } - else { - util.assert(params.getIndex() instanceof PathIndex || - params.getIndex() === VALUE_INDEX, 'unknown index type.'); - if ((startNode != null && typeof startNode === 'object') || - (endNode != null && typeof endNode === 'object')) { - throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' + - 'an object.'); - } - } - }; - /** - * Validates that limit* has been called with the correct combination of parameters - * @param {!QueryParams} params - * @private - */ - Query.validateLimit_ = function (params) { - if (params.hasStart() && - params.hasEnd() && - params.hasLimit() && - !params.hasAnchoredLimit()) { - throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead."); - } - }; - /** - * Validates that no other order by call has been made - * @param {!string} fnName - * @private - */ - Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) { - if (this.orderByCalled_ === true) { - throw new Error(fnName + ": You can't combine multiple orderBy calls."); - } - }; - /** - * @return {!QueryParams} - */ - Query.prototype.getQueryParams = function () { - return this.queryParams_; - }; - /** - * @return {!Reference} - */ - Query.prototype.getRef = function () { - util.validateArgCount('Query.ref', 0, 0, arguments.length); - // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query. - // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this - // method gets called. - return new Query.__referenceConstructor(this.repo, this.path); - }; - /** - * @param {!string} eventType - * @param {!function(DataSnapshot, string=)} callback - * @param {(function(Error)|Object)=} cancelCallbackOrContext - * @param {Object=} context - * @return {!function(DataSnapshot, string=)} - */ - Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) { - util.validateArgCount('Query.on', 2, 4, arguments.length); - validateEventType('Query.on', 1, eventType, false); - util.validateCallback('Query.on', 2, callback, false); - var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); - if (eventType === 'value') { - this.onValueEvent(callback, ret.cancel, ret.context); - } - else { - var callbacks = {}; - callbacks[eventType] = callback; - this.onChildEvent(callbacks, ret.cancel, ret.context); - } - return callback; - }; - /** - * @param {!function(!DataSnapshot)} callback - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - Query.prototype.onValueEvent = function (callback, cancelCallback, context) { - var container = new ValueEventRegistration(callback, cancelCallback || null, context || null); - this.repo.addEventCallbackForQuery(this, container); - }; - /** - * @param {!Object.} callbacks - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) { - var container = new ChildEventRegistration(callbacks, cancelCallback, context); - this.repo.addEventCallbackForQuery(this, container); - }; - /** - * @param {string=} eventType - * @param {(function(!DataSnapshot, ?string=))=} callback - * @param {Object=} context - */ - Query.prototype.off = function (eventType, callback, context) { - util.validateArgCount('Query.off', 0, 3, arguments.length); - validateEventType('Query.off', 1, eventType, true); - util.validateCallback('Query.off', 2, callback, true); - util.validateContextObject('Query.off', 3, context, true); - var container = null; - var callbacks = null; - if (eventType === 'value') { - var valueCallback = callback || null; - container = new ValueEventRegistration(valueCallback, null, context || null); - } - else if (eventType) { - if (callback) { - callbacks = {}; - callbacks[eventType] = callback; - } - container = new ChildEventRegistration(callbacks, null, context || null); - } - this.repo.removeEventCallbackForQuery(this, container); - }; - /** - * Attaches a listener, waits for the first event, and then removes the listener - * @param {!string} eventType - * @param {!function(!DataSnapshot, string=)} userCallback - * @param cancelOrContext - * @param context - * @return {!firebase.Promise} - */ - Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) { - var _this = this; - util.validateArgCount('Query.once', 1, 4, arguments.length); - validateEventType('Query.once', 1, eventType, false); - util.validateCallback('Query.once', 2, userCallback, true); - var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context); - // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event) - // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change - // because the API currently expects callbacks will be called synchronously if the data is cached, but this is - // against the Promise specification. - var firstCall = true; - var deferred = new util.Deferred(); - // A dummy error handler in case a user wasn't expecting promises - deferred.promise.catch(function () { }); - var onceCallback = function (snapshot) { - // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON) - // triggers multiple events (e.g. child_added or child_changed). - if (firstCall) { - firstCall = false; - _this.off(eventType, onceCallback); - if (userCallback) { - userCallback.bind(ret.context)(snapshot); - } - deferred.resolve(snapshot); - } - }; - this.on(eventType, onceCallback, - /*cancel=*/ function (err) { - _this.off(eventType, onceCallback); - if (ret.cancel) - ret.cancel.bind(ret.context)(err); - deferred.reject(err); - }); - return deferred.promise; - }; - /** - * Set a limit and anchor it to the start of the window. - * @param {!number} limit - * @return {!Query} - */ - Query.prototype.limitToFirst = function (limit) { - util.validateArgCount('Query.limitToFirst', 1, 1, arguments.length); - if (typeof limit !== 'number' || - Math.floor(limit) !== limit || - limit <= 0) { - throw new Error('Query.limitToFirst: First argument must be a positive integer.'); - } - if (this.queryParams_.hasLimit()) { - throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' + - 'limitToFirst, or limitToLast).'); - } - return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_); - }; - /** - * Set a limit and anchor it to the end of the window. - * @param {!number} limit - * @return {!Query} - */ - Query.prototype.limitToLast = function (limit) { - util.validateArgCount('Query.limitToLast', 1, 1, arguments.length); - if (typeof limit !== 'number' || - Math.floor(limit) !== limit || - limit <= 0) { - throw new Error('Query.limitToLast: First argument must be a positive integer.'); - } - if (this.queryParams_.hasLimit()) { - throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' + - 'limitToFirst, or limitToLast).'); - } - return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_); - }; - /** - * Given a child path, return a new query ordered by the specified grandchild path. - * @param {!string} path - * @return {!Query} - */ - Query.prototype.orderByChild = function (path) { - util.validateArgCount('Query.orderByChild', 1, 1, arguments.length); - if (path === '$key') { - throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.'); - } - else if (path === '$priority') { - throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.'); - } - else if (path === '$value') { - throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.'); - } - validatePathString('Query.orderByChild', 1, path, false); - this.validateNoPreviousOrderByCall_('Query.orderByChild'); - var parsedPath = new Path(path); - if (parsedPath.isEmpty()) { - throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.'); - } - var index = new PathIndex(parsedPath); - var newParams = this.queryParams_.orderBy(index); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the KeyIndex - * @return {!Query} - */ - Query.prototype.orderByKey = function () { - util.validateArgCount('Query.orderByKey', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByKey'); - var newParams = this.queryParams_.orderBy(KEY_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the PriorityIndex - * @return {!Query} - */ - Query.prototype.orderByPriority = function () { - util.validateArgCount('Query.orderByPriority', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByPriority'); - var newParams = this.queryParams_.orderBy(PRIORITY_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the ValueIndex - * @return {!Query} - */ - Query.prototype.orderByValue = function () { - util.validateArgCount('Query.orderByValue', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByValue'); - var newParams = this.queryParams_.orderBy(VALUE_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - Query.prototype.startAt = function (value, name) { - if (value === void 0) { value = null; } - util.validateArgCount('Query.startAt', 0, 2, arguments.length); - validateFirebaseDataArg('Query.startAt', 1, value, this.path, true); - validateKey('Query.startAt', 2, name, true); - var newParams = this.queryParams_.startAt(value, name); - Query.validateLimit_(newParams); - Query.validateQueryEndpoints_(newParams); - if (this.queryParams_.hasStart()) { - throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' + - 'or equalTo).'); - } - // Calling with no params tells us to start at the beginning. - if (value === undefined) { - value = null; - name = null; - } - return new Query(this.repo, this.path, newParams, this.orderByCalled_); - }; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - Query.prototype.endAt = function (value, name) { - if (value === void 0) { value = null; } - util.validateArgCount('Query.endAt', 0, 2, arguments.length); - validateFirebaseDataArg('Query.endAt', 1, value, this.path, true); - validateKey('Query.endAt', 2, name, true); - var newParams = this.queryParams_.endAt(value, name); - Query.validateLimit_(newParams); - Query.validateQueryEndpoints_(newParams); - if (this.queryParams_.hasEnd()) { - throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' + - 'equalTo).'); - } - return new Query(this.repo, this.path, newParams, this.orderByCalled_); - }; - /** - * Load the selection of children with exactly the specified value, and, optionally, - * the specified name. - * @param {number|string|boolean|null} value - * @param {string=} name - * @return {!Query} - */ - Query.prototype.equalTo = function (value, name) { - util.validateArgCount('Query.equalTo', 1, 2, arguments.length); - validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false); - validateKey('Query.equalTo', 2, name, true); - if (this.queryParams_.hasStart()) { - throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' + - 'equalTo).'); - } - if (this.queryParams_.hasEnd()) { - throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' + - 'equalTo).'); - } - return this.startAt(value, name).endAt(value, name); - }; - /** - * @return {!string} URL for this location. - */ - Query.prototype.toString = function () { - util.validateArgCount('Query.toString', 0, 0, arguments.length); - return this.repo.toString() + this.path.toUrlEncodedString(); - }; - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users. - Query.prototype.toJSON = function () { - // An optional spacer argument is unnecessary for a string. - util.validateArgCount('Query.toJSON', 0, 1, arguments.length); - return this.toString(); - }; - /** - * An object representation of the query parameters used by this Query. - * @return {!Object} - */ - Query.prototype.queryObject = function () { - return this.queryParams_.getQueryObject(); - }; - /** - * @return {!string} - */ - Query.prototype.queryIdentifier = function () { - var obj = this.queryObject(); - var id = ObjectToUniqueKey(obj); - return id === '{}' ? 'default' : id; - }; - /** - * Return true if this query and the provided query are equivalent; otherwise, return false. - * @param {Query} other - * @return {boolean} - */ - Query.prototype.isEqual = function (other) { - util.validateArgCount('Query.isEqual', 1, 1, arguments.length); - if (!(other instanceof Query)) { - var error$$1 = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; - throw new Error(error$$1); - } - var sameRepo = this.repo === other.repo; - var samePath = this.path.equals(other.path); - var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier(); - return sameRepo && samePath && sameQueryIdentifier; - }; - /** - * Helper used by .on and .once to extract the context and or cancel arguments. - * @param {!string} fnName The function name (on or once) - * @param {(function(Error)|Object)=} cancelOrContext - * @param {Object=} context - * @return {{cancel: ?function(Error), context: ?Object}} - * @private - */ - Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) { - var ret = { cancel: null, context: null }; - if (cancelOrContext && context) { - ret.cancel = cancelOrContext; - util.validateCallback(fnName, 3, ret.cancel, true); - ret.context = context; - util.validateContextObject(fnName, 4, ret.context, true); - } - else if (cancelOrContext) { - // we have either a cancel callback or a context. - if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { - // it's a context! - ret.context = cancelOrContext; - } - else if (typeof cancelOrContext === 'function') { - ret.cancel = cancelOrContext; - } - else { - throw new Error(util.errorPrefix(fnName, 3, true) + - ' must either be a cancel callback or a context object.'); - } - } - return ret; - }; - Object.defineProperty(Query.prototype, "ref", { - get: function () { - return this.getRef(); - }, - enumerable: true, - configurable: true - }); - return Query; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Implements a set with a count of elements. - * - * @template K, V - */ -var CountedSet = /** @class */ (function () { - function CountedSet() { - this.set = {}; - } - /** - * @param {!K} item - * @param {V} val - */ - CountedSet.prototype.add = function (item, val) { - this.set[item] = val !== null ? val : true; - }; - /** - * @param {!K} key - * @return {boolean} - */ - CountedSet.prototype.contains = function (key) { - return util.contains(this.set, key); - }; - /** - * @param {!K} item - * @return {V} - */ - CountedSet.prototype.get = function (item) { - return this.contains(item) ? this.set[item] : undefined; - }; - /** - * @param {!K} item - */ - CountedSet.prototype.remove = function (item) { - delete this.set[item]; - }; - /** - * Deletes everything in the set - */ - CountedSet.prototype.clear = function () { - this.set = {}; - }; - /** - * True if there's nothing in the set - * @return {boolean} - */ - CountedSet.prototype.isEmpty = function () { - return util.isEmpty(this.set); - }; - /** - * @return {number} The number of items in the set - */ - CountedSet.prototype.count = function () { - return util.getCount(this.set); - }; - /** - * Run a function on each k,v pair in the set - * @param {function(K, V)} fn - */ - CountedSet.prototype.each = function (fn) { - util.forEach(this.set, function (k, v) { return fn(k, v); }); - }; - /** - * Mostly for debugging - * @return {Array.} The keys present in this CountedSet - */ - CountedSet.prototype.keys = function () { - var keys = []; - util.forEach(this.set, function (k) { - keys.push(k); - }); - return keys; - }; - return CountedSet; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Helper class to store a sparse set of snapshots. - * - * @constructor - */ -var SparseSnapshotTree = /** @class */ (function () { - function SparseSnapshotTree() { - /** - * @private - * @type {Node} - */ - this.value_ = null; - /** - * @private - * @type {CountedSet} - */ - this.children_ = null; - } - /** - * Gets the node stored at the given path if one exists. - * - * @param {!Path} path Path to look up snapshot for. - * @return {?Node} The retrieved node, or null. - */ - SparseSnapshotTree.prototype.find = function (path) { - if (this.value_ != null) { - return this.value_.getChild(path); - } - else if (!path.isEmpty() && this.children_ != null) { - var childKey = path.getFront(); - path = path.popFront(); - if (this.children_.contains(childKey)) { - var childTree = this.children_.get(childKey); - return childTree.find(path); - } - else { - return null; - } - } - else { - return null; - } - }; - /** - * Stores the given node at the specified path. If there is already a node - * at a shallower path, it merges the new data into that snapshot node. - * - * @param {!Path} path Path to look up snapshot for. - * @param {!Node} data The new data, or null. - */ - SparseSnapshotTree.prototype.remember = function (path, data) { - if (path.isEmpty()) { - this.value_ = data; - this.children_ = null; - } - else if (this.value_ !== null) { - this.value_ = this.value_.updateChild(path, data); - } - else { - if (this.children_ == null) { - this.children_ = new CountedSet(); - } - var childKey = path.getFront(); - if (!this.children_.contains(childKey)) { - this.children_.add(childKey, new SparseSnapshotTree()); - } - var child = this.children_.get(childKey); - path = path.popFront(); - child.remember(path, data); - } - }; - /** - * Purge the data at path from the cache. - * - * @param {!Path} path Path to look up snapshot for. - * @return {boolean} True if this node should now be removed. - */ - SparseSnapshotTree.prototype.forget = function (path) { - if (path.isEmpty()) { - this.value_ = null; - this.children_ = null; - return true; - } - else { - if (this.value_ !== null) { - if (this.value_.isLeafNode()) { - // We're trying to forget a node that doesn't exist - return false; - } - else { - var value = this.value_; - this.value_ = null; - var self_1 = this; - value.forEachChild(PRIORITY_INDEX, function (key, tree) { - self_1.remember(new Path(key), tree); - }); - return this.forget(path); - } - } - else if (this.children_ !== null) { - var childKey = path.getFront(); - path = path.popFront(); - if (this.children_.contains(childKey)) { - var safeToRemove = this.children_.get(childKey).forget(path); - if (safeToRemove) { - this.children_.remove(childKey); - } - } - if (this.children_.isEmpty()) { - this.children_ = null; - return true; - } - else { - return false; - } - } - else { - return true; - } - } - }; - /** - * Recursively iterates through all of the stored tree and calls the - * callback on each one. - * - * @param {!Path} prefixPath Path to look up node for. - * @param {!Function} func The function to invoke for each tree. - */ - SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) { - if (this.value_ !== null) { - func(prefixPath, this.value_); - } - else { - this.forEachChild(function (key, tree) { - var path = new Path(prefixPath.toString() + '/' + key); - tree.forEachTree(path, func); - }); - } - }; - /** - * Iterates through each immediate child and triggers the callback. - * - * @param {!Function} func The function to invoke for each child. - */ - SparseSnapshotTree.prototype.forEachChild = function (func) { - if (this.children_ !== null) { - this.children_.each(function (key, tree) { - func(key, tree); - }); - } - }; - return SparseSnapshotTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Generate placeholders for deferred values. - * @param {?Object} values - * @return {!Object} - */ -var generateWithValues = function (values) { - values = values || {}; - values['timestamp'] = values['timestamp'] || new Date().getTime(); - return values; -}; -/** - * Value to use when firing local events. When writing server values, fire - * local events with an approximate value, otherwise return value as-is. - * @param {(Object|string|number|boolean)} value - * @param {!Object} serverValues - * @return {!(string|number|boolean)} - */ -var resolveDeferredValue = function (value, serverValues) { - if (!value || typeof value !== 'object') { - return value; - } - else { - util.assert('.sv' in value, 'Unexpected leaf node or priority contents'); - return serverValues[value['.sv']]; - } -}; -/** - * Recursively replace all deferred values and priorities in the tree with the - * specified generated replacement values. - * @param {!SparseSnapshotTree} tree - * @param {!Object} serverValues - * @return {!SparseSnapshotTree} - */ -var resolveDeferredValueTree = function (tree, serverValues) { - var resolvedTree = new SparseSnapshotTree(); - tree.forEachTree(new Path(''), function (path, node) { - resolvedTree.remember(path, resolveDeferredValueSnapshot(node, serverValues)); - }); - return resolvedTree; -}; -/** - * Recursively replace all deferred values and priorities in the node with the - * specified generated replacement values. If there are no server values in the node, - * it'll be returned as-is. - * @param {!Node} node - * @param {!Object} serverValues - * @return {!Node} - */ -var resolveDeferredValueSnapshot = function (node, serverValues) { - var rawPri = node.getPriority().val(); - var priority = resolveDeferredValue(rawPri, serverValues); - var newNode; - if (node.isLeafNode()) { - var leafNode = node; - var value = resolveDeferredValue(leafNode.getValue(), serverValues); - if (value !== leafNode.getValue() || - priority !== leafNode.getPriority().val()) { - return new LeafNode(value, nodeFromJSON$1(priority)); - } - else { - return node; - } - } - else { - var childrenNode = node; - newNode = childrenNode; - if (priority !== childrenNode.getPriority().val()) { - newNode = newNode.updatePriority(new LeafNode(priority)); - } - childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - var newChildNode = resolveDeferredValueSnapshot(childNode, serverValues); - if (newChildNode !== childNode) { - newNode = newNode.updateImmediateChild(childName, newChildNode); - } - }); - return newNode; - } -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @enum - */ -var OperationType; -(function (OperationType) { - OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; - OperationType[OperationType["MERGE"] = 1] = "MERGE"; - OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; - OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; -})(OperationType || (OperationType = {})); -/** - * @param {boolean} fromUser - * @param {boolean} fromServer - * @param {?string} queryId - * @param {boolean} tagged - * @constructor - */ -var OperationSource = /** @class */ (function () { - function OperationSource(fromUser, fromServer, queryId, tagged) { - this.fromUser = fromUser; - this.fromServer = fromServer; - this.queryId = queryId; - this.tagged = tagged; - util.assert(!tagged || fromServer, 'Tagged queries must be from server.'); - } - /** - * @const - * @type {!OperationSource} - */ - OperationSource.User = new OperationSource( - /*fromUser=*/ true, false, null, - /*tagged=*/ false); - /** - * @const - * @type {!OperationSource} - */ - OperationSource.Server = new OperationSource(false, - /*fromServer=*/ true, null, - /*tagged=*/ false); - /** - * @param {string} queryId - * @return {!OperationSource} - */ - OperationSource.forServerTaggedQuery = function (queryId) { - return new OperationSource(false, - /*fromServer=*/ true, queryId, - /*tagged=*/ true); - }; - return OperationSource; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var AckUserWrite = /** @class */ (function () { - /** - * - * @param {!Path} path - * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap. - * @param {!boolean} revert - */ - function AckUserWrite( - /**@inheritDoc */ path, - /**@inheritDoc */ affectedTree, - /**@inheritDoc */ revert) { - this.path = path; - this.affectedTree = affectedTree; - this.revert = revert; - /** @inheritDoc */ - this.type = OperationType.ACK_USER_WRITE; - /** @inheritDoc */ - this.source = OperationSource.User; - } - /** - * @inheritDoc - */ - AckUserWrite.prototype.operationForChild = function (childName) { - if (!this.path.isEmpty()) { - util.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.'); - return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert); - } - else if (this.affectedTree.value != null) { - util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); - // All child locations are affected as well; just return same operation. - return this; - } - else { - var childTree = this.affectedTree.subtree(new Path(childName)); - return new AckUserWrite(Path.Empty, childTree, this.revert); - } - }; - return AckUserWrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var emptyChildrenSingleton; -/** - * Singleton empty children collection. - * - * @const - * @type {!SortedMap.>} - */ -var EmptyChildren = function () { - if (!emptyChildrenSingleton) { - emptyChildrenSingleton = new SortedMap(stringCompare); - } - return emptyChildrenSingleton; -}; -/** - * A tree with immutable elements. - */ -var ImmutableTree = /** @class */ (function () { - /** - * @template T - * @param {?T} value - * @param {SortedMap.>=} children - */ - function ImmutableTree(value, children) { - if (children === void 0) { children = EmptyChildren(); } - this.value = value; - this.children = children; - } - /** - * @template T - * @param {!Object.} obj - * @return {!ImmutableTree.} - */ - ImmutableTree.fromObject = function (obj) { - var tree = ImmutableTree.Empty; - util.forEach(obj, function (childPath, childSnap) { - tree = tree.set(new Path(childPath), childSnap); - }); - return tree; - }; - /** - * True if the value is empty and there are no children - * @return {boolean} - */ - ImmutableTree.prototype.isEmpty = function () { - return this.value === null && this.children.isEmpty(); - }; - /** - * Given a path and predicate, return the first node and the path to that node - * where the predicate returns true. - * - * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects - * on the way back out, it may be better to pass down a pathSoFar obj. - * - * @param {!Path} relativePath The remainder of the path - * @param {function(T):boolean} predicate The predicate to satisfy to return a - * node - * @return {?{path:!Path, value:!T}} - */ - ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) { - if (this.value != null && predicate(this.value)) { - return { path: Path.Empty, value: this.value }; - } - else { - if (relativePath.isEmpty()) { - return null; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child !== null) { - var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate); - if (childExistingPathAndValue != null) { - var fullPath = new Path(front).child(childExistingPathAndValue.path); - return { path: fullPath, value: childExistingPathAndValue.value }; - } - else { - return null; - } - } - else { - return null; - } - } - } - }; - /** - * Find, if it exists, the shortest subpath of the given path that points a defined - * value in the tree - * @param {!Path} relativePath - * @return {?{path: !Path, value: !T}} - */ - ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) { - return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; }); - }; - /** - * @param {!Path} relativePath - * @return {!ImmutableTree.} The subtree at the given path - */ - ImmutableTree.prototype.subtree = function (relativePath) { - if (relativePath.isEmpty()) { - return this; - } - else { - var front = relativePath.getFront(); - var childTree = this.children.get(front); - if (childTree !== null) { - return childTree.subtree(relativePath.popFront()); - } - else { - return ImmutableTree.Empty; - } - } - }; - /** - * Sets a value at the specified path. - * - * @param {!Path} relativePath Path to set value at. - * @param {?T} toSet Value to set. - * @return {!ImmutableTree.} Resulting tree. - */ - ImmutableTree.prototype.set = function (relativePath, toSet) { - if (relativePath.isEmpty()) { - return new ImmutableTree(toSet, this.children); - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front) || ImmutableTree.Empty; - var newChild = child.set(relativePath.popFront(), toSet); - var newChildren = this.children.insert(front, newChild); - return new ImmutableTree(this.value, newChildren); - } - }; - /** - * Removes the value at the specified path. - * - * @param {!Path} relativePath Path to value to remove. - * @return {!ImmutableTree.} Resulting tree. - */ - ImmutableTree.prototype.remove = function (relativePath) { - if (relativePath.isEmpty()) { - if (this.children.isEmpty()) { - return ImmutableTree.Empty; - } - else { - return new ImmutableTree(null, this.children); - } - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child) { - var newChild = child.remove(relativePath.popFront()); - var newChildren = void 0; - if (newChild.isEmpty()) { - newChildren = this.children.remove(front); - } - else { - newChildren = this.children.insert(front, newChild); - } - if (this.value === null && newChildren.isEmpty()) { - return ImmutableTree.Empty; - } - else { - return new ImmutableTree(this.value, newChildren); - } - } - else { - return this; - } - } - }; - /** - * Gets a value from the tree. - * - * @param {!Path} relativePath Path to get value for. - * @return {?T} Value at path, or null. - */ - ImmutableTree.prototype.get = function (relativePath) { - if (relativePath.isEmpty()) { - return this.value; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child) { - return child.get(relativePath.popFront()); - } - else { - return null; - } - } - }; - /** - * Replace the subtree at the specified path with the given new tree. - * - * @param {!Path} relativePath Path to replace subtree for. - * @param {!ImmutableTree} newTree New tree. - * @return {!ImmutableTree} Resulting tree. - */ - ImmutableTree.prototype.setTree = function (relativePath, newTree) { - if (relativePath.isEmpty()) { - return newTree; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front) || ImmutableTree.Empty; - var newChild = child.setTree(relativePath.popFront(), newTree); - var newChildren = void 0; - if (newChild.isEmpty()) { - newChildren = this.children.remove(front); - } - else { - newChildren = this.children.insert(front, newChild); - } - return new ImmutableTree(this.value, newChildren); - } - }; - /** - * Performs a depth first fold on this tree. Transforms a tree into a single - * value, given a function that operates on the path to a node, an optional - * current value, and a map of child names to folded subtrees - * @template V - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - */ - ImmutableTree.prototype.fold = function (fn) { - return this.fold_(Path.Empty, fn); - }; - /** - * Recursive helper for public-facing fold() method - * @template V - * @param {!Path} pathSoFar - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - * @private - */ - ImmutableTree.prototype.fold_ = function (pathSoFar, fn) { - var accum = {}; - this.children.inorderTraversal(function (childKey, childTree) { - accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn); - }); - return fn(pathSoFar, this.value, accum); - }; - /** - * Find the first matching value on the given path. Return the result of applying f to it. - * @template V - * @param {!Path} path - * @param {!function(!Path, !T):?V} f - * @return {?V} - */ - ImmutableTree.prototype.findOnPath = function (path, f) { - return this.findOnPath_(path, Path.Empty, f); - }; - ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) { - var result = this.value ? f(pathSoFar, this.value) : false; - if (result) { - return result; - } - else { - if (pathToFollow.isEmpty()) { - return null; - } - else { - var front = pathToFollow.getFront(); - var nextChild = this.children.get(front); - if (nextChild) { - return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f); - } - else { - return null; - } - } - } - }; - /** - * - * @param {!Path} path - * @param {!function(!Path, !T)} f - * @returns {!ImmutableTree.} - */ - ImmutableTree.prototype.foreachOnPath = function (path, f) { - return this.foreachOnPath_(path, Path.Empty, f); - }; - ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) { - if (pathToFollow.isEmpty()) { - return this; - } - else { - if (this.value) { - f(currentRelativePath, this.value); - } - var front = pathToFollow.getFront(); - var nextChild = this.children.get(front); - if (nextChild) { - return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f); - } - else { - return ImmutableTree.Empty; - } - } - }; - /** - * Calls the given function for each node in the tree that has a value. - * - * @param {function(!Path, !T)} f A function to be called with - * the path from the root of the tree to a node, and the value at that node. - * Called in depth-first order. - */ - ImmutableTree.prototype.foreach = function (f) { - this.foreach_(Path.Empty, f); - }; - ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) { - this.children.inorderTraversal(function (childName, childTree) { - childTree.foreach_(currentRelativePath.child(childName), f); - }); - if (this.value) { - f(currentRelativePath, this.value); - } - }; - /** - * - * @param {function(string, !T)} f - */ - ImmutableTree.prototype.foreachChild = function (f) { - this.children.inorderTraversal(function (childName, childTree) { - if (childTree.value) { - f(childName, childTree.value); - } - }); - }; - ImmutableTree.Empty = new ImmutableTree(null); - return ImmutableTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @constructor - * @implements {Operation} - */ -var ListenComplete = /** @class */ (function () { - function ListenComplete(source, path) { - this.source = source; - this.path = path; - /** @inheritDoc */ - this.type = OperationType.LISTEN_COMPLETE; - } - ListenComplete.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - return new ListenComplete(this.source, Path.Empty); - } - else { - return new ListenComplete(this.source, this.path.popFront()); - } - }; - return ListenComplete; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!Node} snap - * @constructor - * @implements {Operation} - */ -var Overwrite = /** @class */ (function () { - function Overwrite(source, path, snap) { - this.source = source; - this.path = path; - this.snap = snap; - /** @inheritDoc */ - this.type = OperationType.OVERWRITE; - } - Overwrite.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - return new Overwrite(this.source, Path.Empty, this.snap.getImmediateChild(childName)); - } - else { - return new Overwrite(this.source, this.path.popFront(), this.snap); - } - }; - return Overwrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!ImmutableTree.} children - * @constructor - * @implements {Operation} - */ -var Merge = /** @class */ (function () { - function Merge( - /**@inheritDoc */ source, - /**@inheritDoc */ path, - /**@inheritDoc */ children) { - this.source = source; - this.path = path; - this.children = children; - /** @inheritDoc */ - this.type = OperationType.MERGE; - } - /** - * @inheritDoc - */ - Merge.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - var childTree = this.children.subtree(new Path(childName)); - if (childTree.isEmpty()) { - // This child is unaffected - return null; - } - else if (childTree.value) { - // We have a snapshot for the child in question. This becomes an overwrite of the child. - return new Overwrite(this.source, Path.Empty, childTree.value); - } - else { - // This is a merge at a deeper level - return new Merge(this.source, Path.Empty, childTree); - } - } - else { - util.assert(this.path.getFront() === childName, "Can't get a merge for a child not on the path of the operation"); - return new Merge(this.source, this.path.popFront(), this.children); - } - }; - /** - * @inheritDoc - */ - Merge.prototype.toString = function () { - return ('Operation(' + - this.path + - ': ' + - this.source.toString() + - ' merge: ' + - this.children.toString() + - ')'); - }; - return Merge; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully - * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. - * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks - * whether a node potentially had children removed due to a filter. - */ -var CacheNode = /** @class */ (function () { - /** - * @param {!Node} node_ - * @param {boolean} fullyInitialized_ - * @param {boolean} filtered_ - */ - function CacheNode(node_, fullyInitialized_, filtered_) { - this.node_ = node_; - this.fullyInitialized_ = fullyInitialized_; - this.filtered_ = filtered_; - } - /** - * Returns whether this node was fully initialized with either server data or a complete overwrite by the client - * @return {boolean} - */ - CacheNode.prototype.isFullyInitialized = function () { - return this.fullyInitialized_; - }; - /** - * Returns whether this node is potentially missing children due to a filter applied to the node - * @return {boolean} - */ - CacheNode.prototype.isFiltered = function () { - return this.filtered_; - }; - /** - * @param {!Path} path - * @return {boolean} - */ - CacheNode.prototype.isCompleteForPath = function (path) { - if (path.isEmpty()) { - return this.isFullyInitialized() && !this.filtered_; - } - var childKey = path.getFront(); - return this.isCompleteForChild(childKey); - }; - /** - * @param {!string} key - * @return {boolean} - */ - CacheNode.prototype.isCompleteForChild = function (key) { - return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); - }; - /** - * @return {!Node} - */ - CacheNode.prototype.getNode = function () { - return this.node_; - }; - return CacheNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Stores the data we have cached for a view. - * - * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). - * - * @constructor - */ -var ViewCache = /** @class */ (function () { - /** - * - * @param {!CacheNode} eventCache_ - * @param {!CacheNode} serverCache_ - */ - function ViewCache(eventCache_, serverCache_) { - this.eventCache_ = eventCache_; - this.serverCache_ = serverCache_; - } - /** - * @param {!Node} eventSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) { - return new ViewCache(new CacheNode(eventSnap, complete, filtered), this.serverCache_); - }; - /** - * @param {!Node} serverSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) { - return new ViewCache(this.eventCache_, new CacheNode(serverSnap, complete, filtered)); - }; - /** - * @return {!CacheNode} - */ - ViewCache.prototype.getEventCache = function () { - return this.eventCache_; - }; - /** - * @return {?Node} - */ - ViewCache.prototype.getCompleteEventSnap = function () { - return this.eventCache_.isFullyInitialized() - ? this.eventCache_.getNode() - : null; - }; - /** - * @return {!CacheNode} - */ - ViewCache.prototype.getServerCache = function () { - return this.serverCache_; - }; - /** - * @return {?Node} - */ - ViewCache.prototype.getCompleteServerSnap = function () { - return this.serverCache_.isFullyInitialized() - ? this.serverCache_.getNode() - : null; - }; - /** - * @const - * @type {ViewCache} - */ - ViewCache.Empty = new ViewCache(new CacheNode(ChildrenNode.EMPTY_NODE, - /*fullyInitialized=*/ false, - /*filtered=*/ false), new CacheNode(ChildrenNode.EMPTY_NODE, - /*fullyInitialized=*/ false, - /*filtered=*/ false)); - return ViewCache; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @struct - * @param {!string} type The event type - * @param {!Node} snapshotNode The data - * @param {string=} childName The name for this child, if it's a child event - * @param {Node=} oldSnap Used for intermediate processing of child changed events - * @param {string=} prevName The name for the previous child, if applicable - */ -var Change = /** @class */ (function () { - function Change(type, snapshotNode, childName, oldSnap, prevName) { - this.type = type; - this.snapshotNode = snapshotNode; - this.childName = childName; - this.oldSnap = oldSnap; - this.prevName = prevName; - } - /** - * @param {!Node} snapshot - * @return {!Change} - */ - Change.valueChange = function (snapshot) { - return new Change(Change.VALUE, snapshot); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childAddedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_ADDED, snapshot, childKey); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childRemovedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_REMOVED, snapshot, childKey); - }; - /** - * @param {string} childKey - * @param {!Node} newSnapshot - * @param {!Node} oldSnapshot - * @return {!Change} - */ - Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) { - return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childMovedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_MOVED, snapshot, childKey); - }; - //event types - /** Event type for a child added */ - Change.CHILD_ADDED = 'child_added'; - /** Event type for a child removed */ - Change.CHILD_REMOVED = 'child_removed'; - /** Event type for a child changed */ - Change.CHILD_CHANGED = 'child_changed'; - /** Event type for a child moved */ - Change.CHILD_MOVED = 'child_moved'; - /** Event type for a value change */ - Change.VALUE = 'value'; - return Change; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Doesn't really filter nodes but applies an index to the node and keeps track of any changes - * - * @constructor - * @implements {NodeFilter} - * @param {!Index} index - */ -var IndexedFilter = /** @class */ (function () { - function IndexedFilter(index_) { - this.index_ = index_; - } - IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); - var oldChild = snap.getImmediateChild(key); - // Check if anything actually changed. - if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { - // There's an edge case where a child can enter or leave the view because affectedPath was set to null. - // In this case, affectedPath will appear null in both the old and new snapshots. So we need - // to avoid treating these cases as "nothing changed." - if (oldChild.isEmpty() == newChild.isEmpty()) { - // Nothing changed. - // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. - //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); - return snap; - } - } - if (optChangeAccumulator != null) { - if (newChild.isEmpty()) { - if (snap.hasChild(key)) { - optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, oldChild)); - } - else { - util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); - } - } - else if (oldChild.isEmpty()) { - optChangeAccumulator.trackChildChange(Change.childAddedChange(key, newChild)); - } - else { - optChangeAccumulator.trackChildChange(Change.childChangedChange(key, newChild, oldChild)); - } - } - if (snap.isLeafNode() && newChild.isEmpty()) { - return snap; - } - else { - // Make sure the node is indexed - return snap.updateImmediateChild(key, newChild).withIndex(this.index_); - } - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - if (optChangeAccumulator != null) { - if (!oldSnap.isLeafNode()) { - oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (!newSnap.hasChild(key)) { - optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, childNode)); - } - }); - } - if (!newSnap.isLeafNode()) { - newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (oldSnap.hasChild(key)) { - var oldChild = oldSnap.getImmediateChild(key); - if (!oldChild.equals(childNode)) { - optChangeAccumulator.trackChildChange(Change.childChangedChange(key, childNode, oldChild)); - } - } - else { - optChangeAccumulator.trackChildChange(Change.childAddedChange(key, childNode)); - } - }); - } - } - return newSnap.withIndex(this.index_); - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - if (oldSnap.isEmpty()) { - return ChildrenNode.EMPTY_NODE; - } - else { - return oldSnap.updatePriority(newPriority); - } - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.filtersNodes = function () { - return false; - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.getIndexedFilter = function () { - return this; - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.getIndex = function () { - return this.index_; - }; - return IndexedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - */ -var ChildChangeAccumulator = /** @class */ (function () { - function ChildChangeAccumulator() { - this.changeMap_ = {}; - } - /** - * @param {!Change} change - */ - ChildChangeAccumulator.prototype.trackChildChange = function (change) { - var type = change.type; - var childKey /** @type {!string} */ = change.childName; - util.assert(type == Change.CHILD_ADDED || - type == Change.CHILD_CHANGED || - type == Change.CHILD_REMOVED, 'Only child changes supported for tracking'); - util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); - var oldChange = util.safeGet(this.changeMap_, childKey); - if (oldChange) { - var oldType = oldChange.type; - if (type == Change.CHILD_ADDED && oldType == Change.CHILD_REMOVED) { - this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode); - } - else if (type == Change.CHILD_REMOVED && - oldType == Change.CHILD_ADDED) { - delete this.changeMap_[childKey]; - } - else if (type == Change.CHILD_REMOVED && - oldType == Change.CHILD_CHANGED) { - this.changeMap_[childKey] = Change.childRemovedChange(childKey, oldChange.oldSnap); - } - else if (type == Change.CHILD_CHANGED && - oldType == Change.CHILD_ADDED) { - this.changeMap_[childKey] = Change.childAddedChange(childKey, change.snapshotNode); - } - else if (type == Change.CHILD_CHANGED && - oldType == Change.CHILD_CHANGED) { - this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap); - } - else { - throw util.assertionError('Illegal combination of changes: ' + - change + - ' occurred after ' + - oldChange); - } - } - else { - this.changeMap_[childKey] = change; - } - }; - /** - * @return {!Array.} - */ - ChildChangeAccumulator.prototype.getChanges = function () { - return util.getValues(this.changeMap_); - }; - return ChildChangeAccumulator; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An implementation of CompleteChildSource that never returns any additional children - * - * @private - * @constructor - * @implements CompleteChildSource - */ -var NoCompleteChildSource_ = /** @class */ (function () { - function NoCompleteChildSource_() { - } - /** - * @inheritDoc - */ - NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) { - return null; - }; - /** - * @inheritDoc - */ - NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) { - return null; - }; - return NoCompleteChildSource_; -}()); -/** - * Singleton instance. - * @const - * @type {!CompleteChildSource} - */ -var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); -/** - * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or - * old event caches available to calculate complete children. - * - * - * @implements CompleteChildSource - */ -var WriteTreeCompleteChildSource = /** @class */ (function () { - /** - * @param {!WriteTreeRef} writes_ - * @param {!ViewCache} viewCache_ - * @param {?Node} optCompleteServerCache_ - */ - function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) { - if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; } - this.writes_ = writes_; - this.viewCache_ = viewCache_; - this.optCompleteServerCache_ = optCompleteServerCache_; - } - /** - * @inheritDoc - */ - WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) { - var node = this.viewCache_.getEventCache(); - if (node.isCompleteForChild(childKey)) { - return node.getNode().getImmediateChild(childKey); - } - else { - var serverNode = this.optCompleteServerCache_ != null - ? new CacheNode(this.optCompleteServerCache_, true, false) - : this.viewCache_.getServerCache(); - return this.writes_.calcCompleteChild(childKey, serverNode); - } - }; - /** - * @inheritDoc - */ - WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) { - var completeServerData = this.optCompleteServerCache_ != null - ? this.optCompleteServerCache_ - : this.viewCache_.getCompleteServerSnap(); - var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index); - if (nodes.length === 0) { - return null; - } - else { - return nodes[0]; - } - }; - return WriteTreeCompleteChildSource; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @struct - */ -var ProcessorResult = /** @class */ (function () { - /** - * @param {!ViewCache} viewCache - * @param {!Array.} changes - */ - function ProcessorResult(viewCache, changes) { - this.viewCache = viewCache; - this.changes = changes; - } - return ProcessorResult; -}()); -/** - * @constructor - */ -var ViewProcessor = /** @class */ (function () { - /** - * @param {!NodeFilter} filter_ - */ - function ViewProcessor(filter_) { - this.filter_ = filter_; - } - /** - * @param {!ViewCache} viewCache - */ - ViewProcessor.prototype.assertIndexed = function (viewCache) { - util.assert(viewCache - .getEventCache() - .getNode() - .isIndexed(this.filter_.getIndex()), 'Event snap not indexed'); - util.assert(viewCache - .getServerCache() - .getNode() - .isIndexed(this.filter_.getIndex()), 'Server snap not indexed'); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @return {!ProcessorResult} - */ - ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) { - var accumulator = new ChildChangeAccumulator(); - var newViewCache, filterServerNode; - if (operation.type === OperationType.OVERWRITE) { - var overwrite = operation; - if (overwrite.source.fromUser) { - newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); - } - else { - util.assert(overwrite.source.fromServer, 'Unknown source.'); - // We filter the node if it's a tagged update or the node has been previously filtered and the - // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered - // again - filterServerNode = - overwrite.source.tagged || - (oldViewCache.getServerCache().isFiltered() && - !overwrite.path.isEmpty()); - newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); - } - } - else if (operation.type === OperationType.MERGE) { - var merge = operation; - if (merge.source.fromUser) { - newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); - } - else { - util.assert(merge.source.fromServer, 'Unknown source.'); - // We filter the node if it's a tagged update or the node has been previously filtered - filterServerNode = - merge.source.tagged || oldViewCache.getServerCache().isFiltered(); - newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); - } - } - else if (operation.type === OperationType.ACK_USER_WRITE) { - var ackUserWrite = operation; - if (!ackUserWrite.revert) { - newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); - } - else { - newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); - } - } - else if (operation.type === OperationType.LISTEN_COMPLETE) { - newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator); - } - else { - throw util.assertionError('Unknown operation type: ' + operation.type); - } - var changes = accumulator.getChanges(); - ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes); - return new ProcessorResult(newViewCache, changes); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!ViewCache} newViewCache - * @param {!Array.} accumulator - * @private - */ - ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) { - var eventSnap = newViewCache.getEventCache(); - if (eventSnap.isFullyInitialized()) { - var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); - var oldCompleteSnap = oldViewCache.getCompleteEventSnap(); - if (accumulator.length > 0 || - !oldViewCache.getEventCache().isFullyInitialized() || - (isLeafOrEmpty && - !eventSnap - .getNode() - .equals(/** @type {!Node} */ (oldCompleteSnap))) || - !eventSnap - .getNode() - .getPriority() - .equals(oldCompleteSnap.getPriority())) { - accumulator.push(Change.valueChange( - /** @type {!Node} */ newViewCache.getCompleteEventSnap())); - } - } - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} changePath - * @param {!WriteTreeRef} writesCache - * @param {!CompleteChildSource} source - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) { - var oldEventSnap = viewCache.getEventCache(); - if (writesCache.shadowingWrite(changePath) != null) { - // we have a shadowing write, ignore changes - return viewCache; - } - else { - var newEventCache = void 0, serverNode = void 0; - if (changePath.isEmpty()) { - // TODO: figure out how this plays with "sliding ack windows" - util.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data'); - if (viewCache.getServerCache().isFiltered()) { - // We need to special case this, because we need to only apply writes to complete children, or - // we might end up raising events for incomplete children. If the server data is filtered deep - // writes cannot be guaranteed to be complete - var serverCache = viewCache.getCompleteServerSnap(); - var completeChildren = serverCache instanceof ChildrenNode - ? serverCache - : ChildrenNode.EMPTY_NODE; - var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren); - newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator); - } - else { - var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator); - } - } - else { - var childKey = changePath.getFront(); - if (childKey == '.priority') { - util.assert(changePath.getLength() == 1, "Can't have a priority with additional path components"); - var oldEventNode = oldEventSnap.getNode(); - serverNode = viewCache.getServerCache().getNode(); - // we might have overwrites for this priority - var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode); - if (updatedPriority != null) { - newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority); - } - else { - // priority didn't change, keep old node - newEventCache = oldEventSnap.getNode(); - } - } - else { - var childChangePath = changePath.popFront(); - // update child - var newEventChild = void 0; - if (oldEventSnap.isCompleteForChild(childKey)) { - serverNode = viewCache.getServerCache().getNode(); - var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode); - if (eventChildUpdate != null) { - newEventChild = oldEventSnap - .getNode() - .getImmediateChild(childKey) - .updateChild(childChangePath, eventChildUpdate); - } - else { - // Nothing changed, just keep the old child - newEventChild = oldEventSnap - .getNode() - .getImmediateChild(childKey); - } - } - else { - newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache()); - } - if (newEventChild != null) { - newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); - } - else { - // no complete child available or no change - newEventCache = oldEventSnap.getNode(); - } - } - } - return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes()); - } - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { - var oldServerSnap = oldViewCache.getServerCache(); - var newServerCache; - var serverFilter = filterServerNode - ? this.filter_ - : this.filter_.getIndexedFilter(); - if (changePath.isEmpty()) { - newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); - } - else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { - // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update - var newServerNode = oldServerSnap - .getNode() - .updateChild(changePath, changedSnap); - newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); - } - else { - var childKey = changePath.getFront(); - if (!oldServerSnap.isCompleteForPath(changePath) && - changePath.getLength() > 1) { - // We don't update incomplete nodes with updates intended for other listeners - return oldViewCache; - } - var childChangePath = changePath.popFront(); - var childNode = oldServerSnap.getNode().getImmediateChild(childKey); - var newChildNode = childNode.updateChild(childChangePath, changedSnap); - if (childKey == '.priority') { - newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); - } - else { - newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); - } - } - var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes()); - var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); - return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { - var oldEventSnap = oldViewCache.getEventCache(); - var newViewCache, newEventCache; - var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); - if (changePath.isEmpty()) { - newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator); - newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes()); - } - else { - var childKey = changePath.getFront(); - if (childKey === '.priority') { - newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap); - newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); - } - else { - var childChangePath = changePath.popFront(); - var oldChild = oldEventSnap.getNode().getImmediateChild(childKey); - var newChild = void 0; - if (childChangePath.isEmpty()) { - // Child overwrite, we can replace the child - newChild = changedSnap; - } - else { - var childNode = source.getCompleteChild(childKey); - if (childNode != null) { - if (childChangePath.getBack() === '.priority' && - childNode.getChild(childChangePath.parent()).isEmpty()) { - // This is a priority update on an empty node. If this node exists on the server, the - // server will send down the priority in the update, so ignore for now - newChild = childNode; - } - else { - newChild = childNode.updateChild(childChangePath, changedSnap); - } - } - else { - // There is no complete child node available - newChild = ChildrenNode.EMPTY_NODE; - } - } - if (!oldChild.equals(newChild)) { - var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); - newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes()); - } - else { - newViewCache = oldViewCache; - } - } - } - return newViewCache; - }; - /** - * @param {!ViewCache} viewCache - * @param {string} childKey - * @return {boolean} - * @private - */ - ViewProcessor.cacheHasChild_ = function (viewCache, childKey) { - return viewCache.getEventCache().isCompleteForChild(childKey); - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) { - var _this = this; - // HACK: In the case of a limit query, there may be some changes that bump things out of the - // window leaving room for new items. It's important we process these changes first, so we - // iterate the changes twice, first processing any that affect items currently in view. - // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server - // and event snap. I'm not sure if this will result in edge cases when a child is in one but - // not the other. - var curViewCache = viewCache; - changedChildren.foreach(function (relativePath, childNode) { - var writePath = path.child(relativePath); - if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) { - curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator); - } - }); - changedChildren.foreach(function (relativePath, childNode) { - var writePath = path.child(relativePath); - if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) { - curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator); - } - }); - return curViewCache; - }; - /** - * @param {!Node} node - * @param {ImmutableTree.} merge - * @return {!Node} - * @private - */ - ViewProcessor.prototype.applyMerge_ = function (node, merge) { - merge.foreach(function (relativePath, childNode) { - node = node.updateChild(relativePath, childNode); - }); - return node; - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { - var _this = this; - // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and - // wait for the complete data update coming soon. - if (viewCache - .getServerCache() - .getNode() - .isEmpty() && - !viewCache.getServerCache().isFullyInitialized()) { - return viewCache; - } - // HACK: In the case of a limit query, there may be some changes that bump things out of the - // window leaving room for new items. It's important we process these changes first, so we - // iterate the changes twice, first processing any that affect items currently in view. - // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server - // and event snap. I'm not sure if this will result in edge cases when a child is in one but - // not the other. - var curViewCache = viewCache; - var viewMergeTree; - if (path.isEmpty()) { - viewMergeTree = changedChildren; - } - else { - viewMergeTree = ImmutableTree.Empty.setTree(path, changedChildren); - } - var serverNode = viewCache.getServerCache().getNode(); - viewMergeTree.children.inorderTraversal(function (childKey, childTree) { - if (serverNode.hasChild(childKey)) { - var serverChild = viewCache - .getServerCache() - .getNode() - .getImmediateChild(childKey); - var newChild = _this.applyMerge_(serverChild, childTree); - curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); - } - }); - viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) { - var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) && - childMergeTree.value == null; - if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { - var serverChild = viewCache - .getServerCache() - .getNode() - .getImmediateChild(childKey); - var newChild = _this.applyMerge_(serverChild, childMergeTree); - curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); - } - }); - return curViewCache; - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} ackPath - * @param {!ImmutableTree} affectedTree - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { - if (writesCache.shadowingWrite(ackPath) != null) { - return viewCache; - } - // Only filter server node if it is currently filtered - var filterServerNode = viewCache.getServerCache().isFiltered(); - // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update - // now that it won't be shadowed. - var serverCache = viewCache.getServerCache(); - if (affectedTree.value != null) { - // This is an overwrite. - if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) || - serverCache.isCompleteForPath(ackPath)) { - return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); - } - else if (ackPath.isEmpty()) { - // This is a goofy edge case where we are acking data at this location but don't have full data. We - // should just re-apply whatever we have in our cache as a merge. - var changedChildren_1 = ImmutableTree.Empty; - serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) { - changedChildren_1 = changedChildren_1.set(new Path(name), node); - }); - return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator); - } - else { - return viewCache; - } - } - else { - // This is a merge. - var changedChildren_2 = ImmutableTree.Empty; - affectedTree.foreach(function (mergePath, value) { - var serverCachePath = ackPath.child(mergePath); - if (serverCache.isCompleteForPath(serverCachePath)) { - changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath)); - } - }); - return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator); - } - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) { - var oldServerNode = viewCache.getServerCache(); - var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered()); - return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) { - var complete; - if (writesCache.shadowingWrite(path) != null) { - return viewCache; - } - else { - var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); - var oldEventCache = viewCache.getEventCache().getNode(); - var newEventCache = void 0; - if (path.isEmpty() || path.getFront() === '.priority') { - var newNode = void 0; - if (viewCache.getServerCache().isFullyInitialized()) { - newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - } - else { - var serverChildren = viewCache.getServerCache().getNode(); - util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); - newNode = writesCache.calcCompleteEventChildren(serverChildren); - } - newNode = newNode; - newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator); - } - else { - var childKey = path.getFront(); - var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache()); - if (newChild == null && - viewCache.getServerCache().isCompleteForChild(childKey)) { - newChild = oldEventCache.getImmediateChild(childKey); - } - if (newChild != null) { - newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator); - } - else if (viewCache - .getEventCache() - .getNode() - .hasChild(childKey)) { - // No complete child available, delete the existing one, if any - newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator); - } - else { - newEventCache = oldEventCache; - } - if (newEventCache.isEmpty() && - viewCache.getServerCache().isFullyInitialized()) { - // We might have reverted all child writes. Maybe the old event was a leaf node - complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - if (complete.isLeafNode()) { - newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator); - } - } - } - complete = - viewCache.getServerCache().isFullyInitialized() || - writesCache.shadowingWrite(Path.Empty) != null; - return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes()); - } - }; - return ViewProcessor; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An EventGenerator is used to convert "raw" changes (Change) as computed by the - * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() - * for details. - * - * @constructor - */ -var EventGenerator = /** @class */ (function () { - /** - * - * @param {!Query} query_ - */ - function EventGenerator(query_) { - this.query_ = query_; - /** - * @private - * @type {!Index} - */ - this.index_ = this.query_.getQueryParams().getIndex(); - } - /** - * Given a set of raw changes (no moved events and prevName not specified yet), and a set of - * EventRegistrations that should be notified of these changes, generate the actual events to be raised. - * - * Notes: - * - child_moved events will be synthesized at this time for any child_changed events that affect - * our index. - * - prevName will be calculated based on the index ordering. - * - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {!Array.} eventRegistrations - * @return {!Array.} - */ - EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) { - var _this = this; - var events = []; - var moves = []; - changes.forEach(function (change) { - if (change.type === Change.CHILD_CHANGED && - _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { - moves.push(Change.childMovedChange(change.childName, change.snapshotNode)); - } - }); - this.generateEventsForType_(events, Change.CHILD_REMOVED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_ADDED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_MOVED, moves, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_CHANGED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.VALUE, changes, eventRegistrations, eventCache); - return events; - }; - /** - * Given changes of a single change type, generate the corresponding events. - * - * @param {!Array.} events - * @param {!string} eventType - * @param {!Array.} changes - * @param {!Array.} registrations - * @param {!Node} eventCache - * @private - */ - EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) { - var _this = this; - var filteredChanges = changes.filter(function (change) { return change.type === eventType; }); - filteredChanges.sort(this.compareChanges_.bind(this)); - filteredChanges.forEach(function (change) { - var materializedChange = _this.materializeSingleChange_(change, eventCache); - registrations.forEach(function (registration) { - if (registration.respondsTo(change.type)) { - events.push(registration.createEvent(materializedChange, _this.query_)); - } - }); - }); - }; - /** - * @param {!Change} change - * @param {!Node} eventCache - * @return {!Change} - * @private - */ - EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) { - if (change.type === 'value' || change.type === 'child_removed') { - return change; - } - else { - change.prevName = eventCache.getPredecessorChildName( - /** @type {!string} */ - change.childName, change.snapshotNode, this.index_); - return change; - } - }; - /** - * @param {!Change} a - * @param {!Change} b - * @return {number} - * @private - */ - EventGenerator.prototype.compareChanges_ = function (a, b) { - if (a.childName == null || b.childName == null) { - throw util.assertionError('Should only compare child_ events.'); - } - var aWrapped = new NamedNode(a.childName, a.snapshotNode); - var bWrapped = new NamedNode(b.childName, b.snapshotNode); - return this.index_.compare(aWrapped, bWrapped); - }; - return EventGenerator; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A view represents a specific location and query that has 1 or more event registrations. - * - * It does several things: - * - Maintains the list of event registrations for this location/query. - * - Maintains a cache of the data visible for this location/query. - * - Applies new operations (via applyOperation), updates the cache, and based on the event - * registrations returns the set of events to be raised. - * @constructor - */ -var View = /** @class */ (function () { - /** - * - * @param {!Query} query_ - * @param {!ViewCache} initialViewCache - */ - function View(query_, initialViewCache) { - this.query_ = query_; - this.eventRegistrations_ = []; - var params = this.query_.getQueryParams(); - var indexFilter = new IndexedFilter(params.getIndex()); - var filter = params.getNodeFilter(); - /** - * @type {ViewProcessor} - * @private - */ - this.processor_ = new ViewProcessor(filter); - var initialServerCache = initialViewCache.getServerCache(); - var initialEventCache = initialViewCache.getEventCache(); - // Don't filter server node with other filter than index, wait for tagged listen - var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); - var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); - var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); - var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); - /** - * @type {!ViewCache} - * @private - */ - this.viewCache_ = new ViewCache(newEventCache, newServerCache); - /** - * @type {!EventGenerator} - * @private - */ - this.eventGenerator_ = new EventGenerator(this.query_); - } - /** - * @return {!Query} - */ - View.prototype.getQuery = function () { - return this.query_; - }; - /** - * @return {?Node} - */ - View.prototype.getServerCache = function () { - return this.viewCache_.getServerCache().getNode(); - }; - /** - * @param {!Path} path - * @return {?Node} - */ - View.prototype.getCompleteServerCache = function (path) { - var cache = this.viewCache_.getCompleteServerSnap(); - if (cache) { - // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and - // we need to see if it contains the child we're interested in. - if (this.query_.getQueryParams().loadsAllData() || - (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) { - return cache.getChild(path); - } - } - return null; - }; - /** - * @return {boolean} - */ - View.prototype.isEmpty = function () { - return this.eventRegistrations_.length === 0; - }; - /** - * @param {!EventRegistration} eventRegistration - */ - View.prototype.addEventRegistration = function (eventRegistration) { - this.eventRegistrations_.push(eventRegistration); - }; - /** - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - View.prototype.removeEventRegistration = function (eventRegistration, cancelError) { - var cancelEvents = []; - if (cancelError) { - util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); - var path_1 = this.query_.path; - this.eventRegistrations_.forEach(function (registration) { - cancelError /** @type {!Error} */ = cancelError; - var maybeEvent = registration.createCancelEvent(cancelError, path_1); - if (maybeEvent) { - cancelEvents.push(maybeEvent); - } - }); - } - if (eventRegistration) { - var remaining = []; - for (var i = 0; i < this.eventRegistrations_.length; ++i) { - var existing = this.eventRegistrations_[i]; - if (!existing.matches(eventRegistration)) { - remaining.push(existing); - } - else if (eventRegistration.hasAnyCallback()) { - // We're removing just this one - remaining = remaining.concat(this.eventRegistrations_.slice(i + 1)); - break; - } - } - this.eventRegistrations_ = remaining; - } - else { - this.eventRegistrations_ = []; - } - return cancelEvents; - }; - /** - * Applies the given Operation, updates our cache, and returns the appropriate events. - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @return {!Array.} - */ - View.prototype.applyOperation = function (operation, writesCache, completeServerCache) { - if (operation.type === OperationType.MERGE && - operation.source.queryId !== null) { - util.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges'); - util.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache'); - } - var oldViewCache = this.viewCache_; - var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache); - this.processor_.assertIndexed(result.viewCache); - util.assert(result.viewCache.getServerCache().isFullyInitialized() || - !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back'); - this.viewCache_ = result.viewCache; - return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null); - }; - /** - * @param {!EventRegistration} registration - * @return {!Array.} - */ - View.prototype.getInitialEvents = function (registration) { - var eventSnap = this.viewCache_.getEventCache(); - var initialChanges = []; - if (!eventSnap.getNode().isLeafNode()) { - var eventNode = eventSnap.getNode(); - eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) { - initialChanges.push(Change.childAddedChange(key, childNode)); - }); - } - if (eventSnap.isFullyInitialized()) { - initialChanges.push(Change.valueChange(eventSnap.getNode())); - } - return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration); - }; - /** - * @private - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {EventRegistration=} eventRegistration - * @return {!Array.} - */ - View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) { - var registrations = eventRegistration - ? [eventRegistration] - : this.eventRegistrations_; - return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations); - }; - return View; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __referenceConstructor$1; -/** - * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to - * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes - * and user writes (set, transaction, update). - * - * It's responsible for: - * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). - * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, - * applyUserOverwrite, etc.) - */ -var SyncPoint = /** @class */ (function () { - function SyncPoint() { - /** - * The Views being tracked at this location in the tree, stored as a map where the key is a - * queryId and the value is the View for that query. - * - * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). - * - * @type {!Object.} - * @private - */ - this.views_ = {}; - } - Object.defineProperty(SyncPoint, "__referenceConstructor", { - get: function () { - util.assert(__referenceConstructor$1, 'Reference.ts has not been loaded'); - return __referenceConstructor$1; - }, - set: function (val) { - util.assert(!__referenceConstructor$1, '__referenceConstructor has already been defined'); - __referenceConstructor$1 = val; - }, - enumerable: true, - configurable: true - }); - /** - * @return {boolean} - */ - SyncPoint.prototype.isEmpty = function () { - return util.isEmpty(this.views_); - }; - /** - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} optCompleteServerCache - * @return {!Array.} - */ - SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) { - var queryId = operation.source.queryId; - if (queryId !== null) { - var view = util.safeGet(this.views_, queryId); - util.assert(view != null, 'SyncTree gave us an op for an invalid query.'); - return view.applyOperation(operation, writesCache, optCompleteServerCache); - } - else { - var events_1 = []; - util.forEach(this.views_, function (key, view) { - events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache)); - }); - return events_1; - } - }; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache Complete server cache, if we have it. - * @param {boolean} serverCacheComplete - * @return {!Array.} Events to raise. - */ - SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) { - var queryId = query.queryIdentifier(); - var view = util.safeGet(this.views_, queryId); - if (!view) { - // TODO: make writesCache take flag for complete server node - var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null); - var eventCacheComplete = false; - if (eventCache) { - eventCacheComplete = true; - } - else if (serverCache instanceof ChildrenNode) { - eventCache = writesCache.calcCompleteEventChildren(serverCache); - eventCacheComplete = false; - } - else { - eventCache = ChildrenNode.EMPTY_NODE; - eventCacheComplete = false; - } - var viewCache = new ViewCache(new CacheNode( - /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode( - /** @type {!Node} */ (serverCache), serverCacheComplete, false)); - view = new View(query, viewCache); - this.views_[queryId] = view; - } - // This is guaranteed to exist now, we just created anything that was missing - view.addEventRegistration(eventRegistration); - return view.getInitialEvents(eventRegistration); - }; - /** - * Remove event callback(s). Return cancelEvents if a cancelError is specified. - * - * If query is the default query, we'll check all views for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified view(s). - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events - */ - SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) { - var queryId = query.queryIdentifier(); - var removed = []; - var cancelEvents = []; - var hadCompleteView = this.hasCompleteView(); - if (queryId === 'default') { - // When you do ref.off(...), we search all views for the registration to remove. - var self_1 = this; - util.forEach(this.views_, function (viewQueryId, view) { - cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError)); - if (view.isEmpty()) { - delete self_1.views_[viewQueryId]; - // We'll deal with complete views later. - if (!view - .getQuery() - .getQueryParams() - .loadsAllData()) { - removed.push(view.getQuery()); - } - } - }); - } - else { - // remove the callback from the specific view. - var view = util.safeGet(this.views_, queryId); - if (view) { - cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError)); - if (view.isEmpty()) { - delete this.views_[queryId]; - // We'll deal with complete views later. - if (!view - .getQuery() - .getQueryParams() - .loadsAllData()) { - removed.push(view.getQuery()); - } - } - } - } - if (hadCompleteView && !this.hasCompleteView()) { - // We removed our last complete view. - removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path)); - } - return { removed: removed, events: cancelEvents }; - }; - /** - * @return {!Array.} - */ - SyncPoint.prototype.getQueryViews = function () { - var _this = this; - var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; }); - return values.filter(function (view) { - return !view - .getQuery() - .getQueryParams() - .loadsAllData(); - }); - }; - /** - * - * @param {!Path} path The path to the desired complete snapshot - * @return {?Node} A complete cache, if it exists - */ - SyncPoint.prototype.getCompleteServerCache = function (path) { - var serverCache = null; - util.forEach(this.views_, function (key, view) { - serverCache = serverCache || view.getCompleteServerCache(path); - }); - return serverCache; - }; - /** - * @param {!Query} query - * @return {?View} - */ - SyncPoint.prototype.viewForQuery = function (query) { - var params = query.getQueryParams(); - if (params.loadsAllData()) { - return this.getCompleteView(); - } - else { - var queryId = query.queryIdentifier(); - return util.safeGet(this.views_, queryId); - } - }; - /** - * @param {!Query} query - * @return {boolean} - */ - SyncPoint.prototype.viewExistsForQuery = function (query) { - return this.viewForQuery(query) != null; - }; - /** - * @return {boolean} - */ - SyncPoint.prototype.hasCompleteView = function () { - return this.getCompleteView() != null; - }; - /** - * @return {?View} - */ - SyncPoint.prototype.getCompleteView = function () { - var completeView = util.findValue(this.views_, function (view) { - return view - .getQuery() - .getQueryParams() - .loadsAllData(); - }); - return completeView || null; - }; - return SyncPoint; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with - * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write - * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write - * to reflect the write added. - * - * @constructor - * @param {!ImmutableTree.} writeTree - */ -var CompoundWrite = /** @class */ (function () { - function CompoundWrite(writeTree_) { - this.writeTree_ = writeTree_; - } - /** - * @param {!Path} path - * @param {!Node} node - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.addWrite = function (path, node) { - if (path.isEmpty()) { - return new CompoundWrite(new ImmutableTree(node)); - } - else { - var rootmost = this.writeTree_.findRootMostValueAndPath(path); - if (rootmost != null) { - var rootMostPath = rootmost.path; - var value = rootmost.value; - var relativePath = Path.relativePath(rootMostPath, path); - value = value.updateChild(relativePath, node); - return new CompoundWrite(this.writeTree_.set(rootMostPath, value)); - } - else { - var subtree = new ImmutableTree(node); - var newWriteTree = this.writeTree_.setTree(path, subtree); - return new CompoundWrite(newWriteTree); - } - } - }; - /** - * @param {!Path} path - * @param {!Object.} updates - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.addWrites = function (path, updates) { - var newWrite = this; - util.forEach(updates, function (childKey, node) { - newWrite = newWrite.addWrite(path.child(childKey), node); - }); - return newWrite; - }; - /** - * Will remove a write at the given path and deeper paths. This will not modify a write at a higher - * location, which must be removed by calling this method with that path. - * - * @param {!Path} path The path at which a write and all deeper writes should be removed - * @return {!CompoundWrite} The new CompoundWrite with the removed path - */ - CompoundWrite.prototype.removeWrite = function (path) { - if (path.isEmpty()) { - return CompoundWrite.Empty; - } - else { - var newWriteTree = this.writeTree_.setTree(path, ImmutableTree.Empty); - return new CompoundWrite(newWriteTree); - } - }; - /** - * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be - * considered "complete". - * - * @param {!Path} path The path to check for - * @return {boolean} Whether there is a complete write at that path - */ - CompoundWrite.prototype.hasCompleteWrite = function (path) { - return this.getCompleteNode(path) != null; - }; - /** - * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate - * writes from deeper paths, but will return child nodes from a more shallow path. - * - * @param {!Path} path The path to get a complete write - * @return {?Node} The node if complete at that path, or null otherwise. - */ - CompoundWrite.prototype.getCompleteNode = function (path) { - var rootmost = this.writeTree_.findRootMostValueAndPath(path); - if (rootmost != null) { - return this.writeTree_ - .get(rootmost.path) - .getChild(Path.relativePath(rootmost.path, path)); - } - else { - return null; - } - }; - /** - * Returns all children that are guaranteed to be a complete overwrite. - * - * @return {!Array.} A list of all complete children. - */ - CompoundWrite.prototype.getCompleteChildren = function () { - var children = []; - var node = this.writeTree_.value; - if (node != null) { - // If it's a leaf node, it has no children; so nothing to do. - if (!node.isLeafNode()) { - node.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - children.push(new NamedNode(childName, childNode)); - }); - } - } - else { - this.writeTree_.children.inorderTraversal(function (childName, childTree) { - if (childTree.value != null) { - children.push(new NamedNode(childName, childTree.value)); - } - }); - } - return children; - }; - /** - * @param {!Path} path - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.childCompoundWrite = function (path) { - if (path.isEmpty()) { - return this; - } - else { - var shadowingNode = this.getCompleteNode(path); - if (shadowingNode != null) { - return new CompoundWrite(new ImmutableTree(shadowingNode)); - } - else { - return new CompoundWrite(this.writeTree_.subtree(path)); - } - } - }; - /** - * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. - * @return {boolean} Whether this CompoundWrite is empty - */ - CompoundWrite.prototype.isEmpty = function () { - return this.writeTree_.isEmpty(); - }; - /** - * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the - * node - * @param {!Node} node The node to apply this CompoundWrite to - * @return {!Node} The node with all writes applied - */ - CompoundWrite.prototype.apply = function (node) { - return CompoundWrite.applySubtreeWrite_(Path.Empty, this.writeTree_, node); - }; - /** - * @type {!CompoundWrite} - */ - CompoundWrite.Empty = new CompoundWrite(new ImmutableTree(null)); - /** - * @param {!Path} relativePath - * @param {!ImmutableTree.} writeTree - * @param {!Node} node - * @return {!Node} - * @private - */ - CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) { - if (writeTree.value != null) { - // Since there a write is always a leaf, we're done here - return node.updateChild(relativePath, writeTree.value); - } - else { - var priorityWrite_1 = null; - writeTree.children.inorderTraversal(function (childKey, childTree) { - if (childKey === '.priority') { - // Apply priorities at the end so we don't update priorities for either empty nodes or forget - // to apply priorities to empty nodes that are later filled - util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); - priorityWrite_1 = childTree.value; - } - else { - node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node); - } - }); - // If there was a priority write, we only apply it if the node is not empty - if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) { - node = node.updateChild(relativePath.child('.priority'), priorityWrite_1); - } - return node; - } - }; - return CompoundWrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them - * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() - * and addMerge(), and removed with removeWrite(). - * - * @constructor - */ -var WriteTree = /** @class */ (function () { - function WriteTree() { - /** - * A tree tracking the result of applying all visible writes. This does not include transactions with - * applyLocally=false or writes that are completely shadowed by other writes. - * - * @type {!CompoundWrite} - * @private - */ - this.visibleWrites_ = CompoundWrite.Empty; - /** - * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary - * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also - * used by transactions). - * - * @type {!Array.} - * @private - */ - this.allWrites_ = []; - this.lastWriteId_ = -1; - } - /** - * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. - * - * @param {!Path} path - * @return {!WriteTreeRef} - */ - WriteTree.prototype.childWrites = function (path) { - return new WriteTreeRef(path, this); - }; - /** - * Record a new overwrite from user code. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} writeId - * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches - */ - WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) { - util.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones'); - if (visible === undefined) { - visible = true; - } - this.allWrites_.push({ - path: path, - snap: snap, - writeId: writeId, - visible: visible - }); - if (visible) { - this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap); - } - this.lastWriteId_ = writeId; - }; - /** - * Record a new merge from user code. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - */ - WriteTree.prototype.addMerge = function (path, changedChildren, writeId) { - util.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones'); - this.allWrites_.push({ - path: path, - children: changedChildren, - writeId: writeId, - visible: true - }); - this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren); - this.lastWriteId_ = writeId; - }; - /** - * @param {!number} writeId - * @return {?WriteRecord} - */ - WriteTree.prototype.getWrite = function (writeId) { - for (var i = 0; i < this.allWrites_.length; i++) { - var record = this.allWrites_[i]; - if (record.writeId === writeId) { - return record; - } - } - return null; - }; - /** - * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates - * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. - * - * @param {!number} writeId - * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise - * events as a result). - */ - WriteTree.prototype.removeWrite = function (writeId) { - // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied - // out of order. - //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; - //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); - var _this = this; - var idx = this.allWrites_.findIndex(function (s) { - return s.writeId === writeId; - }); - util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); - var writeToRemove = this.allWrites_[idx]; - this.allWrites_.splice(idx, 1); - var removedWriteWasVisible = writeToRemove.visible; - var removedWriteOverlapsWithOtherWrites = false; - var i = this.allWrites_.length - 1; - while (removedWriteWasVisible && i >= 0) { - var currentWrite = this.allWrites_[i]; - if (currentWrite.visible) { - if (i >= idx && - this.recordContainsPath_(currentWrite, writeToRemove.path)) { - // The removed write was completely shadowed by a subsequent write. - removedWriteWasVisible = false; - } - else if (writeToRemove.path.contains(currentWrite.path)) { - // Either we're covering some writes or they're covering part of us (depending on which came first). - removedWriteOverlapsWithOtherWrites = true; - } - } - i--; - } - if (!removedWriteWasVisible) { - return false; - } - else if (removedWriteOverlapsWithOtherWrites) { - // There's some shadowing going on. Just rebuild the visible writes from scratch. - this.resetTree_(); - return true; - } - else { - // There's no shadowing. We can safely just remove the write(s) from visibleWrites. - if (writeToRemove.snap) { - this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path); - } - else { - var children = writeToRemove.children; - util.forEach(children, function (childName) { - _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName)); - }); - } - return true; - } - }; - /** - * Return a complete snapshot for the given path if there's visible write data at that path, else null. - * No server data is considered. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTree.prototype.getCompleteWriteData = function (path) { - return this.visibleWrites_.getCompleteNode(path); - }; - /** - * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden - * writes), attempt to calculate a complete snapshot for the given path - * - * @param {!Path} treePath - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude An optional set to be excluded - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { - if (!writeIdsToExclude && !includeHiddenWrites) { - var shadowingNode = this.visibleWrites_.getCompleteNode(treePath); - if (shadowingNode != null) { - return shadowingNode; - } - else { - var subMerge = this.visibleWrites_.childCompoundWrite(treePath); - if (subMerge.isEmpty()) { - return completeServerCache; - } - else if (completeServerCache == null && - !subMerge.hasCompleteWrite(Path.Empty)) { - // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow - return null; - } - else { - var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; - return subMerge.apply(layeredCache); - } - } - } - else { - var merge = this.visibleWrites_.childCompoundWrite(treePath); - if (!includeHiddenWrites && merge.isEmpty()) { - return completeServerCache; - } - else { - // If the server cache is null, and we don't have a complete cache, we need to return null - if (!includeHiddenWrites && - completeServerCache == null && - !merge.hasCompleteWrite(Path.Empty)) { - return null; - } - else { - var filter = function (write) { - return ((write.visible || includeHiddenWrites) && - (!writeIdsToExclude || - !~writeIdsToExclude.indexOf(write.writeId)) && - (write.path.contains(treePath) || treePath.contains(write.path))); - }; - var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath); - var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; - return mergeAtPath.apply(layeredCache); - } - } - } - }; - /** - * With optional, underlying server data, attempt to return a children node of children that we have complete data for. - * Used when creating new views, to pre-fill their complete event children snapshot. - * - * @param {!Path} treePath - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) { - var completeChildren = ChildrenNode.EMPTY_NODE; - var topLevelSet = this.visibleWrites_.getCompleteNode(treePath); - if (topLevelSet) { - if (!topLevelSet.isLeafNode()) { - // we're shadowing everything. Return the children. - topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) { - completeChildren = completeChildren.updateImmediateChild(childName, childSnap); - }); - } - return completeChildren; - } - else if (completeServerChildren) { - // Layer any children we have on top of this - // We know we don't have a top-level set, so just enumerate existing children - var merge_1 = this.visibleWrites_.childCompoundWrite(treePath); - completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - var node = merge_1 - .childCompoundWrite(new Path(childName)) - .apply(childNode); - completeChildren = completeChildren.updateImmediateChild(childName, node); - }); - // Add any complete children we have from the set - merge_1.getCompleteChildren().forEach(function (namedNode) { - completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); - }); - return completeChildren; - } - else { - // We don't have anything to layer on top of. Layer on any children we have - // Note that we can return an empty snap if we have a defined delete - var merge = this.visibleWrites_.childCompoundWrite(treePath); - merge.getCompleteChildren().forEach(function (namedNode) { - completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); - }); - return completeChildren; - } - }; - /** - * Given that the underlying server data has updated, determine what, if anything, needs to be - * applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events - * - * Either existingEventSnap or existingServerSnap must exist - * - * @param {!Path} treePath - * @param {!Path} childPath - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) { - util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); - var path = treePath.child(childPath); - if (this.visibleWrites_.hasCompleteWrite(path)) { - // At this point we can probably guarantee that we're in case 2, meaning no events - // May need to check visibility while doing the findRootMostValueAndPath call - return null; - } - else { - // No complete shadowing. We're either partially shadowing or not shadowing at all. - var childMerge = this.visibleWrites_.childCompoundWrite(path); - if (childMerge.isEmpty()) { - // We're not shadowing at all. Case 1 - return existingServerSnap.getChild(childPath); - } - else { - // This could be more efficient if the serverNode + updates doesn't change the eventSnap - // However this is tricky to find out, since user updates don't necessary change the server - // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server - // adds nodes, but doesn't change any existing writes. It is therefore not enough to - // only check if the updates change the serverNode. - // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? - return childMerge.apply(existingServerSnap.getChild(childPath)); - } - } - }; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!Path} treePath - * @param {!string} childKey - * @param {!CacheNode} existingServerSnap - * @return {?Node} - */ - WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) { - var path = treePath.child(childKey); - var shadowingNode = this.visibleWrites_.getCompleteNode(path); - if (shadowingNode != null) { - return shadowingNode; - } - else { - if (existingServerSnap.isCompleteForChild(childKey)) { - var childMerge = this.visibleWrites_.childCompoundWrite(path); - return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey)); - } - else { - return null; - } - } - }; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTree.prototype.shadowingWrite = function (path) { - return this.visibleWrites_.getCompleteNode(path); - }; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window. - * - * @param {!Path} treePath - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) { - var toIterate; - var merge = this.visibleWrites_.childCompoundWrite(treePath); - var shadowingNode = merge.getCompleteNode(Path.Empty); - if (shadowingNode != null) { - toIterate = shadowingNode; - } - else if (completeServerData != null) { - toIterate = merge.apply(completeServerData); - } - else { - // no children to iterate on - return []; - } - toIterate = toIterate.withIndex(index); - if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { - var nodes = []; - var cmp = index.getCompare(); - var iter = reverse - ? toIterate.getReverseIteratorFrom(startPost, index) - : toIterate.getIteratorFrom(startPost, index); - var next = iter.getNext(); - while (next && nodes.length < count) { - if (cmp(next, startPost) !== 0) { - nodes.push(next); - } - next = iter.getNext(); - } - return nodes; - } - else { - return []; - } - }; - /** - * @param {!WriteRecord} writeRecord - * @param {!Path} path - * @return {boolean} - * @private - */ - WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) { - if (writeRecord.snap) { - return writeRecord.path.contains(path); - } - else { - // findKey can return undefined, so use !! to coerce to boolean - return !!util.findKey(writeRecord.children, function (childSnap, childName) { - return writeRecord.path.child(childName).contains(path); - }); - } - }; - /** - * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots - * @private - */ - WriteTree.prototype.resetTree_ = function () { - this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path.Empty); - if (this.allWrites_.length > 0) { - this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId; - } - else { - this.lastWriteId_ = -1; - } - }; - /** - * The default filter used when constructing the tree. Keep everything that's visible. - * - * @param {!WriteRecord} write - * @return {boolean} - * @private - */ - WriteTree.DefaultFilter_ = function (write) { - return write.visible; - }; - /** - * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of - * event data at that path. - * - * @param {!Array.} writes - * @param {!function(!WriteRecord):boolean} filter - * @param {!Path} treeRoot - * @return {!CompoundWrite} - * @private - */ - WriteTree.layerTree_ = function (writes, filter, treeRoot) { - var compoundWrite = CompoundWrite.Empty; - for (var i = 0; i < writes.length; ++i) { - var write = writes[i]; - // Theory, a later set will either: - // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction - // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction - if (filter(write)) { - var writePath = write.path; - var relativePath = void 0; - if (write.snap) { - if (treeRoot.contains(writePath)) { - relativePath = Path.relativePath(treeRoot, writePath); - compoundWrite = compoundWrite.addWrite(relativePath, write.snap); - } - else if (writePath.contains(treeRoot)) { - relativePath = Path.relativePath(writePath, treeRoot); - compoundWrite = compoundWrite.addWrite(Path.Empty, write.snap.getChild(relativePath)); - } - else { - // There is no overlap between root path and write path, ignore write - } - } - else if (write.children) { - if (treeRoot.contains(writePath)) { - relativePath = Path.relativePath(treeRoot, writePath); - compoundWrite = compoundWrite.addWrites(relativePath, write.children); - } - else if (writePath.contains(treeRoot)) { - relativePath = Path.relativePath(writePath, treeRoot); - if (relativePath.isEmpty()) { - compoundWrite = compoundWrite.addWrites(Path.Empty, write.children); - } - else { - var child = util.safeGet(write.children, relativePath.getFront()); - if (child) { - // There exists a child in this node that matches the root path - var deepNode = child.getChild(relativePath.popFront()); - compoundWrite = compoundWrite.addWrite(Path.Empty, deepNode); - } - } - } - else { - // There is no overlap between root path and write path, ignore write - } - } - else { - throw util.assertionError('WriteRecord should have .snap or .children'); - } - } - } - return compoundWrite; - }; - return WriteTree; -}()); -/** - * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods - * just proxy to the underlying WriteTree. - * - * @constructor - */ -var WriteTreeRef = /** @class */ (function () { - /** - * @param {!Path} path - * @param {!WriteTree} writeTree - */ - function WriteTreeRef(path, writeTree) { - this.treePath_ = path; - this.writeTree_ = writeTree; - } - /** - * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used - * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node - * can lead to a more expensive calculation. - * - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude Optional writes to exclude. - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) { - return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites); - }; - /** - * If possible, returns a children node containing all of the complete children we have data for. The returned data is a - * mix of the given server data and write data. - * - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) { - return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren); - }; - /** - * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, - * if anything, needs to be applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events should be raised - * - * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert - * - * @param {!Path} path - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) { - return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap); - }; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTreeRef.prototype.shadowingWrite = function (path) { - return this.writeTree_.shadowingWrite(this.treePath_.child(path)); - }; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window - * - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) { - return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index); - }; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!string} childKey - * @param {!CacheNode} existingServerCache - * @return {?Node} - */ - WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) { - return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache); - }; - /** - * Return a WriteTreeRef for a child. - * - * @param {string} childName - * @return {!WriteTreeRef} - */ - WriteTreeRef.prototype.child = function (childName) { - return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_); - }; - return WriteTreeRef; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SyncTree is the central class for managing event callback registration, data caching, views - * (query processing), and event generation. There are typically two SyncTree instances for - * each Repo, one for the normal Firebase data, and one for the .info data. - * - * It has a number of responsibilities, including: - * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). - * - Applying and caching data changes for user set(), transaction(), and update() calls - * (applyUserOverwrite(), applyUserMerge()). - * - Applying and caching data changes for server data changes (applyServerOverwrite(), - * applyServerMerge()). - * - Generating user-facing events for server and user changes (all of the apply* methods - * return the set of events that need to be raised as a result). - * - Maintaining the appropriate set of server listens to ensure we are always subscribed - * to the correct set of paths and queries to satisfy the current set of user event - * callbacks (listens are started/stopped using the provided listenProvider). - * - * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual - * events are returned to the caller rather than raised synchronously. - * - * @constructor - */ -var SyncTree = /** @class */ (function () { - /** - * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening - * to server data. - */ - function SyncTree(listenProvider_) { - this.listenProvider_ = listenProvider_; - /** - * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. - * @type {!ImmutableTree.} - * @private - */ - this.syncPointTree_ = ImmutableTree.Empty; - /** - * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). - * @type {!WriteTree} - * @private - */ - this.pendingWriteTree_ = new WriteTree(); - this.tagToQueryMap_ = {}; - this.queryToTagMap_ = {}; - } - /** - * Apply the data changes for a user-generated set() or transaction() call. - * - * @param {!Path} path - * @param {!Node} newData - * @param {number} writeId - * @param {boolean=} visible - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) { - // Record pending write. - this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible); - if (!visible) { - return []; - } - else { - return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.User, path, newData)); - } - }; - /** - * Apply the data from a user-generated update() call - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) { - // Record pending merge. - this.pendingWriteTree_.addMerge(path, changedChildren, writeId); - var changeTree = ImmutableTree.fromObject(changedChildren); - return this.applyOperationToSyncPoints_(new Merge(OperationSource.User, path, changeTree)); - }; - /** - * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). - * - * @param {!number} writeId - * @param {boolean=} revert True if the given write failed and needs to be reverted - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.ackUserWrite = function (writeId, revert) { - if (revert === void 0) { revert = false; } - var write = this.pendingWriteTree_.getWrite(writeId); - var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId); - if (!needToReevaluate) { - return []; - } - else { - var affectedTree_1 = ImmutableTree.Empty; - if (write.snap != null) { - // overwrite - affectedTree_1 = affectedTree_1.set(Path.Empty, true); - } - else { - util.forEach(write.children, function (pathString, node) { - affectedTree_1 = affectedTree_1.set(new Path(pathString), node); - }); - } - return this.applyOperationToSyncPoints_(new AckUserWrite(write.path, affectedTree_1, revert)); - } - }; - /** - * Apply new server data for the specified path.. - * - * @param {!Path} path - * @param {!Node} newData - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyServerOverwrite = function (path, newData) { - return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.Server, path, newData)); - }; - /** - * Apply new server data to be merged in at the specified path. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyServerMerge = function (path, changedChildren) { - var changeTree = ImmutableTree.fromObject(changedChildren); - return this.applyOperationToSyncPoints_(new Merge(OperationSource.Server, path, changeTree)); - }; - /** - * Apply a listen complete for a query - * - * @param {!Path} path - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyListenComplete = function (path) { - return this.applyOperationToSyncPoints_(new ListenComplete(OperationSource.Server, path)); - }; - /** - * Apply new server data for the specified tagged query. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey != null) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var op = new Overwrite(OperationSource.forServerTaggedQuery(queryId), relativePath, snap); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // Query must have been removed already - return []; - } - }; - /** - * Apply server data to be merged in for the specified tagged query. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var changeTree = ImmutableTree.fromObject(changedChildren); - var op = new Merge(OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // We've already removed the query. No big deal, ignore the update - return []; - } - }; - /** - * Apply a listen complete for a tagged query - * - * @param {!Path} path - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedListenComplete = function (path, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var op = new ListenComplete(OperationSource.forServerTaggedQuery(queryId), relativePath); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // We've already removed the query. No big deal, ignore the update - return []; - } - }; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.addEventRegistration = function (query, eventRegistration) { - var path = query.path; - var serverCache = null; - var foundAncestorDefaultView = false; - // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. - // Consider optimizing this once there's a better understanding of what actual behavior will be. - this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) { - var relativePath = Path.relativePath(pathToSyncPoint, path); - serverCache = serverCache || sp.getCompleteServerCache(relativePath); - foundAncestorDefaultView = - foundAncestorDefaultView || sp.hasCompleteView(); - }); - var syncPoint = this.syncPointTree_.get(path); - if (!syncPoint) { - syncPoint = new SyncPoint(); - this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint); - } - else { - foundAncestorDefaultView = - foundAncestorDefaultView || syncPoint.hasCompleteView(); - serverCache = serverCache || syncPoint.getCompleteServerCache(Path.Empty); - } - var serverCacheComplete; - if (serverCache != null) { - serverCacheComplete = true; - } - else { - serverCacheComplete = false; - serverCache = ChildrenNode.EMPTY_NODE; - var subtree = this.syncPointTree_.subtree(path); - subtree.foreachChild(function (childName, childSyncPoint) { - var completeCache = childSyncPoint.getCompleteServerCache(Path.Empty); - if (completeCache) { - serverCache = serverCache.updateImmediateChild(childName, completeCache); - } - }); - } - var viewAlreadyExists = syncPoint.viewExistsForQuery(query); - if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) { - // We need to track a tag for this query - var queryKey = SyncTree.makeQueryKey_(query); - util.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag'); - var tag = SyncTree.getNextQueryTag_(); - this.queryToTagMap_[queryKey] = tag; - // Coerce to string to avoid sparse arrays. - this.tagToQueryMap_['_' + tag] = queryKey; - } - var writesCache = this.pendingWriteTree_.childWrites(path); - var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete); - if (!viewAlreadyExists && !foundAncestorDefaultView) { - var view /** @type !View */ = syncPoint.viewForQuery(query); - events = events.concat(this.setupListener_(query, view)); - } - return events; - }; - /** - * Remove event callback(s). - * - * If query is the default query, we'll check all queries for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, all callbacks are removed. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) { - var _this = this; - // Find the syncPoint first. Then deal with whether or not it has matching listeners - var path = query.path; - var maybeSyncPoint = this.syncPointTree_.get(path); - var cancelEvents = []; - // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without - // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and - // not loadsAllData(). - if (maybeSyncPoint && - (query.queryIdentifier() === 'default' || - maybeSyncPoint.viewExistsForQuery(query))) { - /** - * @type {{removed: !Array., events: !Array.}} - */ - var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError); - if (maybeSyncPoint.isEmpty()) { - this.syncPointTree_ = this.syncPointTree_.remove(path); - } - var removed = removedAndEvents.removed; - cancelEvents = removedAndEvents.events; - // We may have just removed one of many listeners and can short-circuit this whole process - // We may also not have removed a default listener, in which case all of the descendant listeners should already be - // properly set up. - // - // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of - // queryId === 'default' - var removingDefault = -1 !== - removed.findIndex(function (query) { - return query.getQueryParams().loadsAllData(); - }); - var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) { - return parentSyncPoint.hasCompleteView(); - }); - if (removingDefault && !covered) { - var subtree = this.syncPointTree_.subtree(path); - // There are potentially child listeners. Determine what if any listens we need to send before executing the - // removal - if (!subtree.isEmpty()) { - // We need to fold over our subtree and collect the listeners to send - var newViews = this.collectDistinctViewsForSubTree_(subtree); - // Ok, we've collected all the listens we need. Set them up. - for (var i = 0; i < newViews.length; ++i) { - var view = newViews[i], newQuery = view.getQuery(); - var listener = this.createListenerForView_(view); - this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete); - } - } - else { - // There's nothing below us, so nothing we need to start listening on - } - } - // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query - // The above block has us covered in terms of making sure we're set up on listens lower in the tree. - // Also, note that if we have a cancelError, it's already been removed at the provider level. - if (!covered && removed.length > 0 && !cancelError) { - // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one - // default. Otherwise, we need to iterate through and cancel each individual query - if (removingDefault) { - // We don't tag default listeners - var defaultTag = null; - this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag); - } - else { - removed.forEach(function (queryToRemove) { - var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)]; - _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove); - }); - } - } - // Now, clear all of the tags we're tracking for the removed listens - this.removeTags_(removed); - } - else { - // No-op, this listener must've been already removed - } - return cancelEvents; - }; - /** - * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above - * it, but as this is only used by transaction code, that should always be the case anyways. - * - * Note: this method will *include* hidden writes from transaction with applyLocally set to false. - * @param {!Path} path The path to the data we want - * @param {Array.=} writeIdsToExclude A specific set to be excluded - * @return {?Node} - */ - SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) { - var includeHiddenSets = true; - var writeTree = this.pendingWriteTree_; - var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) { - var relativePath = Path.relativePath(pathSoFar, path); - var serverCache = syncPoint.getCompleteServerCache(relativePath); - if (serverCache) { - return serverCache; - } - }); - return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets); - }; - /** - * This collapses multiple unfiltered views into a single view, since we only need a single - * listener for them. - * - * @param {!ImmutableTree.} subtree - * @return {!Array.} - * @private - */ - SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) { - return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) { - if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) { - var completeView = maybeChildSyncPoint.getCompleteView(); - return [completeView]; - } - else { - // No complete view here, flatten any deeper listens into an array - var views_1 = []; - if (maybeChildSyncPoint) { - views_1 = maybeChildSyncPoint.getQueryViews(); - } - util.forEach(childMap, function (key, childViews) { - views_1 = views_1.concat(childViews); - }); - return views_1; - } - }); - }; - /** - * @param {!Array.} queries - * @private - */ - SyncTree.prototype.removeTags_ = function (queries) { - for (var j = 0; j < queries.length; ++j) { - var removedQuery = queries[j]; - if (!removedQuery.getQueryParams().loadsAllData()) { - // We should have a tag for this - var removedQueryKey = SyncTree.makeQueryKey_(removedQuery); - var removedQueryTag = this.queryToTagMap_[removedQueryKey]; - delete this.queryToTagMap_[removedQueryKey]; - delete this.tagToQueryMap_['_' + removedQueryTag]; - } - } - }; - /** - * Normalizes a query to a query we send the server for listening - * @param {!Query} query - * @return {!Query} The normalized query - * @private - */ - SyncTree.queryForListening_ = function (query) { - if (query.getQueryParams().loadsAllData() && - !query.getQueryParams().isDefault()) { - // We treat queries that load all data as default queries - // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits - // from Query - return /** @type {!Query} */ query.getRef(); - } - else { - return query; - } - }; - /** - * For a given new listen, manage the de-duplication of outstanding subscriptions. - * - * @param {!Query} query - * @param {!View} view - * @return {!Array.} This method can return events to support synchronous data sources - * @private - */ - SyncTree.prototype.setupListener_ = function (query, view) { - var path = query.path; - var tag = this.tagForQuery_(query); - var listener = this.createListenerForView_(view); - var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete); - var subtree = this.syncPointTree_.subtree(path); - // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we - // may need to shadow other listens as well. - if (tag) { - util.assert(!subtree.value.hasCompleteView(), "If we're adding a query, it shouldn't be shadowed"); - } - else { - // Shadow everything at or below this location, this is a default listener. - var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) { - if (!relativePath.isEmpty() && - maybeChildSyncPoint && - maybeChildSyncPoint.hasCompleteView()) { - return [maybeChildSyncPoint.getCompleteView().getQuery()]; - } - else { - // No default listener here, flatten any deeper queries into an array - var queries_1 = []; - if (maybeChildSyncPoint) { - queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); })); - } - util.forEach(childMap, function (key, childQueries) { - queries_1 = queries_1.concat(childQueries); - }); - return queries_1; - } - }); - for (var i = 0; i < queriesToStop.length; ++i) { - var queryToStop = queriesToStop[i]; - this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop)); - } - } - return events; - }; - /** - * - * @param {!View} view - * @return {{hashFn: function(), onComplete: function(!string, *)}} - * @private - */ - SyncTree.prototype.createListenerForView_ = function (view) { - var _this = this; - var query = view.getQuery(); - var tag = this.tagForQuery_(query); - return { - hashFn: function () { - var cache = view.getServerCache() || ChildrenNode.EMPTY_NODE; - return cache.hash(); - }, - onComplete: function (status) { - if (status === 'ok') { - if (tag) { - return _this.applyTaggedListenComplete(query.path, tag); - } - else { - return _this.applyListenComplete(query.path); - } - } - else { - // If a listen failed, kill all of the listeners here, not just the one that triggered the error. - // Note that this may need to be scoped to just this listener if we change permissions on filtered children - var error$$1 = errorForServerCode(status, query); - return _this.removeEventRegistration(query, - /*eventRegistration*/ null, error$$1); - } - } - }; - }; - /** - * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. - * @private - * @param {!Query} query - * @return {string} - */ - SyncTree.makeQueryKey_ = function (query) { - return query.path.toString() + '$' + query.queryIdentifier(); - }; - /** - * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. - * @private - * @param {!string} queryKey - * @return {{queryId: !string, path: !Path}} - */ - SyncTree.parseQueryKey_ = function (queryKey) { - var splitIndex = queryKey.indexOf('$'); - util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); - return { - queryId: queryKey.substr(splitIndex + 1), - path: new Path(queryKey.substr(0, splitIndex)) - }; - }; - /** - * Return the query associated with the given tag, if we have one - * @param {!number} tag - * @return {?string} - * @private - */ - SyncTree.prototype.queryKeyForTag_ = function (tag) { - return this.tagToQueryMap_['_' + tag]; - }; - /** - * Return the tag associated with the given query. - * @param {!Query} query - * @return {?number} - * @private - */ - SyncTree.prototype.tagForQuery_ = function (query) { - var queryKey = SyncTree.makeQueryKey_(query); - return util.safeGet(this.queryToTagMap_, queryKey); - }; - /** - * Static accessor for query tags. - * @return {number} - * @private - */ - SyncTree.getNextQueryTag_ = function () { - return SyncTree.nextQueryTag_++; - }; - /** - * A helper method to apply tagged operations - * - * @param {!Path} queryPath - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) { - var syncPoint = this.syncPointTree_.get(queryPath); - util.assert(syncPoint, "Missing sync point for query tag that we're tracking"); - var writesCache = this.pendingWriteTree_.childWrites(queryPath); - return syncPoint.applyOperation(operation, writesCache, - /*serverCache=*/ null); - }; - /** - * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. - * - * NOTES: - * - Descendant SyncPoints will be visited first (since we raise events depth-first). - - * - We call applyOperation() on each SyncPoint passing three things: - * 1. A version of the Operation that has been made relative to the SyncPoint location. - * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. - * 3. A snapshot Node with cached server data, if we have it. - - * - We concatenate all of the events returned by each SyncPoint and return the result. - * - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) { - return this.applyOperationHelper_(operation, this.syncPointTree_, - /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path.Empty)); - }; - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) { - if (operation.path.isEmpty()) { - return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); - } - else { - var syncPoint = syncPointTree.get(Path.Empty); - // If we don't have cached server data, see if we can get it from this SyncPoint. - if (serverCache == null && syncPoint != null) { - serverCache = syncPoint.getCompleteServerCache(Path.Empty); - } - var events = []; - var childName = operation.path.getFront(); - var childOperation = operation.operationForChild(childName); - var childTree = syncPointTree.children.get(childName); - if (childTree && childOperation) { - var childServerCache = serverCache - ? serverCache.getImmediateChild(childName) - : null; - var childWritesCache = writesCache.child(childName); - events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); - } - if (syncPoint) { - events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache)); - } - return events; - } - }; - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) { - var _this = this; - var syncPoint = syncPointTree.get(Path.Empty); - // If we don't have cached server data, see if we can get it from this SyncPoint. - if (serverCache == null && syncPoint != null) { - serverCache = syncPoint.getCompleteServerCache(Path.Empty); - } - var events = []; - syncPointTree.children.inorderTraversal(function (childName, childTree) { - var childServerCache = serverCache - ? serverCache.getImmediateChild(childName) - : null; - var childWritesCache = writesCache.child(childName); - var childOperation = operation.operationForChild(childName); - if (childOperation) { - events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); - } - }); - if (syncPoint) { - events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache)); - } - return events; - }; - /** - * Static tracker for next query tag. - * @type {number} - * @private - */ - SyncTree.nextQueryTag_ = 1; - return SyncTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Mutable object which basically just stores a reference to the "latest" immutable snapshot. - * - * @constructor - */ -var SnapshotHolder = /** @class */ (function () { - function SnapshotHolder() { - this.rootNode_ = ChildrenNode.EMPTY_NODE; - } - SnapshotHolder.prototype.getNode = function (path) { - return this.rootNode_.getChild(path); - }; - SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) { - this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); - }; - return SnapshotHolder; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Abstraction around FirebaseApp's token fetching capabilities. - */ -var AuthTokenProvider = /** @class */ (function () { - /** - * @param {!FirebaseApp} app_ - */ - function AuthTokenProvider(app_) { - this.app_ = app_; - } - /** - * @param {boolean} forceRefresh - * @return {!Promise} - */ - AuthTokenProvider.prototype.getToken = function (forceRefresh) { - return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, - // .catch - function (error$$1) { - // TODO: Need to figure out all the cases this is raised and whether - // this makes sense. - if (error$$1 && error$$1.code === 'auth/token-not-initialized') { - log('Got auth/token-not-initialized error. Treating as null token.'); - return null; - } - else { - return Promise.reject(error$$1); - } - }); - }; - AuthTokenProvider.prototype.addTokenChangeListener = function (listener) { - // TODO: We might want to wrap the listener and call it with no args to - // avoid a leaky abstraction, but that makes removing the listener harder. - this.app_['INTERNAL']['addAuthTokenListener'](listener); - }; - AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) { - this.app_['INTERNAL']['removeAuthTokenListener'](listener); - }; - AuthTokenProvider.prototype.notifyForInvalidToken = function () { - var errorMessage = 'Provided authentication credentials for the app named "' + - this.app_.name + - '" are invalid. This usually indicates your app was not ' + - 'initialized correctly. '; - if ('credential' in this.app_.options) { - errorMessage += - 'Make sure the "credential" property provided to initializeApp() ' + - 'is authorized to access the specified "databaseURL" and is from the correct ' + - 'project.'; - } - else if ('serviceAccount' in this.app_.options) { - errorMessage += - 'Make sure the "serviceAccount" property provided to initializeApp() ' + - 'is authorized to access the specified "databaseURL" and is from the correct ' + - 'project.'; - } - else { - errorMessage += - 'Make sure the "apiKey" and "databaseURL" properties provided to ' + - 'initializeApp() match the values provided for your app at ' + - 'https://console.firebase.google.com/.'; - } - warn(errorMessage); - }; - return AuthTokenProvider; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Tracks a collection of stats. - * - * @constructor - */ -var StatsCollection = /** @class */ (function () { - function StatsCollection() { - this.counters_ = {}; - } - StatsCollection.prototype.incrementCounter = function (name, amount) { - if (amount === void 0) { amount = 1; } - if (!util.contains(this.counters_, name)) - this.counters_[name] = 0; - this.counters_[name] += amount; - }; - StatsCollection.prototype.get = function () { - return util.deepCopy(this.counters_); - }; - return StatsCollection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var StatsManager = /** @class */ (function () { - function StatsManager() { - } - StatsManager.getCollection = function (repoInfo) { - var hashString = repoInfo.toString(); - if (!this.collections_[hashString]) { - this.collections_[hashString] = new StatsCollection(); - } - return this.collections_[hashString]; - }; - StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) { - var hashString = repoInfo.toString(); - if (!this.reporters_[hashString]) { - this.reporters_[hashString] = creatorFunction(); - } - return this.reporters_[hashString]; - }; - StatsManager.collections_ = {}; - StatsManager.reporters_ = {}; - return StatsManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns the delta from the previous call to get stats. - * - * @param collection_ The collection to "listen" to. - * @constructor - */ -var StatsListener = /** @class */ (function () { - function StatsListener(collection_) { - this.collection_ = collection_; - this.last_ = null; - } - StatsListener.prototype.get = function () { - var newStats = this.collection_.get(); - var delta = util.clone(newStats); - if (this.last_) { - util.forEach(this.last_, function (stat, value) { - delta[stat] = delta[stat] - value; - }); - } - this.last_ = newStats; - return delta; - }; - return StatsListener; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably -// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 -// seconds to try to ensure the Firebase connection is established / settled. -var FIRST_STATS_MIN_TIME = 10 * 1000; -var FIRST_STATS_MAX_TIME = 30 * 1000; -// We'll continue to report stats on average every 5 minutes. -var REPORT_STATS_INTERVAL = 5 * 60 * 1000; -/** - * @constructor - */ -var StatsReporter = /** @class */ (function () { - /** - * @param collection - * @param server_ - */ - function StatsReporter(collection, server_) { - this.server_ = server_; - this.statsToReport_ = {}; - this.statsListener_ = new StatsListener(collection); - var timeout = FIRST_STATS_MIN_TIME + - (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); - setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); - } - StatsReporter.prototype.includeStat = function (stat) { - this.statsToReport_[stat] = true; - }; - StatsReporter.prototype.reportStats_ = function () { - var _this = this; - var stats = this.statsListener_.get(); - var reportedStats = {}; - var haveStatsToReport = false; - util.forEach(stats, function (stat, value) { - if (value > 0 && util.contains(_this.statsToReport_, stat)) { - reportedStats[stat] = value; - haveStatsToReport = true; - } - }); - if (haveStatsToReport) { - this.server_.reportStats(reportedStats); - } - // queue our next run. - setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); - }; - return StatsReporter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * The event queue serves a few purposes: - * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more - * events being queued. - * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, - * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call - * left off, ensuring that the events are still raised synchronously and in order. - * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued - * events are raised synchronously. - * - * NOTE: This can all go away if/when we move to async events. - * - * @constructor - */ -var EventQueue = /** @class */ (function () { - function EventQueue() { - /** - * @private - * @type {!Array.} - */ - this.eventLists_ = []; - /** - * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. - * @private - * @type {!number} - */ - this.recursionDepth_ = 0; - } - /** - * @param {!Array.} eventDataList The new events to queue. - */ - EventQueue.prototype.queueEvents = function (eventDataList) { - // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. - var currList = null; - for (var i = 0; i < eventDataList.length; i++) { - var eventData = eventDataList[i]; - var eventPath = eventData.getPath(); - if (currList !== null && !eventPath.equals(currList.getPath())) { - this.eventLists_.push(currList); - currList = null; - } - if (currList === null) { - currList = new EventList(eventPath); - } - currList.add(eventData); - } - if (currList) { - this.eventLists_.push(currList); - } - }; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) - * for the specified path. - * - * It is assumed that the new events are all for the specified path. - * - * @param {!Path} path The path to raise events for. - * @param {!Array.} eventDataList The new events to raise. - */ - EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) { - this.queueEvents(eventDataList); - this.raiseQueuedEventsMatchingPredicate_(function (eventPath) { - return eventPath.equals(path); - }); - }; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) for - * locations related to the specified change path (i.e. all ancestors and descendants). - * - * It is assumed that the new events are all related (ancestor or descendant) to the specified path. - * - * @param {!Path} changedPath The path to raise events for. - * @param {!Array.} eventDataList The events to raise - */ - EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) { - this.queueEvents(eventDataList); - this.raiseQueuedEventsMatchingPredicate_(function (eventPath) { - return eventPath.contains(changedPath) || changedPath.contains(eventPath); - }); - }; - /** - * @param {!function(!Path):boolean} predicate - * @private - */ - EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) { - this.recursionDepth_++; - var sentAll = true; - for (var i = 0; i < this.eventLists_.length; i++) { - var eventList = this.eventLists_[i]; - if (eventList) { - var eventPath = eventList.getPath(); - if (predicate(eventPath)) { - this.eventLists_[i].raise(); - this.eventLists_[i] = null; - } - else { - sentAll = false; - } - } - } - if (sentAll) { - this.eventLists_ = []; - } - this.recursionDepth_--; - }; - return EventQueue; -}()); -/** - * @param {!Path} path - * @constructor - */ -var EventList = /** @class */ (function () { - function EventList(path_) { - this.path_ = path_; - /** - * @type {!Array.} - * @private - */ - this.events_ = []; - } - /** - * @param {!Event} eventData - */ - EventList.prototype.add = function (eventData) { - this.events_.push(eventData); - }; - /** - * Iterates through the list and raises each event - */ - EventList.prototype.raise = function () { - for (var i = 0; i < this.events_.length; i++) { - var eventData = this.events_[i]; - if (eventData !== null) { - this.events_[i] = null; - var eventFn = eventData.getEventRunner(); - if (logger$1) { - log('event: ' + eventData.toString()); - } - exceptionGuard(eventFn); - } - } - }; - /** - * @return {!Path} - */ - EventList.prototype.getPath = function () { - return this.path_; - }; - return EventList; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Base class to be used if you want to emit events. Call the constructor with - * the set of allowed event names. - */ -var EventEmitter = /** @class */ (function () { - /** - * @param {!Array.} allowedEvents_ - */ - function EventEmitter(allowedEvents_) { - this.allowedEvents_ = allowedEvents_; - this.listeners_ = {}; - util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); - } - /** - * To be called by derived classes to trigger events. - * @param {!string} eventType - * @param {...*} var_args - */ - EventEmitter.prototype.trigger = function (eventType) { - var var_args = []; - for (var _i = 1; _i < arguments.length; _i++) { - var_args[_i - 1] = arguments[_i]; - } - if (Array.isArray(this.listeners_[eventType])) { - // Clone the list, since callbacks could add/remove listeners. - var listeners = this.listeners_[eventType].slice(); - for (var i = 0; i < listeners.length; i++) { - listeners[i].callback.apply(listeners[i].context, var_args); - } - } - }; - EventEmitter.prototype.on = function (eventType, callback, context) { - this.validateEventType_(eventType); - this.listeners_[eventType] = this.listeners_[eventType] || []; - this.listeners_[eventType].push({ callback: callback, context: context }); - var eventData = this.getInitialEvent(eventType); - if (eventData) { - callback.apply(context, eventData); - } - }; - EventEmitter.prototype.off = function (eventType, callback, context) { - this.validateEventType_(eventType); - var listeners = this.listeners_[eventType] || []; - for (var i = 0; i < listeners.length; i++) { - if (listeners[i].callback === callback && - (!context || context === listeners[i].context)) { - listeners.splice(i, 1); - return; - } - } - }; - EventEmitter.prototype.validateEventType_ = function (eventType) { - util.assert(this.allowedEvents_.find(function (et) { - return et === eventType; - }), 'Unknown event: ' + eventType); - }; - return EventEmitter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @extends {EventEmitter} - */ -var VisibilityMonitor = /** @class */ (function (_super) { - tslib_1.__extends(VisibilityMonitor, _super); - function VisibilityMonitor() { - var _this = _super.call(this, ['visible']) || this; - var hidden; - var visibilityChange; - if (typeof document !== 'undefined' && - typeof document.addEventListener !== 'undefined') { - if (typeof document['hidden'] !== 'undefined') { - // Opera 12.10 and Firefox 18 and later support - visibilityChange = 'visibilitychange'; - hidden = 'hidden'; - } - else if (typeof document['mozHidden'] !== 'undefined') { - visibilityChange = 'mozvisibilitychange'; - hidden = 'mozHidden'; - } - else if (typeof document['msHidden'] !== 'undefined') { - visibilityChange = 'msvisibilitychange'; - hidden = 'msHidden'; - } - else if (typeof document['webkitHidden'] !== 'undefined') { - visibilityChange = 'webkitvisibilitychange'; - hidden = 'webkitHidden'; - } - } - // Initially, we always assume we are visible. This ensures that in browsers - // without page visibility support or in cases where we are never visible - // (e.g. chrome extension), we act as if we are visible, i.e. don't delay - // reconnects - _this.visible_ = true; - if (visibilityChange) { - document.addEventListener(visibilityChange, function () { - var visible = !document[hidden]; - if (visible !== _this.visible_) { - _this.visible_ = visible; - _this.trigger('visible', visible); - } - }, false); - } - return _this; - } - VisibilityMonitor.getInstance = function () { - return new VisibilityMonitor(); - }; - /** - * @param {!string} eventType - * @return {Array.} - */ - VisibilityMonitor.prototype.getInitialEvent = function (eventType) { - util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); - return [this.visible_]; - }; - return VisibilityMonitor; -}(EventEmitter)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Monitors online state (as reported by window.online/offline events). - * - * The expectation is that this could have many false positives (thinks we are online - * when we're not), but no false negatives. So we can safely use it to determine when - * we definitely cannot reach the internet. - * - * @extends {EventEmitter} - */ -var OnlineMonitor = /** @class */ (function (_super) { - tslib_1.__extends(OnlineMonitor, _super); - function OnlineMonitor() { - var _this = _super.call(this, ['online']) || this; - _this.online_ = true; - // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. - // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 - // It would seem that the 'online' event does not always fire consistently. So we disable it - // for Cordova. - if (typeof window !== 'undefined' && - typeof window.addEventListener !== 'undefined' && - !util.isMobileCordova()) { - window.addEventListener('online', function () { - if (!_this.online_) { - _this.online_ = true; - _this.trigger('online', true); - } - }, false); - window.addEventListener('offline', function () { - if (_this.online_) { - _this.online_ = false; - _this.trigger('online', false); - } - }, false); - } - return _this; - } - OnlineMonitor.getInstance = function () { - return new OnlineMonitor(); - }; - /** - * @param {!string} eventType - * @return {Array.} - */ - OnlineMonitor.prototype.getInitialEvent = function (eventType) { - util.assert(eventType === 'online', 'Unknown event type: ' + eventType); - return [this.online_]; - }; - /** - * @return {boolean} - */ - OnlineMonitor.prototype.currentlyOnline = function () { - return this.online_; - }; - return OnlineMonitor; -}(EventEmitter)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class ensures the packets from the server arrive in order - * This class takes data from the server and ensures it gets passed into the callbacks in order. - * @constructor - */ -var PacketReceiver = /** @class */ (function () { - /** - * @param onMessage_ - */ - function PacketReceiver(onMessage_) { - this.onMessage_ = onMessage_; - this.pendingResponses = []; - this.currentResponseNum = 0; - this.closeAfterResponse = -1; - this.onClose = null; - } - PacketReceiver.prototype.closeAfter = function (responseNum, callback) { - this.closeAfterResponse = responseNum; - this.onClose = callback; - if (this.closeAfterResponse < this.currentResponseNum) { - this.onClose(); - this.onClose = null; - } - }; - /** - * Each message from the server comes with a response number, and an array of data. The responseNumber - * allows us to ensure that we process them in the right order, since we can't be guaranteed that all - * browsers will respond in the same order as the requests we sent - * @param {number} requestNum - * @param {Array} data - */ - PacketReceiver.prototype.handleResponse = function (requestNum, data) { - var _this = this; - this.pendingResponses[requestNum] = data; - var _loop_1 = function () { - var toProcess = this_1.pendingResponses[this_1.currentResponseNum]; - delete this_1.pendingResponses[this_1.currentResponseNum]; - var _loop_2 = function (i) { - if (toProcess[i]) { - exceptionGuard(function () { - _this.onMessage_(toProcess[i]); - }); - } - }; - for (var i = 0; i < toProcess.length; ++i) { - _loop_2(i); - } - if (this_1.currentResponseNum === this_1.closeAfterResponse) { - if (this_1.onClose) { - this_1.onClose(); - this_1.onClose = null; - } - return "break"; - } - this_1.currentResponseNum++; - }; - var this_1 = this; - while (this.pendingResponses[this.currentResponseNum]) { - var state_1 = _loop_1(); - if (state_1 === "break") - break; - } - }; - return PacketReceiver; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// URL query parameters associated with longpolling -var FIREBASE_LONGPOLL_START_PARAM = 'start'; -var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; -var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; -var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; -var FIREBASE_LONGPOLL_ID_PARAM = 'id'; -var FIREBASE_LONGPOLL_PW_PARAM = 'pw'; -var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; -var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; -var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; -var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; -var FIREBASE_LONGPOLL_DATA_PARAM = 'd'; -var FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn'; -var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; -//Data size constants. -//TODO: Perf: the maximum length actually differs from browser to browser. -// We should check what browser we're on and set accordingly. -var MAX_URL_DATA_SIZE = 1870; -var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= -var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; -/** - * Keepalive period - * send a fresh request at minimum every 25 seconds. Opera has a maximum request - * length of 30 seconds that we can't exceed. - * @const - * @type {number} - */ -var KEEPALIVE_REQUEST_INTERVAL = 25000; -/** - * How long to wait before aborting a long-polling connection attempt. - * @const - * @type {number} - */ -var LP_CONNECT_TIMEOUT = 30000; -/** - * This class manages a single long-polling connection. - * - * @constructor - * @implements {Transport} - */ -var BrowserPollConnection = /** @class */ (function () { - /** - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing - * transport session - * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a - * connection previously - */ - function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) { - this.connId = connId; - this.repoInfo = repoInfo; - this.transportSessionId = transportSessionId; - this.lastSessionId = lastSessionId; - this.bytesSent = 0; - this.bytesReceived = 0; - this.everConnected_ = false; - this.log_ = logWrapper(connId); - this.stats_ = StatsManager.getCollection(repoInfo); - this.urlFn = function (params) { - return repoInfo.connectionURL(LONG_POLLING, params); - }; - } - /** - * - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) { - var _this = this; - this.curSegmentNum = 0; - this.onDisconnect_ = onDisconnect; - this.myPacketOrderer = new PacketReceiver(onMessage); - this.isClosed_ = false; - this.connectTimeoutTimer_ = setTimeout(function () { - _this.log_('Timed out trying to connect.'); - // Make sure we clear the host cache - _this.onClosed_(); - _this.connectTimeoutTimer_ = null; - }, Math.floor(LP_CONNECT_TIMEOUT)); - // Ensure we delay the creation of the iframe until the DOM is loaded. - executeWhenDOMReady(function () { - if (_this.isClosed_) - return; - //Set up a callback that gets triggered once a connection is set up. - _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var command = args[0], arg1 = args[1], arg2 = args[2]; - _this.incrementIncomingBytes_(args); - if (!_this.scriptTagHolder) - return; // we closed the connection. - if (_this.connectTimeoutTimer_) { - clearTimeout(_this.connectTimeoutTimer_); - _this.connectTimeoutTimer_ = null; - } - _this.everConnected_ = true; - if (command == FIREBASE_LONGPOLL_START_PARAM) { - _this.id = arg1; - _this.password = arg2; - } - else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { - // Don't clear the host cache. We got a response from the server, so we know it's reachable - if (arg1) { - // We aren't expecting any more data (other than what the server's already in the process of sending us - // through our already open polls), so don't send any more. - _this.scriptTagHolder.sendNewPolls = false; - // arg1 in this case is the last response number sent by the server. We should try to receive - // all of the responses up to this one before closing - _this.myPacketOrderer.closeAfter(arg1, function () { - _this.onClosed_(); - }); - } - else { - _this.onClosed_(); - } - } - else { - throw new Error('Unrecognized command received: ' + command); - } - }, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var pN = args[0], data = args[1]; - _this.incrementIncomingBytes_(args); - _this.myPacketOrderer.handleResponse(pN, data); - }, function () { - _this.onClosed_(); - }, _this.urlFn); - //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results - //from cache. - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); - if (_this.scriptTagHolder.uniqueCallbackIdentifier) - urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier; - urlParams[VERSION_PARAM] = PROTOCOL_VERSION; - if (_this.transportSessionId) { - urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId; - } - if (_this.lastSessionId) { - urlParams[LAST_SESSION_PARAM] = _this.lastSessionId; - } - if (!util.isNodeSdk() && - typeof location !== 'undefined' && - location.href && - location.href.indexOf(FORGE_DOMAIN) !== -1) { - urlParams[REFERER_PARAM] = FORGE_REF; - } - var connectURL = _this.urlFn(urlParams); - _this.log_('Connecting via long-poll to ' + connectURL); - _this.scriptTagHolder.addTag(connectURL, function () { - /* do nothing */ - }); - }); - }; - /** - * Call this when a handshake has completed successfully and we want to consider the connection established - */ - BrowserPollConnection.prototype.start = function () { - this.scriptTagHolder.startLongPoll(this.id, this.password); - this.addDisconnectPingFrame(this.id, this.password); - }; - /** - * Forces long polling to be considered as a potential transport - */ - BrowserPollConnection.forceAllow = function () { - BrowserPollConnection.forceAllow_ = true; - }; - /** - * Forces longpolling to not be considered as a potential transport - */ - BrowserPollConnection.forceDisallow = function () { - BrowserPollConnection.forceDisallow_ = true; - }; - // Static method, use string literal so it can be accessed in a generic way - BrowserPollConnection.isAvailable = function () { - // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in - // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). - return (BrowserPollConnection.forceAllow_ || - (!BrowserPollConnection.forceDisallow_ && - typeof document !== 'undefined' && - document.createElement != null && - !isChromeExtensionContentScript() && - !isWindowsStoreApp() && - !util.isNodeSdk())); - }; - /** - * No-op for polling - */ - BrowserPollConnection.prototype.markConnectionHealthy = function () { }; - /** - * Stops polling and cleans up the iframe - * @private - */ - BrowserPollConnection.prototype.shutdown_ = function () { - this.isClosed_ = true; - if (this.scriptTagHolder) { - this.scriptTagHolder.close(); - this.scriptTagHolder = null; - } - //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. - if (this.myDisconnFrame) { - document.body.removeChild(this.myDisconnFrame); - this.myDisconnFrame = null; - } - if (this.connectTimeoutTimer_) { - clearTimeout(this.connectTimeoutTimer_); - this.connectTimeoutTimer_ = null; - } - }; - /** - * Triggered when this transport is closed - * @private - */ - BrowserPollConnection.prototype.onClosed_ = function () { - if (!this.isClosed_) { - this.log_('Longpoll is closing itself'); - this.shutdown_(); - if (this.onDisconnect_) { - this.onDisconnect_(this.everConnected_); - this.onDisconnect_ = null; - } - } - }; - /** - * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server - * that we've left. - */ - BrowserPollConnection.prototype.close = function () { - if (!this.isClosed_) { - this.log_('Longpoll is being closed.'); - this.shutdown_(); - } - }; - /** - * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then - * broken into chunks (since URLs have a small maximum length). - * @param {!Object} data The JSON data to transmit. - */ - BrowserPollConnection.prototype.send = function (data) { - var dataStr = util.stringify(data); - this.bytesSent += dataStr.length; - this.stats_.incrementCounter('bytes_sent', dataStr.length); - //first, lets get the base64-encoded data - var base64data = util.base64Encode(dataStr); - //We can only fit a certain amount in each URL, so we need to split this request - //up into multiple pieces if it doesn't fit in one request. - var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); - //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number - //of segments so that we can reassemble the packet on the server. - for (var i = 0; i < dataSegs.length; i++) { - this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); - this.curSegmentNum++; - } - }; - /** - * This is how we notify the server that we're leaving. - * We aren't able to send requests with DHTML on a window close event, but we can - * trigger XHR requests in some browsers (everything but Opera basically). - * @param {!string} id - * @param {!string} pw - */ - BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) { - if (util.isNodeSdk()) - return; - this.myDisconnFrame = document.createElement('iframe'); - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; - this.myDisconnFrame.src = this.urlFn(urlParams); - this.myDisconnFrame.style.display = 'none'; - document.body.appendChild(this.myDisconnFrame); - }; - /** - * Used to track the bytes received by this client - * @param {*} args - * @private - */ - BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) { - // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. - var bytesReceived = util.stringify(args).length; - this.bytesReceived += bytesReceived; - this.stats_.incrementCounter('bytes_received', bytesReceived); - }; - return BrowserPollConnection; -}()); -/********************************************************************************************* - * A wrapper around an iframe that is used as a long-polling script holder. - * @constructor - *********************************************************************************************/ -var FirebaseIFrameScriptHolder = /** @class */ (function () { - /** - * @param commandCB - The callback to be called when control commands are recevied from the server. - * @param onMessageCB - The callback to be triggered when responses arrive from the server. - * @param onDisconnect - The callback to be triggered when this tag holder is closed - * @param urlFn - A function that provides the URL of the endpoint to send data to. - */ - function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) { - this.onDisconnect = onDisconnect; - this.urlFn = urlFn; - //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause - //problems in some browsers. - /** - * @type {CountedSet.} - */ - this.outstandingRequests = new CountedSet(); - //A queue of the pending segments waiting for transmission to the server. - this.pendingSegs = []; - //A serial number. We use this for two things: - // 1) A way to ensure the browser doesn't cache responses to polls - // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The - // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute - // JSONP code in the order it was added to the iframe. - this.currentSerial = Math.floor(Math.random() * 100000000); - // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still - // incoming data from the server that we're waiting for). - this.sendNewPolls = true; - if (!util.isNodeSdk()) { - //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the - //iframes where we put the long-polling script tags. We have two callbacks: - // 1) Command Callback - Triggered for control issues, like starting a connection. - // 2) Message Callback - Triggered when new data arrives. - this.uniqueCallbackIdentifier = LUIDGenerator(); - window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; - window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB; - //Create an iframe for us to add script tags to. - this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); - // Set the iframe's contents. - var script = ''; - // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient - // for ie9, but ie8 needs to do it again in the document itself. - if (this.myIFrame.src && - this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { - var currentDomain = document.domain; - script = ''; - } - var iframeContents = '' + script + ''; - try { - this.myIFrame.doc.open(); - this.myIFrame.doc.write(iframeContents); - this.myIFrame.doc.close(); - } - catch (e) { - log('frame writing exception'); - if (e.stack) { - log(e.stack); - } - log(e); - } - } - else { - this.commandCB = commandCB; - this.onMessageCB = onMessageCB; - } - } - /** - * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can - * actually use. - * @private - * @return {Element} - */ - FirebaseIFrameScriptHolder.createIFrame_ = function () { - var iframe = document.createElement('iframe'); - iframe.style.display = 'none'; - // This is necessary in order to initialize the document inside the iframe - if (document.body) { - document.body.appendChild(iframe); - try { - // If document.domain has been modified in IE, this will throw an error, and we need to set the - // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute - // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. - var a = iframe.contentWindow.document; - if (!a) { - // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. - log('No IE domain setting required'); - } - } - catch (e) { - var domain = document.domain; - iframe.src = - "javascript:void((function(){document.open();document.domain='" + - domain + - "';document.close();})())"; - } - } - else { - // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this - // never gets hit. - throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; - } - // Get the document of the iframe in a browser-specific way. - if (iframe.contentDocument) { - iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari - } - else if (iframe.contentWindow) { - iframe.doc = iframe.contentWindow.document; // Internet Explorer - } - else if (iframe.document) { - iframe.doc = iframe.document; //others? - } - return iframe; - }; - /** - * Cancel all outstanding queries and remove the frame. - */ - FirebaseIFrameScriptHolder.prototype.close = function () { - var _this = this; - //Mark this iframe as dead, so no new requests are sent. - this.alive = false; - if (this.myIFrame) { - //We have to actually remove all of the html inside this iframe before removing it from the - //window, or IE will continue loading and executing the script tags we've already added, which - //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this. - this.myIFrame.doc.body.innerHTML = ''; - setTimeout(function () { - if (_this.myIFrame !== null) { - document.body.removeChild(_this.myIFrame); - _this.myIFrame = null; - } - }, Math.floor(0)); - } - if (util.isNodeSdk() && this.myID) { - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; - var theURL = this.urlFn(urlParams); - FirebaseIFrameScriptHolder.nodeRestRequest(theURL); - } - // Protect from being called recursively. - var onDisconnect = this.onDisconnect; - if (onDisconnect) { - this.onDisconnect = null; - onDisconnect(); - } - }; - /** - * Actually start the long-polling session by adding the first script tag(s) to the iframe. - * @param {!string} id - The ID of this connection - * @param {!string} pw - The password for this connection - */ - FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) { - this.myID = id; - this.myPW = pw; - this.alive = true; - //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. - while (this.newRequest_()) { } - }; - /** - * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't - * too many outstanding requests and we are still alive. - * - * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if - * needed. - */ - FirebaseIFrameScriptHolder.prototype.newRequest_ = function () { - // We keep one outstanding request open all the time to receive data, but if we need to send data - // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically - // close the old request. - if (this.alive && - this.sendNewPolls && - this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) { - //construct our url - this.currentSerial++; - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; - urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; - var theURL = this.urlFn(urlParams); - //Now add as much data as we can. - var curDataString = ''; - var i = 0; - while (this.pendingSegs.length > 0) { - //first, lets see if the next segment will fit. - var nextSeg = this.pendingSegs[0]; - if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <= - MAX_URL_DATA_SIZE) { - //great, the segment will fit. Lets append it. - var theSeg = this.pendingSegs.shift(); - curDataString = - curDataString + - '&' + - FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + - i + - '=' + - theSeg.seg + - '&' + - FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + - i + - '=' + - theSeg.ts + - '&' + - FIREBASE_LONGPOLL_DATA_PARAM + - i + - '=' + - theSeg.d; - i++; - } - else { - break; - } - } - theURL = theURL + curDataString; - this.addLongPollTag_(theURL, this.currentSerial); - return true; - } - else { - return false; - } - }; - /** - * Queue a packet for transmission to the server. - * @param segnum - A sequential id for this packet segment used for reassembly - * @param totalsegs - The total number of segments in this packet - * @param data - The data for this segment. - */ - FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) { - //add this to the queue of segments to send. - this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); - //send the data immediately if there isn't already data being transmitted, unless - //startLongPoll hasn't been called yet. - if (this.alive) { - this.newRequest_(); - } - }; - /** - * Add a script tag for a regular long-poll request. - * @param {!string} url - The URL of the script tag. - * @param {!number} serial - The serial number of the request. - * @private - */ - FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) { - var _this = this; - //remember that we sent this request. - this.outstandingRequests.add(serial, 1); - var doNewRequest = function () { - _this.outstandingRequests.remove(serial); - _this.newRequest_(); - }; - // If this request doesn't return on its own accord (by the server sending us some data), we'll - // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. - var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); - var readyStateCB = function () { - // Request completed. Cancel the keepalive. - clearTimeout(keepaliveTimeout); - // Trigger a new request so we can continue receiving data. - doNewRequest(); - }; - this.addTag(url, readyStateCB); - }; - /** - * Add an arbitrary script tag to the iframe. - * @param {!string} url - The URL for the script tag source. - * @param {!function()} loadCB - A callback to be triggered once the script has loaded. - */ - FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) { - var _this = this; - if (util.isNodeSdk()) { - this.doNodeLongPoll(url, loadCB); - } - else { - setTimeout(function () { - try { - // if we're already closed, don't add this poll - if (!_this.sendNewPolls) - return; - var newScript_1 = _this.myIFrame.doc.createElement('script'); - newScript_1.type = 'text/javascript'; - newScript_1.async = true; - newScript_1.src = url; - newScript_1.onload = newScript_1.onreadystatechange = function () { - var rstate = newScript_1.readyState; - if (!rstate || rstate === 'loaded' || rstate === 'complete') { - newScript_1.onload = newScript_1.onreadystatechange = null; - if (newScript_1.parentNode) { - newScript_1.parentNode.removeChild(newScript_1); - } - loadCB(); - } - }; - newScript_1.onerror = function () { - log('Long-poll script failed to load: ' + url); - _this.sendNewPolls = false; - _this.close(); - }; - _this.myIFrame.doc.body.appendChild(newScript_1); - } - catch (e) { - // TODO: we should make this error visible somehow - } - }, Math.floor(1)); - } - }; - return FirebaseIFrameScriptHolder; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var WEBSOCKET_MAX_FRAME_SIZE = 16384; -var WEBSOCKET_KEEPALIVE_INTERVAL = 45000; -var WebSocketImpl = null; -if (typeof MozWebSocket !== 'undefined') { - WebSocketImpl = MozWebSocket; -} -else if (typeof WebSocket !== 'undefined') { - WebSocketImpl = WebSocket; -} -/** - * Create a new websocket connection with the given callbacks. - * @constructor - * @implements {Transport} - */ -var WebSocketConnection = /** @class */ (function () { - /** - * @param {string} connId identifier for this transport - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - */ - function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) { - this.connId = connId; - this.keepaliveTimer = null; - this.frames = null; - this.totalFrames = 0; - this.bytesSent = 0; - this.bytesReceived = 0; - this.log_ = logWrapper(this.connId); - this.stats_ = StatsManager.getCollection(repoInfo); - this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId); - } - /** - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @return {string} connection url - * @private - */ - WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) { - var urlParams = {}; - urlParams[VERSION_PARAM] = PROTOCOL_VERSION; - if (!util.isNodeSdk() && - typeof location !== 'undefined' && - location.href && - location.href.indexOf(FORGE_DOMAIN) !== -1) { - urlParams[REFERER_PARAM] = FORGE_REF; - } - if (transportSessionId) { - urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; - } - if (lastSessionId) { - urlParams[LAST_SESSION_PARAM] = lastSessionId; - } - return repoInfo.connectionURL(WEBSOCKET, urlParams); - }; - /** - * - * @param onMessage Callback when messages arrive - * @param onDisconnect Callback with connection lost. - */ - WebSocketConnection.prototype.open = function (onMessage, onDisconnect) { - var _this = this; - this.onDisconnect = onDisconnect; - this.onMessage = onMessage; - this.log_('Websocket connecting to ' + this.connURL); - this.everConnected_ = false; - // Assume failure until proven otherwise. - PersistentStorage.set('previous_websocket_failure', true); - try { - if (util.isNodeSdk()) { - var device = util.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node'; - // UA Format: Firebase//// - var options = { - headers: { - 'User-Agent': "Firebase/" + PROTOCOL_VERSION + "/" + firebase.SDK_VERSION + "/" + process.platform + "/" + device - } - }; - // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. - var env = process['env']; - var proxy = this.connURL.indexOf('wss://') == 0 - ? env['HTTPS_PROXY'] || env['https_proxy'] - : env['HTTP_PROXY'] || env['http_proxy']; - if (proxy) { - options['proxy'] = { origin: proxy }; - } - this.mySock = new WebSocketImpl(this.connURL, [], options); - } - else { - this.mySock = new WebSocketImpl(this.connURL); - } - } - catch (e) { - this.log_('Error instantiating WebSocket.'); - var error$$1 = e.message || e.data; - if (error$$1) { - this.log_(error$$1); - } - this.onClosed_(); - return; - } - this.mySock.onopen = function () { - _this.log_('Websocket connected.'); - _this.everConnected_ = true; - }; - this.mySock.onclose = function () { - _this.log_('Websocket connection was disconnected.'); - _this.mySock = null; - _this.onClosed_(); - }; - this.mySock.onmessage = function (m) { - _this.handleIncomingFrame(m); - }; - this.mySock.onerror = function (e) { - _this.log_('WebSocket error. Closing connection.'); - var error$$1 = e.message || e.data; - if (error$$1) { - _this.log_(error$$1); - } - _this.onClosed_(); - }; - }; - /** - * No-op for websockets, we don't need to do anything once the connection is confirmed as open - */ - WebSocketConnection.prototype.start = function () { }; - WebSocketConnection.forceDisallow = function () { - WebSocketConnection.forceDisallow_ = true; - }; - WebSocketConnection.isAvailable = function () { - var isOldAndroid = false; - if (typeof navigator !== 'undefined' && navigator.userAgent) { - var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; - var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); - if (oldAndroidMatch && oldAndroidMatch.length > 1) { - if (parseFloat(oldAndroidMatch[1]) < 4.4) { - isOldAndroid = true; - } - } - } - return (!isOldAndroid && - WebSocketImpl !== null && - !WebSocketConnection.forceDisallow_); - }; - /** - * Returns true if we previously failed to connect with this transport. - * @return {boolean} - */ - WebSocketConnection.previouslyFailed = function () { - // If our persistent storage is actually only in-memory storage, - // we default to assuming that it previously failed to be safe. - return (PersistentStorage.isInMemoryStorage || - PersistentStorage.get('previous_websocket_failure') === true); - }; - WebSocketConnection.prototype.markConnectionHealthy = function () { - PersistentStorage.remove('previous_websocket_failure'); - }; - WebSocketConnection.prototype.appendFrame_ = function (data) { - this.frames.push(data); - if (this.frames.length == this.totalFrames) { - var fullMess = this.frames.join(''); - this.frames = null; - var jsonMess = util.jsonEval(fullMess); - //handle the message - this.onMessage(jsonMess); - } - }; - /** - * @param {number} frameCount The number of frames we are expecting from the server - * @private - */ - WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) { - this.totalFrames = frameCount; - this.frames = []; - }; - /** - * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 - * @param {!String} data - * @return {?String} Any remaining data to be process, or null if there is none - * @private - */ - WebSocketConnection.prototype.extractFrameCount_ = function (data) { - util.assert(this.frames === null, 'We already have a frame buffer'); - // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced - // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 - if (data.length <= 6) { - var frameCount = Number(data); - if (!isNaN(frameCount)) { - this.handleNewFrameCount_(frameCount); - return null; - } - } - this.handleNewFrameCount_(1); - return data; - }; - /** - * Process a websocket frame that has arrived from the server. - * @param mess The frame data - */ - WebSocketConnection.prototype.handleIncomingFrame = function (mess) { - if (this.mySock === null) - return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. - var data = mess['data']; - this.bytesReceived += data.length; - this.stats_.incrementCounter('bytes_received', data.length); - this.resetKeepAlive(); - if (this.frames !== null) { - // we're buffering - this.appendFrame_(data); - } - else { - // try to parse out a frame count, otherwise, assume 1 and process it - var remainingData = this.extractFrameCount_(data); - if (remainingData !== null) { - this.appendFrame_(remainingData); - } - } - }; - /** - * Send a message to the server - * @param {Object} data The JSON object to transmit - */ - WebSocketConnection.prototype.send = function (data) { - this.resetKeepAlive(); - var dataStr = util.stringify(data); - this.bytesSent += dataStr.length; - this.stats_.incrementCounter('bytes_sent', dataStr.length); - //We can only fit a certain amount in each websocket frame, so we need to split this request - //up into multiple pieces if it doesn't fit in one request. - var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); - //Send the length header - if (dataSegs.length > 1) { - this.sendString_(String(dataSegs.length)); - } - //Send the actual data in segments. - for (var i = 0; i < dataSegs.length; i++) { - this.sendString_(dataSegs[i]); - } - }; - WebSocketConnection.prototype.shutdown_ = function () { - this.isClosed_ = true; - if (this.keepaliveTimer) { - clearInterval(this.keepaliveTimer); - this.keepaliveTimer = null; - } - if (this.mySock) { - this.mySock.close(); - this.mySock = null; - } - }; - WebSocketConnection.prototype.onClosed_ = function () { - if (!this.isClosed_) { - this.log_('WebSocket is closing itself'); - this.shutdown_(); - // since this is an internal close, trigger the close listener - if (this.onDisconnect) { - this.onDisconnect(this.everConnected_); - this.onDisconnect = null; - } - } - }; - /** - * External-facing close handler. - * Close the websocket and kill the connection. - */ - WebSocketConnection.prototype.close = function () { - if (!this.isClosed_) { - this.log_('WebSocket is being closed'); - this.shutdown_(); - } - }; - /** - * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after - * the last activity. - */ - WebSocketConnection.prototype.resetKeepAlive = function () { - var _this = this; - clearInterval(this.keepaliveTimer); - this.keepaliveTimer = setInterval(function () { - //If there has been no websocket activity for a while, send a no-op - if (_this.mySock) { - _this.sendString_('0'); - } - _this.resetKeepAlive(); - }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); - }; - /** - * Send a string over the websocket. - * - * @param {string} str String to send. - * @private - */ - WebSocketConnection.prototype.sendString_ = function (str) { - // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() - // calls for some unknown reason. We treat these as an error and disconnect. - // See https://app.asana.com/0/58926111402292/68021340250410 - try { - this.mySock.send(str); - } - catch (e) { - this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); - setTimeout(this.onClosed_.bind(this), 0); - } - }; - /** - * Number of response before we consider the connection "healthy." - * @type {number} - */ - WebSocketConnection.responsesRequiredToBeHealthy = 2; - /** - * Time to wait for the connection te become healthy before giving up. - * @type {number} - */ - WebSocketConnection.healthyTimeout = 30000; - return WebSocketConnection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Currently simplistic, this class manages what transport a Connection should use at various stages of its - * lifecycle. - * - * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if - * they are available. - * @constructor - */ -var TransportManager = /** @class */ (function () { - /** - * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to - */ - function TransportManager(repoInfo) { - this.initTransports_(repoInfo); - } - Object.defineProperty(TransportManager, "ALL_TRANSPORTS", { - /** - * @const - * @type {!Array.} - */ - get: function () { - return [BrowserPollConnection, WebSocketConnection]; - }, - enumerable: true, - configurable: true - }); - /** - * @param {!RepoInfo} repoInfo - * @private - */ - TransportManager.prototype.initTransports_ = function (repoInfo) { - var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); - var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); - if (repoInfo.webSocketOnly) { - if (!isWebSocketsAvailable) - warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); - isSkipPollConnection = true; - } - if (isSkipPollConnection) { - this.transports_ = [WebSocketConnection]; - } - else { - var transports_1 = (this.transports_ = []); - each(TransportManager.ALL_TRANSPORTS, function (i, transport) { - if (transport && transport['isAvailable']()) { - transports_1.push(transport); - } - }); - } - }; - /** - * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the - * initial transport to use - */ - TransportManager.prototype.initialTransport = function () { - if (this.transports_.length > 0) { - return this.transports_[0]; - } - else { - throw new Error('No transports available'); - } - }; - /** - * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next - * transport, or null - */ - TransportManager.prototype.upgradeTransport = function () { - if (this.transports_.length > 1) { - return this.transports_[1]; - } - else { - return null; - } - }; - return TransportManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Abort upgrade attempt if it takes longer than 60s. -var UPGRADE_TIMEOUT = 60000; -// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. -// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. -var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; -// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) -// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout -// but we've sent/received enough bytes, we don't cancel the connection. -var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; -var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; -var MESSAGE_TYPE = 't'; -var MESSAGE_DATA = 'd'; -var CONTROL_SHUTDOWN = 's'; -var CONTROL_RESET = 'r'; -var CONTROL_ERROR = 'e'; -var CONTROL_PONG = 'o'; -var SWITCH_ACK = 'a'; -var END_TRANSMISSION = 'n'; -var PING = 'p'; -var SERVER_HELLO = 'h'; -/** - * Creates a new real-time connection to the server using whichever method works - * best in the current browser. - * - * @constructor - */ -var Connection = /** @class */ (function () { - /** - * @param {!string} id - an id for this connection - * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to - * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives - * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages. - * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost - * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down. - * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server - */ - function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { - this.id = id; - this.repoInfo_ = repoInfo_; - this.onMessage_ = onMessage_; - this.onReady_ = onReady_; - this.onDisconnect_ = onDisconnect_; - this.onKill_ = onKill_; - this.lastSessionId = lastSessionId; - this.connectionCount = 0; - this.pendingDataMessages = []; - this.state_ = 0 /* CONNECTING */; - this.log_ = logWrapper('c:' + this.id + ':'); - this.transportManager_ = new TransportManager(repoInfo_); - this.log_('Connection created'); - this.start_(); - } - /** - * Starts a connection attempt - * @private - */ - Connection.prototype.start_ = function () { - var _this = this; - var conn = this.transportManager_.initialTransport(); - this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId); - // For certain transports (WebSockets), we need to send and receive several messages back and forth before we - // can consider the transport healthy. - this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; - var onMessageReceived = this.connReceiver_(this.conn_); - var onConnectionLost = this.disconnReceiver_(this.conn_); - this.tx_ = this.conn_; - this.rx_ = this.conn_; - this.secondaryConn_ = null; - this.isHealthy_ = false; - /* - * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. - * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. - * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should - * still have the context of your originating frame. - */ - setTimeout(function () { - // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it - _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost); - }, Math.floor(0)); - var healthyTimeout_ms = conn['healthyTimeout'] || 0; - if (healthyTimeout_ms > 0) { - this.healthyTimeout_ = setTimeoutNonBlocking(function () { - _this.healthyTimeout_ = null; - if (!_this.isHealthy_) { - if (_this.conn_ && - _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { - _this.log_('Connection exceeded healthy timeout but has received ' + - _this.conn_.bytesReceived + - ' bytes. Marking connection healthy.'); - _this.isHealthy_ = true; - _this.conn_.markConnectionHealthy(); - } - else if (_this.conn_ && - _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { - _this.log_('Connection exceeded healthy timeout but has sent ' + - _this.conn_.bytesSent + - ' bytes. Leaving connection alive.'); - // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to - // the server. - } - else { - _this.log_('Closing unhealthy connection after timeout.'); - _this.close(); - } - } - }, Math.floor(healthyTimeout_ms)); - } - }; - /** - * @return {!string} - * @private - */ - Connection.prototype.nextTransportId_ = function () { - return 'c:' + this.id + ':' + this.connectionCount++; - }; - Connection.prototype.disconnReceiver_ = function (conn) { - var _this = this; - return function (everConnected) { - if (conn === _this.conn_) { - _this.onConnectionLost_(everConnected); - } - else if (conn === _this.secondaryConn_) { - _this.log_('Secondary connection lost.'); - _this.onSecondaryConnectionLost_(); - } - else { - _this.log_('closing an old connection'); - } - }; - }; - Connection.prototype.connReceiver_ = function (conn) { - var _this = this; - return function (message) { - if (_this.state_ != 2 /* DISCONNECTED */) { - if (conn === _this.rx_) { - _this.onPrimaryMessageReceived_(message); - } - else if (conn === _this.secondaryConn_) { - _this.onSecondaryMessageReceived_(message); - } - else { - _this.log_('message on old connection'); - } - } - }; - }; - /** - * - * @param {Object} dataMsg An arbitrary data message to be sent to the server - */ - Connection.prototype.sendRequest = function (dataMsg) { - // wrap in a data message envelope and send it on - var msg = { t: 'd', d: dataMsg }; - this.sendData_(msg); - }; - Connection.prototype.tryCleanupConnection = function () { - if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { - this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); - this.conn_ = this.secondaryConn_; - this.secondaryConn_ = null; - // the server will shutdown the old connection - } - }; - Connection.prototype.onSecondaryControl_ = function (controlData) { - if (MESSAGE_TYPE in controlData) { - var cmd = controlData[MESSAGE_TYPE]; - if (cmd === SWITCH_ACK) { - this.upgradeIfSecondaryHealthy_(); - } - else if (cmd === CONTROL_RESET) { - // Most likely the session wasn't valid. Abandon the switch attempt - this.log_('Got a reset on secondary, closing it'); - this.secondaryConn_.close(); - // If we were already using this connection for something, than we need to fully close - if (this.tx_ === this.secondaryConn_ || - this.rx_ === this.secondaryConn_) { - this.close(); - } - } - else if (cmd === CONTROL_PONG) { - this.log_('got pong on secondary.'); - this.secondaryResponsesRequired_--; - this.upgradeIfSecondaryHealthy_(); - } - } - }; - Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) { - var layer = requireKey('t', parsedData); - var data = requireKey('d', parsedData); - if (layer == 'c') { - this.onSecondaryControl_(data); - } - else if (layer == 'd') { - // got a data message, but we're still second connection. Need to buffer it up - this.pendingDataMessages.push(data); - } - else { - throw new Error('Unknown protocol layer: ' + layer); - } - }; - Connection.prototype.upgradeIfSecondaryHealthy_ = function () { - if (this.secondaryResponsesRequired_ <= 0) { - this.log_('Secondary connection is healthy.'); - this.isHealthy_ = true; - this.secondaryConn_.markConnectionHealthy(); - this.proceedWithUpgrade_(); - } - else { - // Send a ping to make sure the connection is healthy. - this.log_('sending ping on secondary.'); - this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); - } - }; - Connection.prototype.proceedWithUpgrade_ = function () { - // tell this connection to consider itself open - this.secondaryConn_.start(); - // send ack - this.log_('sending client ack on secondary'); - this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); - // send end packet on primary transport, switch to sending on this one - // can receive on this one, buffer responses until end received on primary transport - this.log_('Ending transmission on primary'); - this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); - this.tx_ = this.secondaryConn_; - this.tryCleanupConnection(); - }; - Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) { - // Must refer to parsedData properties in quotes, so closure doesn't touch them. - var layer = requireKey('t', parsedData); - var data = requireKey('d', parsedData); - if (layer == 'c') { - this.onControl_(data); - } - else if (layer == 'd') { - this.onDataMessage_(data); - } - }; - Connection.prototype.onDataMessage_ = function (message) { - this.onPrimaryResponse_(); - // We don't do anything with data messages, just kick them up a level - this.onMessage_(message); - }; - Connection.prototype.onPrimaryResponse_ = function () { - if (!this.isHealthy_) { - this.primaryResponsesRequired_--; - if (this.primaryResponsesRequired_ <= 0) { - this.log_('Primary connection is healthy.'); - this.isHealthy_ = true; - this.conn_.markConnectionHealthy(); - } - } - }; - Connection.prototype.onControl_ = function (controlData) { - var cmd = requireKey(MESSAGE_TYPE, controlData); - if (MESSAGE_DATA in controlData) { - var payload = controlData[MESSAGE_DATA]; - if (cmd === SERVER_HELLO) { - this.onHandshake_(payload); - } - else if (cmd === END_TRANSMISSION) { - this.log_('recvd end transmission on primary'); - this.rx_ = this.secondaryConn_; - for (var i = 0; i < this.pendingDataMessages.length; ++i) { - this.onDataMessage_(this.pendingDataMessages[i]); - } - this.pendingDataMessages = []; - this.tryCleanupConnection(); - } - else if (cmd === CONTROL_SHUTDOWN) { - // This was previously the 'onKill' callback passed to the lower-level connection - // payload in this case is the reason for the shutdown. Generally a human-readable error - this.onConnectionShutdown_(payload); - } - else if (cmd === CONTROL_RESET) { - // payload in this case is the host we should contact - this.onReset_(payload); - } - else if (cmd === CONTROL_ERROR) { - error('Server Error: ' + payload); - } - else if (cmd === CONTROL_PONG) { - this.log_('got pong on primary.'); - this.onPrimaryResponse_(); - this.sendPingOnPrimaryIfNecessary_(); - } - else { - error('Unknown control packet command: ' + cmd); - } - } - }; - /** - * - * @param {Object} handshake The handshake data returned from the server - * @private - */ - Connection.prototype.onHandshake_ = function (handshake) { - var timestamp = handshake.ts; - var version = handshake.v; - var host = handshake.h; - this.sessionId = handshake.s; - this.repoInfo_.updateHost(host); - // if we've already closed the connection, then don't bother trying to progress further - if (this.state_ == 0 /* CONNECTING */) { - this.conn_.start(); - this.onConnectionEstablished_(this.conn_, timestamp); - if (PROTOCOL_VERSION !== version) { - warn('Protocol version mismatch detected'); - } - // TODO: do we want to upgrade? when? maybe a delay? - this.tryStartUpgrade_(); - } - }; - Connection.prototype.tryStartUpgrade_ = function () { - var conn = this.transportManager_.upgradeTransport(); - if (conn) { - this.startUpgrade_(conn); - } - }; - Connection.prototype.startUpgrade_ = function (conn) { - var _this = this; - this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId); - // For certain transports (WebSockets), we need to send and receive several messages back and forth before we - // can consider the transport healthy. - this.secondaryResponsesRequired_ = - conn['responsesRequiredToBeHealthy'] || 0; - var onMessage = this.connReceiver_(this.secondaryConn_); - var onDisconnect = this.disconnReceiver_(this.secondaryConn_); - this.secondaryConn_.open(onMessage, onDisconnect); - // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. - setTimeoutNonBlocking(function () { - if (_this.secondaryConn_) { - _this.log_('Timed out trying to upgrade.'); - _this.secondaryConn_.close(); - } - }, Math.floor(UPGRADE_TIMEOUT)); - }; - Connection.prototype.onReset_ = function (host) { - this.log_('Reset packet received. New host: ' + host); - this.repoInfo_.updateHost(host); - // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. - // We don't currently support resets after the connection has already been established - if (this.state_ === 1 /* CONNECTED */) { - this.close(); - } - else { - // Close whatever connections we have open and start again. - this.closeConnections_(); - this.start_(); - } - }; - Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) { - var _this = this; - this.log_('Realtime connection established.'); - this.conn_ = conn; - this.state_ = 1 /* CONNECTED */; - if (this.onReady_) { - this.onReady_(timestamp, this.sessionId); - this.onReady_ = null; - } - // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, - // send some pings. - if (this.primaryResponsesRequired_ === 0) { - this.log_('Primary connection is healthy.'); - this.isHealthy_ = true; - } - else { - setTimeoutNonBlocking(function () { - _this.sendPingOnPrimaryIfNecessary_(); - }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); - } - }; - Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () { - // If the connection isn't considered healthy yet, we'll send a noop ping packet request. - if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) { - this.log_('sending ping on primary.'); - this.sendData_({ t: 'c', d: { t: PING, d: {} } }); - } - }; - Connection.prototype.onSecondaryConnectionLost_ = function () { - var conn = this.secondaryConn_; - this.secondaryConn_ = null; - if (this.tx_ === conn || this.rx_ === conn) { - // we are relying on this connection already in some capacity. Therefore, a failure is real - this.close(); - } - }; - /** - * - * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if - * we should flush the host cache - * @private - */ - Connection.prototype.onConnectionLost_ = function (everConnected) { - this.conn_ = null; - // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting - // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. - if (!everConnected && this.state_ === 0 /* CONNECTING */) { - this.log_('Realtime connection failed.'); - // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away - if (this.repoInfo_.isCacheableHost()) { - PersistentStorage.remove('host:' + this.repoInfo_.host); - // reset the internal host to what we would show the user, i.e. .firebaseio.com - this.repoInfo_.internalHost = this.repoInfo_.host; - } - } - else if (this.state_ === 1 /* CONNECTED */) { - this.log_('Realtime connection lost.'); - } - this.close(); - }; - /** - * - * @param {string} reason - * @private - */ - Connection.prototype.onConnectionShutdown_ = function (reason) { - this.log_('Connection shutdown command received. Shutting down...'); - if (this.onKill_) { - this.onKill_(reason); - this.onKill_ = null; - } - // We intentionally don't want to fire onDisconnect (kill is a different case), - // so clear the callback. - this.onDisconnect_ = null; - this.close(); - }; - Connection.prototype.sendData_ = function (data) { - if (this.state_ !== 1 /* CONNECTED */) { - throw 'Connection is not connected'; - } - else { - this.tx_.send(data); - } - }; - /** - * Cleans up this connection, calling the appropriate callbacks - */ - Connection.prototype.close = function () { - if (this.state_ !== 2 /* DISCONNECTED */) { - this.log_('Closing realtime connection.'); - this.state_ = 2 /* DISCONNECTED */; - this.closeConnections_(); - if (this.onDisconnect_) { - this.onDisconnect_(); - this.onDisconnect_ = null; - } - } - }; - /** - * - * @private - */ - Connection.prototype.closeConnections_ = function () { - this.log_('Shutting down all connections'); - if (this.conn_) { - this.conn_.close(); - this.conn_ = null; - } - if (this.secondaryConn_) { - this.secondaryConn_.close(); - this.secondaryConn_ = null; - } - if (this.healthyTimeout_) { - clearTimeout(this.healthyTimeout_); - this.healthyTimeout_ = null; - } - }; - return Connection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Interface defining the set of actions that can be performed against the Firebase server - * (basically corresponds to our wire protocol). - * - * @interface - */ -var ServerActions = /** @class */ (function () { - function ServerActions() { - } - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - * @param {string=} hash - */ - ServerActions.prototype.put = function (pathString, data, onComplete, hash) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, ?string)} onComplete - * @param {string=} hash - */ - ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { }; - /** - * Refreshes the auth token for the current connection. - * @param {string} token The authentication token - */ - ServerActions.prototype.refreshAuthToken = function (token) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { }; - /** - * @param {string} pathString - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { }; - /** - * @param {Object.} stats - */ - ServerActions.prototype.reportStats = function (stats) { }; - return ServerActions; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var RECONNECT_MIN_DELAY = 1000; -var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) -var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) -var RECONNECT_DELAY_MULTIPLIER = 1.3; -var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. -var SERVER_KILL_INTERRUPT_REASON = 'server_kill'; -// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. -var INVALID_AUTH_TOKEN_THRESHOLD = 3; -/** - * Firebase connection. Abstracts wire protocol and handles reconnecting. - * - * NOTE: All JSON objects sent to the realtime connection must have property names enclosed - * in quotes to make sure the closure compiler does not minify them. - */ -var PersistentConnection = /** @class */ (function (_super) { - tslib_1.__extends(PersistentConnection, _super); - /** - * @implements {ServerActions} - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param onConnectStatus_ - * @param onServerInfoUpdate_ - * @param authTokenProvider_ - * @param authOverride_ - */ - function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) { - var _this = _super.call(this) || this; - _this.repoInfo_ = repoInfo_; - _this.onDataUpdate_ = onDataUpdate_; - _this.onConnectStatus_ = onConnectStatus_; - _this.onServerInfoUpdate_ = onServerInfoUpdate_; - _this.authTokenProvider_ = authTokenProvider_; - _this.authOverride_ = authOverride_; - // Used for diagnostic logging. - _this.id = PersistentConnection.nextPersistentConnectionId_++; - _this.log_ = logWrapper('p:' + _this.id + ':'); - /** @private {Object} */ - _this.interruptReasons_ = {}; - _this.listens_ = {}; - _this.outstandingPuts_ = []; - _this.outstandingPutCount_ = 0; - _this.onDisconnectRequestQueue_ = []; - _this.connected_ = false; - _this.reconnectDelay_ = RECONNECT_MIN_DELAY; - _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; - _this.securityDebugCallback_ = null; - _this.lastSessionId = null; - /** @private {number|null} */ - _this.establishConnectionTimer_ = null; - /** @private {boolean} */ - _this.visible_ = false; - // Before we get connected, we keep a queue of pending messages to send. - _this.requestCBHash_ = {}; - _this.requestNumber_ = 0; - /** @private {?{ - * sendRequest(Object), - * close() - * }} */ - _this.realtime_ = null; - /** @private {string|null} */ - _this.authToken_ = null; - _this.forceTokenRefresh_ = false; - _this.invalidAuthTokenCount_ = 0; - _this.firstConnection_ = true; - _this.lastConnectionAttemptTime_ = null; - _this.lastConnectionEstablishedTime_ = null; - if (authOverride_ && !util.isNodeSdk()) { - throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); - } - _this.scheduleConnect_(0); - VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this); - if (repoInfo_.host.indexOf('fblocal') === -1) { - OnlineMonitor.getInstance().on('online', _this.onOnline_, _this); - } - return _this; - } - /** - * @param {!string} action - * @param {*} body - * @param {function(*)=} onResponse - * @protected - */ - PersistentConnection.prototype.sendRequest = function (action, body, onResponse) { - var curReqNum = ++this.requestNumber_; - var msg = { r: curReqNum, a: action, b: body }; - this.log_(util.stringify(msg)); - util.assert(this.connected_, "sendRequest call when we're not connected not allowed."); - this.realtime_.sendRequest(msg); - if (onResponse) { - this.requestCBHash_[curReqNum] = onResponse; - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) { - var queryId = query.queryIdentifier(); - var pathString = query.path.toString(); - this.log_('Listen called for ' + pathString + ' ' + queryId); - this.listens_[pathString] = this.listens_[pathString] || {}; - util.assert(query.getQueryParams().isDefault() || - !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query'); - util.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.'); - var listenSpec = { - onComplete: onComplete, - hashFn: currentHashFn, - query: query, - tag: tag - }; - this.listens_[pathString][queryId] = listenSpec; - if (this.connected_) { - this.sendListen_(listenSpec); - } - }; - /** - * @param {!{onComplete(), - * hashFn():!string, - * query: !Query, - * tag: ?number}} listenSpec - * @private - */ - PersistentConnection.prototype.sendListen_ = function (listenSpec) { - var _this = this; - var query = listenSpec.query; - var pathString = query.path.toString(); - var queryId = query.queryIdentifier(); - this.log_('Listen on ' + pathString + ' for ' + queryId); - var req = { /*path*/ p: pathString }; - var action = 'q'; - // Only bother to send query if it's non-default. - if (listenSpec.tag) { - req['q'] = query.queryObject(); - req['t'] = listenSpec.tag; - } - req[ /*hash*/'h'] = listenSpec.hashFn(); - this.sendRequest(action, req, function (message) { - var payload = message[ /*data*/'d']; - var status = message[ /*status*/'s']; - // print warnings in any case... - PersistentConnection.warnOnListenWarnings_(payload, query); - var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId]; - // only trigger actions if the listen hasn't been removed and readded - if (currentListenSpec === listenSpec) { - _this.log_('listen response', message); - if (status !== 'ok') { - _this.removeListen_(pathString, queryId); - } - if (listenSpec.onComplete) { - listenSpec.onComplete(status, payload); - } - } - }); - }; - /** - * @param {*} payload - * @param {!Query} query - * @private - */ - PersistentConnection.warnOnListenWarnings_ = function (payload, query) { - if (payload && typeof payload === 'object' && util.contains(payload, 'w')) { - var warnings = util.safeGet(payload, 'w'); - if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { - var indexSpec = '".indexOn": "' + - query - .getQueryParams() - .getIndex() - .toString() + - '"'; - var indexPath = query.path.toString(); - warn("Using an unspecified index. Your data will be downloaded and " + - ("filtered on the client. Consider adding " + indexSpec + " at ") + - (indexPath + " to your security rules for better performance.")); - } - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.refreshAuthToken = function (token) { - this.authToken_ = token; - this.log_('Auth token refreshed'); - if (this.authToken_) { - this.tryAuth(); - } - else { - //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete - //the credential so we dont become authenticated next time we connect. - if (this.connected_) { - this.sendRequest('unauth', {}, function () { }); - } - } - this.reduceReconnectDelayIfAdminCredential_(token); - }; - /** - * @param {!string} credential - * @private - */ - PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) { - // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). - // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. - var isFirebaseSecret = credential && credential.length === 40; - if (isFirebaseSecret || util.isAdmin(credential)) { - this.log_('Admin auth credential detected. Reducing max reconnect time.'); - this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; - } - }; - /** - * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like - * a auth revoked (the connection is closed). - */ - PersistentConnection.prototype.tryAuth = function () { - var _this = this; - if (this.connected_ && this.authToken_) { - var token_1 = this.authToken_; - var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth'; - var requestData = { cred: token_1 }; - if (this.authOverride_ === null) { - requestData['noauth'] = true; - } - else if (typeof this.authOverride_ === 'object') { - requestData['authvar'] = this.authOverride_; - } - this.sendRequest(authMethod, requestData, function (res) { - var status = res[ /*status*/'s']; - var data = res[ /*data*/'d'] || 'error'; - if (_this.authToken_ === token_1) { - if (status === 'ok') { - _this.invalidAuthTokenCount_ = 0; - } - else { - // Triggers reconnect and force refresh for auth token - _this.onAuthRevoked_(status, data); - } - } - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.unlisten = function (query, tag) { - var pathString = query.path.toString(); - var queryId = query.queryIdentifier(); - this.log_('Unlisten called for ' + pathString + ' ' + queryId); - util.assert(query.getQueryParams().isDefault() || - !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query'); - var listen = this.removeListen_(pathString, queryId); - if (listen && this.connected_) { - this.sendUnlisten_(pathString, queryId, query.queryObject(), tag); - } - }; - PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) { - this.log_('Unlisten on ' + pathString + ' for ' + queryId); - var req = { /*path*/ p: pathString }; - var action = 'n'; - // Only bother sending queryId if it's non-default. - if (tag) { - req['q'] = queryObj; - req['t'] = tag; - } - this.sendRequest(action, req); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('o', pathString, data, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'o', - data: data, - onComplete: onComplete - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('om', pathString, data, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'om', - data: data, - onComplete: onComplete - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('oc', pathString, null, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'oc', - data: null, - onComplete: onComplete - }); - } - }; - PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) { - var request = { /*path*/ p: pathString, /*data*/ d: data }; - this.log_('onDisconnect ' + action, request); - this.sendRequest(action, request, function (response) { - if (onComplete) { - setTimeout(function () { - onComplete(response[ /*status*/'s'], response[ /* data */'d']); - }, Math.floor(0)); - } - }); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { - this.putInternal('p', pathString, data, onComplete, hash); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) { - this.putInternal('m', pathString, data, onComplete, hash); - }; - PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) { - var request = { - /*path*/ p: pathString, - /*data*/ d: data - }; - if (hash !== undefined) - request[ /*hash*/'h'] = hash; - // TODO: Only keep track of the most recent put for a given path? - this.outstandingPuts_.push({ - action: action, - request: request, - onComplete: onComplete - }); - this.outstandingPutCount_++; - var index = this.outstandingPuts_.length - 1; - if (this.connected_) { - this.sendPut_(index); - } - else { - this.log_('Buffering put: ' + pathString); - } - }; - PersistentConnection.prototype.sendPut_ = function (index) { - var _this = this; - var action = this.outstandingPuts_[index].action; - var request = this.outstandingPuts_[index].request; - var onComplete = this.outstandingPuts_[index].onComplete; - this.outstandingPuts_[index].queued = this.connected_; - this.sendRequest(action, request, function (message) { - _this.log_(action + ' response', message); - delete _this.outstandingPuts_[index]; - _this.outstandingPutCount_--; - // Clean up array occasionally. - if (_this.outstandingPutCount_ === 0) { - _this.outstandingPuts_ = []; - } - if (onComplete) - onComplete(message[ /*status*/'s'], message[ /* data */'d']); - }); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.reportStats = function (stats) { - var _this = this; - // If we're not connected, we just drop the stats. - if (this.connected_) { - var request = { /*counters*/ c: stats }; - this.log_('reportStats', request); - this.sendRequest(/*stats*/ 's', request, function (result) { - var status = result[ /*status*/'s']; - if (status !== 'ok') { - var errorReason = result[ /* data */'d']; - _this.log_('reportStats', 'Error sending stats: ' + errorReason); - } - }); - } - }; - /** - * @param {*} message - * @private - */ - PersistentConnection.prototype.onDataMessage_ = function (message) { - if ('r' in message) { - // this is a response - this.log_('from server: ' + util.stringify(message)); - var reqNum = message['r']; - var onResponse = this.requestCBHash_[reqNum]; - if (onResponse) { - delete this.requestCBHash_[reqNum]; - onResponse(message[ /*body*/'b']); - } - } - else if ('error' in message) { - throw 'A server-side error has occurred: ' + message['error']; - } - else if ('a' in message) { - // a and b are action and body, respectively - this.onDataPush_(message['a'], message['b']); - } - }; - PersistentConnection.prototype.onDataPush_ = function (action, body) { - this.log_('handleServerMessage', action, body); - if (action === 'd') - this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], - /*isMerge*/ false, body['t']); - else if (action === 'm') - this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], - /*isMerge=*/ true, body['t']); - else if (action === 'c') - this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); - else if (action === 'ac') - this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); - else if (action === 'sd') - this.onSecurityDebugPacket_(body); - else - error('Unrecognized action received from server: ' + - util.stringify(action) + - '\nAre you using the latest client?'); - }; - PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) { - this.log_('connection ready'); - this.connected_ = true; - this.lastConnectionEstablishedTime_ = new Date().getTime(); - this.handleTimestamp_(timestamp); - this.lastSessionId = sessionId; - if (this.firstConnection_) { - this.sendConnectStats_(); - } - this.restoreState_(); - this.firstConnection_ = false; - this.onConnectStatus_(true); - }; - PersistentConnection.prototype.scheduleConnect_ = function (timeout) { - var _this = this; - util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); - if (this.establishConnectionTimer_) { - clearTimeout(this.establishConnectionTimer_); - } - // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in - // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). - this.establishConnectionTimer_ = setTimeout(function () { - _this.establishConnectionTimer_ = null; - _this.establishConnection_(); - }, Math.floor(timeout)); - }; - /** - * @param {boolean} visible - * @private - */ - PersistentConnection.prototype.onVisible_ = function (visible) { - // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. - if (visible && - !this.visible_ && - this.reconnectDelay_ === this.maxReconnectDelay_) { - this.log_('Window became visible. Reducing delay.'); - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - this.visible_ = visible; - }; - PersistentConnection.prototype.onOnline_ = function (online) { - if (online) { - this.log_('Browser went online.'); - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - else { - this.log_('Browser went offline. Killing connection.'); - if (this.realtime_) { - this.realtime_.close(); - } - } - }; - PersistentConnection.prototype.onRealtimeDisconnect_ = function () { - this.log_('data client disconnected'); - this.connected_ = false; - this.realtime_ = null; - // Since we don't know if our sent transactions succeeded or not, we need to cancel them. - this.cancelSentTransactions_(); - // Clear out the pending requests. - this.requestCBHash_ = {}; - if (this.shouldReconnect_()) { - if (!this.visible_) { - this.log_("Window isn't visible. Delaying reconnect."); - this.reconnectDelay_ = this.maxReconnectDelay_; - this.lastConnectionAttemptTime_ = new Date().getTime(); - } - else if (this.lastConnectionEstablishedTime_) { - // If we've been connected long enough, reset reconnect delay to minimum. - var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; - if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - this.lastConnectionEstablishedTime_ = null; - } - var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_; - var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); - reconnectDelay = Math.random() * reconnectDelay; - this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); - this.scheduleConnect_(reconnectDelay); - // Adjust reconnect delay for next time. - this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); - } - this.onConnectStatus_(false); - }; - PersistentConnection.prototype.establishConnection_ = function () { - if (this.shouldReconnect_()) { - this.log_('Making a connection attempt'); - this.lastConnectionAttemptTime_ = new Date().getTime(); - this.lastConnectionEstablishedTime_ = null; - var onDataMessage_1 = this.onDataMessage_.bind(this); - var onReady_1 = this.onReady_.bind(this); - var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this); - var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++; - var self_1 = this; - var lastSessionId_1 = this.lastSessionId; - var canceled_1 = false; - var connection_1 = null; - var closeFn_1 = function () { - if (connection_1) { - connection_1.close(); - } - else { - canceled_1 = true; - onDisconnect_1(); - } - }; - var sendRequestFn = function (msg) { - util.assert(connection_1, "sendRequest call when we're not connected not allowed."); - connection_1.sendRequest(msg); - }; - this.realtime_ = { - close: closeFn_1, - sendRequest: sendRequestFn - }; - var forceRefresh = this.forceTokenRefresh_; - this.forceTokenRefresh_ = false; - // First fetch auth token, and establish connection after fetching the token was successful - this.authTokenProvider_ - .getToken(forceRefresh) - .then(function (result) { - if (!canceled_1) { - log('getToken() completed. Creating connection.'); - self_1.authToken_ = result && result.accessToken; - connection_1 = new Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, - /* onKill= */ function (reason) { - warn(reason + ' (' + self_1.repoInfo_.toString() + ')'); - self_1.interrupt(SERVER_KILL_INTERRUPT_REASON); - }, lastSessionId_1); - } - else { - log('getToken() completed but was canceled'); - } - }) - .then(null, function (error$$1) { - self_1.log_('Failed to get token: ' + error$$1); - if (!canceled_1) { - if (util.CONSTANTS.NODE_ADMIN) { - // This may be a critical error for the Admin Node.js SDK, so log a warning. - // But getToken() may also just have temporarily failed, so we still want to - // continue retrying. - warn(error$$1); - } - closeFn_1(); - } - }); - } - }; - /** - * @param {string} reason - */ - PersistentConnection.prototype.interrupt = function (reason) { - log('Interrupting connection for reason: ' + reason); - this.interruptReasons_[reason] = true; - if (this.realtime_) { - this.realtime_.close(); - } - else { - if (this.establishConnectionTimer_) { - clearTimeout(this.establishConnectionTimer_); - this.establishConnectionTimer_ = null; - } - if (this.connected_) { - this.onRealtimeDisconnect_(); - } - } - }; - /** - * @param {string} reason - */ - PersistentConnection.prototype.resume = function (reason) { - log('Resuming connection for reason: ' + reason); - delete this.interruptReasons_[reason]; - if (util.isEmpty(this.interruptReasons_)) { - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - }; - PersistentConnection.prototype.handleTimestamp_ = function (timestamp) { - var delta = timestamp - new Date().getTime(); - this.onServerInfoUpdate_({ serverTimeOffset: delta }); - }; - PersistentConnection.prototype.cancelSentTransactions_ = function () { - for (var i = 0; i < this.outstandingPuts_.length; i++) { - var put = this.outstandingPuts_[i]; - if (put && /*hash*/ 'h' in put.request && put.queued) { - if (put.onComplete) - put.onComplete('disconnect'); - delete this.outstandingPuts_[i]; - this.outstandingPutCount_--; - } - } - // Clean up array occasionally. - if (this.outstandingPutCount_ === 0) - this.outstandingPuts_ = []; - }; - /** - * @param {!string} pathString - * @param {Array.<*>=} query - * @private - */ - PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) { - // Remove the listen and manufacture a "permission_denied" error for the failed listen. - var queryId; - if (!query) { - queryId = 'default'; - } - else { - queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$'); - } - var listen = this.removeListen_(pathString, queryId); - if (listen && listen.onComplete) - listen.onComplete('permission_denied'); - }; - /** - * @param {!string} pathString - * @param {!string} queryId - * @return {{queries:Array., onComplete:function(string)}} - * @private - */ - PersistentConnection.prototype.removeListen_ = function (pathString, queryId) { - var normalizedPathString = new Path(pathString).toString(); // normalize path. - var listen; - if (this.listens_[normalizedPathString] !== undefined) { - listen = this.listens_[normalizedPathString][queryId]; - delete this.listens_[normalizedPathString][queryId]; - if (util.getCount(this.listens_[normalizedPathString]) === 0) { - delete this.listens_[normalizedPathString]; - } - } - else { - // all listens for this path has already been removed - listen = undefined; - } - return listen; - }; - PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) { - log('Auth token revoked: ' + statusCode + '/' + explanation); - this.authToken_ = null; - this.forceTokenRefresh_ = true; - this.realtime_.close(); - if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { - // We'll wait a couple times before logging the warning / increasing the - // retry period since oauth tokens will report as "invalid" if they're - // just expired. Plus there may be transient issues that resolve themselves. - this.invalidAuthTokenCount_++; - if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) { - // Set a long reconnect delay because recovery is unlikely - this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; - // Notify the auth token provider that the token is invalid, which will log - // a warning - this.authTokenProvider_.notifyForInvalidToken(); - } - } - }; - PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) { - if (this.securityDebugCallback_) { - this.securityDebugCallback_(body); - } - else { - if ('msg' in body) { - console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); - } - } - }; - PersistentConnection.prototype.restoreState_ = function () { - var _this = this; - //Re-authenticate ourselves if we have a credential stored. - this.tryAuth(); - // Puts depend on having received the corresponding data update from the server before they complete, so we must - // make sure to send listens before puts. - util.forEach(this.listens_, function (pathString, queries) { - util.forEach(queries, function (key, listenSpec) { - _this.sendListen_(listenSpec); - }); - }); - for (var i = 0; i < this.outstandingPuts_.length; i++) { - if (this.outstandingPuts_[i]) - this.sendPut_(i); - } - while (this.onDisconnectRequestQueue_.length) { - var request = this.onDisconnectRequestQueue_.shift(); - this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); - } - }; - /** - * Sends client stats for first connection - * @private - */ - PersistentConnection.prototype.sendConnectStats_ = function () { - var stats = {}; - var clientName = 'js'; - if (util.CONSTANTS.NODE_ADMIN) { - clientName = 'admin_node'; - } - else if (util.CONSTANTS.NODE_CLIENT) { - clientName = 'node'; - } - stats['sdk.' + clientName + '.' + firebase.SDK_VERSION.replace(/\./g, '-')] = 1; - if (util.isMobileCordova()) { - stats['framework.cordova'] = 1; - } - else if (util.isReactNative()) { - stats['framework.reactnative'] = 1; - } - this.reportStats(stats); - }; - /** - * @return {boolean} - * @private - */ - PersistentConnection.prototype.shouldReconnect_ = function () { - var online = OnlineMonitor.getInstance().currentlyOnline(); - return util.isEmpty(this.interruptReasons_) && online; - }; - /** - * @private - */ - PersistentConnection.nextPersistentConnectionId_ = 0; - /** - * Counter for number of connections created. Mainly used for tagging in the logs - * @type {number} - * @private - */ - PersistentConnection.nextConnectionId_ = 0; - return PersistentConnection; -}(ServerActions)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An implementation of ServerActions that communicates with the server via REST requests. - * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full - * persistent connection (using WebSockets or long-polling) - */ -var ReadonlyRestClient = /** @class */ (function (_super) { - tslib_1.__extends(ReadonlyRestClient, _super); - /** - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param {AuthTokenProvider} authTokenProvider_ - * @implements {ServerActions} - */ - function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) { - var _this = _super.call(this) || this; - _this.repoInfo_ = repoInfo_; - _this.onDataUpdate_ = onDataUpdate_; - _this.authTokenProvider_ = authTokenProvider_; - /** @private {function(...[*])} */ - _this.log_ = logWrapper('p:rest:'); - /** - * We don't actually need to track listens, except to prevent us calling an onComplete for a listen - * that's been removed. :-/ - * - * @private {!Object.} - */ - _this.listens_ = {}; - return _this; - } - ReadonlyRestClient.prototype.reportStats = function (stats) { - throw new Error('Method not implemented.'); - }; - /** - * @param {!Query} query - * @param {?number=} tag - * @return {string} - * @private - */ - ReadonlyRestClient.getListenId_ = function (query, tag) { - if (tag !== undefined) { - return 'tag$' + tag; - } - else { - util.assert(query.getQueryParams().isDefault(), "should have a tag if it's not a default query."); - return query.path.toString(); - } - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) { - var _this = this; - var pathString = query.path.toString(); - this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier()); - // Mark this listener so we can tell if it's removed. - var listenId = ReadonlyRestClient.getListenId_(query, tag); - var thisListen = {}; - this.listens_[listenId] = thisListen; - var queryStringParameters = query - .getQueryParams() - .toRestQueryStringParameters(); - this.restRequest_(pathString + '.json', queryStringParameters, function (error$$1, result) { - var data = result; - if (error$$1 === 404) { - data = null; - error$$1 = null; - } - if (error$$1 === null) { - _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); - } - if (util.safeGet(_this.listens_, listenId) === thisListen) { - var status_1; - if (!error$$1) { - status_1 = 'ok'; - } - else if (error$$1 == 401) { - status_1 = 'permission_denied'; - } - else { - status_1 = 'rest_error:' + error$$1; - } - onComplete(status_1, null); - } - }); - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.unlisten = function (query, tag) { - var listenId = ReadonlyRestClient.getListenId_(query, tag); - delete this.listens_[listenId]; - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.refreshAuthToken = function (token) { - // no-op since we just always call getToken. - }; - /** - * Performs a REST request to the given path, with the provided query string parameters, - * and any auth credentials we have. - * - * @param {!string} pathString - * @param {!Object.} queryStringParameters - * @param {?function(?number, *=)} callback - * @private - */ - ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) { - var _this = this; - if (queryStringParameters === void 0) { queryStringParameters = {}; } - queryStringParameters['format'] = 'export'; - this.authTokenProvider_ - .getToken(/*forceRefresh=*/ false) - .then(function (authTokenData) { - var authToken = authTokenData && authTokenData.accessToken; - if (authToken) { - queryStringParameters['auth'] = authToken; - } - var url = (_this.repoInfo_.secure ? 'https://' : 'http://') + - _this.repoInfo_.host + - pathString + - '?' + - 'ns=' + - _this.repoInfo_.namespace + - util.querystring(queryStringParameters); - _this.log_('Sending REST request for ' + url); - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function () { - if (callback && xhr.readyState === 4) { - _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); - var res = null; - if (xhr.status >= 200 && xhr.status < 300) { - try { - res = util.jsonEval(xhr.responseText); - } - catch (e) { - warn('Failed to parse JSON response for ' + - url + - ': ' + - xhr.responseText); - } - callback(null, res); - } - else { - // 401 and 404 are expected. - if (xhr.status !== 401 && xhr.status !== 404) { - warn('Got unsuccessful REST response for ' + - url + - ' Status: ' + - xhr.status); - } - callback(xhr.status); - } - callback = null; - } - }; - xhr.open('GET', url, /*asynchronous=*/ true); - xhr.send(); - }); - }; - return ReadonlyRestClient; -}(ServerActions)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var INTERRUPT_REASON = 'repo_interrupt'; -/** - * A connection to a single data repository. - */ -var Repo = /** @class */ (function () { - /** - * @param {!RepoInfo} repoInfo_ - * @param {boolean} forceRestClient - * @param {!FirebaseApp} app - */ - function Repo(repoInfo_, forceRestClient, app) { - var _this = this; - this.repoInfo_ = repoInfo_; - this.app = app; - this.dataUpdateCount = 0; - this.statsListener_ = null; - this.eventQueue_ = new EventQueue(); - this.nextWriteId_ = 1; - this.interceptServerDataCallback_ = null; - // A list of data pieces and paths to be set when this client disconnects. - this.onDisconnect_ = new SparseSnapshotTree(); - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @type {?PersistentConnection} - */ - this.persistentConnection_ = null; - /** @type {!AuthTokenProvider} */ - var authTokenProvider = new AuthTokenProvider(app); - this.stats_ = StatsManager.getCollection(repoInfo_); - if (forceRestClient || beingCrawled()) { - this.server_ = new ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider); - // Minor hack: Fire onConnect immediately, since there's no actual connection. - setTimeout(this.onConnectStatus_.bind(this, true), 0); - } - else { - var authOverride = app.options['databaseAuthVariableOverride']; - // Validate authOverride - if (typeof authOverride !== 'undefined' && authOverride !== null) { - if (typeof authOverride !== 'object') { - throw new Error('Only objects are supported for option databaseAuthVariableOverride'); - } - try { - util.stringify(authOverride); - } - catch (e) { - throw new Error('Invalid authOverride provided: ' + e); - } - } - this.persistentConnection_ = new PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride); - this.server_ = this.persistentConnection_; - } - authTokenProvider.addTokenChangeListener(function (token) { - _this.server_.refreshAuthToken(token); - }); - // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), - // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. - this.statsReporter_ = StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter(_this.stats_, _this.server_); }); - this.transactions_init_(); - // Used for .info. - this.infoData_ = new SnapshotHolder(); - this.infoSyncTree_ = new SyncTree({ - startListening: function (query, tag, currentHashFn, onComplete) { - var infoEvents = []; - var node = _this.infoData_.getNode(query.path); - // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events - // on initial data... - if (!node.isEmpty()) { - infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node); - setTimeout(function () { - onComplete('ok'); - }, 0); - } - return infoEvents; - }, - stopListening: function () { } - }); - this.updateInfo_('connected', false); - this.serverSyncTree_ = new SyncTree({ - startListening: function (query, tag, currentHashFn, onComplete) { - _this.server_.listen(query, currentHashFn, tag, function (status, data) { - var events = onComplete(status, data); - _this.eventQueue_.raiseEventsForChangedPath(query.path, events); - }); - // No synchronous events for network-backed sync trees - return []; - }, - stopListening: function (query, tag) { - _this.server_.unlisten(query, tag); - } - }); - } - /** - * @return {string} The URL corresponding to the root of this Firebase. - */ - Repo.prototype.toString = function () { - return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); - }; - /** - * @return {!string} The namespace represented by the repo. - */ - Repo.prototype.name = function () { - return this.repoInfo_.namespace; - }; - /** - * @return {!number} The time in milliseconds, taking the server offset into account if we have one. - */ - Repo.prototype.serverTime = function () { - var offsetNode = this.infoData_.getNode(new Path('.info/serverTimeOffset')); - var offset = offsetNode.val() || 0; - return new Date().getTime() + offset; - }; - /** - * Generate ServerValues using some variables from the repo object. - * @return {!Object} - */ - Repo.prototype.generateServerValues = function () { - return generateWithValues({ - timestamp: this.serverTime() - }); - }; - /** - * Called by realtime when we get new messages from the server. - * - * @private - * @param {string} pathString - * @param {*} data - * @param {boolean} isMerge - * @param {?number} tag - */ - Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) { - // For testing. - this.dataUpdateCount++; - var path = new Path(pathString); - data = this.interceptServerDataCallback_ - ? this.interceptServerDataCallback_(pathString, data) - : data; - var events = []; - if (tag) { - if (isMerge) { - var taggedChildren = util.map(data, function (raw) { - return nodeFromJSON$1(raw); - }); - events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag); - } - else { - var taggedSnap = nodeFromJSON$1(data); - events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag); - } - } - else if (isMerge) { - var changedChildren = util.map(data, function (raw) { - return nodeFromJSON$1(raw); - }); - events = this.serverSyncTree_.applyServerMerge(path, changedChildren); - } - else { - var snap = nodeFromJSON$1(data); - events = this.serverSyncTree_.applyServerOverwrite(path, snap); - } - var affectedPath = path; - if (events.length > 0) { - // Since we have a listener outstanding for each transaction, receiving any events - // is a proxy for some change having occurred. - affectedPath = this.rerunTransactions_(path); - } - this.eventQueue_.raiseEventsForChangedPath(affectedPath, events); - }; - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @param {?function(!string, *):*} callback - * @private - */ - Repo.prototype.interceptServerData_ = function (callback) { - this.interceptServerDataCallback_ = callback; - }; - /** - * @param {!boolean} connectStatus - * @private - */ - Repo.prototype.onConnectStatus_ = function (connectStatus) { - this.updateInfo_('connected', connectStatus); - if (connectStatus === false) { - this.runOnDisconnectEvents_(); - } - }; - /** - * @param {!Object} updates - * @private - */ - Repo.prototype.onServerInfoUpdate_ = function (updates) { - var _this = this; - each(updates, function (value, key) { - _this.updateInfo_(key, value); - }); - }; - /** - * - * @param {!string} pathString - * @param {*} value - * @private - */ - Repo.prototype.updateInfo_ = function (pathString, value) { - var path = new Path('/.info/' + pathString); - var newNode = nodeFromJSON$1(value); - this.infoData_.updateSnapshot(path, newNode); - var events = this.infoSyncTree_.applyServerOverwrite(path, newNode); - this.eventQueue_.raiseEventsForChangedPath(path, events); - }; - /** - * @return {!number} - * @private - */ - Repo.prototype.getNextWriteId_ = function () { - return this.nextWriteId_++; - }; - /** - * @param {!Path} path - * @param {*} newVal - * @param {number|string|null} newPriority - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) { - var _this = this; - this.log_('set', { - path: path.toString(), - value: newVal, - priority: newPriority - }); - // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or - // (b) store unresolved paths on JSON parse - var serverValues = this.generateServerValues(); - var newNodeUnresolved = nodeFromJSON$1(newVal, newPriority); - var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - var writeId = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true); - this.eventQueue_.queueEvents(events); - this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) { - var success = status === 'ok'; - if (!success) { - warn('set at ' + path + ' failed: ' + status); - } - var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success); - _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents); - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - var affectedPath = this.abortTransactions_(path); - this.rerunTransactions_(affectedPath); - // We queued the events above, so just flush the queue here - this.eventQueue_.raiseEventsForChangedPath(affectedPath, []); - }; - /** - * @param {!Path} path - * @param {!Object} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.update = function (path, childrenToMerge, onComplete) { - var _this = this; - this.log_('update', { path: path.toString(), value: childrenToMerge }); - // Start with our existing data and merge each child into it. - var empty = true; - var serverValues = this.generateServerValues(); - var changedChildren = {}; - util.forEach(childrenToMerge, function (changedKey, changedValue) { - empty = false; - var newNodeUnresolved = nodeFromJSON$1(changedValue); - changedChildren[changedKey] = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - }); - if (!empty) { - var writeId_1 = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1); - this.eventQueue_.queueEvents(events); - this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) { - var success = status === 'ok'; - if (!success) { - warn('update at ' + path + ' failed: ' + status); - } - var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success); - var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path; - _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents); - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - util.forEach(childrenToMerge, function (changedPath) { - var affectedPath = _this.abortTransactions_(path.child(changedPath)); - _this.rerunTransactions_(affectedPath); - }); - // We queued the events above, so just flush the queue here - this.eventQueue_.raiseEventsForChangedPath(path, []); - } - else { - log("update() called with empty data. Don't do anything."); - this.callOnCompleteCallback(onComplete, 'ok'); - } - }; - /** - * Applies all of the changes stored up in the onDisconnect_ tree. - * @private - */ - Repo.prototype.runOnDisconnectEvents_ = function () { - var _this = this; - this.log_('onDisconnectEvents'); - var serverValues = this.generateServerValues(); - var resolvedOnDisconnectTree = resolveDeferredValueTree(this.onDisconnect_, serverValues); - var events = []; - resolvedOnDisconnectTree.forEachTree(Path.Empty, function (path, snap) { - events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap)); - var affectedPath = _this.abortTransactions_(path); - _this.rerunTransactions_(affectedPath); - }); - this.onDisconnect_ = new SparseSnapshotTree(); - this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events); - }; - /** - * @param {!Path} path - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectCancel = function (path, onComplete) { - var _this = this; - this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.forget(path); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} value - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectSet = function (path, value, onComplete) { - var _this = this; - var newNode = nodeFromJSON$1(value); - this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.remember(path, newNode); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} value - * @param {*} priority - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) { - var _this = this; - var newNode = nodeFromJSON$1(value, priority); - this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.remember(path, newNode); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) { - var _this = this; - if (util.isEmpty(childrenToMerge)) { - log("onDisconnect().update() called with empty data. Don't do anything."); - this.callOnCompleteCallback(onComplete, 'ok'); - return; - } - this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) { - if (status === 'ok') { - util.forEach(childrenToMerge, function (childName, childNode) { - var newChildNode = nodeFromJSON$1(childNode); - _this.onDisconnect_.remember(path.child(childName), newChildNode); - }); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - */ - Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) { - var events; - if (query.path.getFront() === '.info') { - events = this.infoSyncTree_.addEventRegistration(query, eventRegistration); - } - else { - events = this.serverSyncTree_.addEventRegistration(query, eventRegistration); - } - this.eventQueue_.raiseEventsAtPath(query.path, events); - }; - /** - * @param {!Query} query - * @param {?EventRegistration} eventRegistration - */ - Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) { - // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof - // a little bit by handling the return values anyways. - var events; - if (query.path.getFront() === '.info') { - events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration); - } - else { - events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration); - } - this.eventQueue_.raiseEventsAtPath(query.path, events); - }; - Repo.prototype.interrupt = function () { - if (this.persistentConnection_) { - this.persistentConnection_.interrupt(INTERRUPT_REASON); - } - }; - Repo.prototype.resume = function () { - if (this.persistentConnection_) { - this.persistentConnection_.resume(INTERRUPT_REASON); - } - }; - Repo.prototype.stats = function (showDelta) { - if (showDelta === void 0) { showDelta = false; } - if (typeof console === 'undefined') - return; - var stats; - if (showDelta) { - if (!this.statsListener_) - this.statsListener_ = new StatsListener(this.stats_); - stats = this.statsListener_.get(); - } - else { - stats = this.stats_.get(); - } - var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) { - return Math.max(currentValue.length, previousValue); - }, 0); - util.forEach(stats, function (stat, value) { - // pad stat names to be the same length (plus 2 extra spaces). - for (var i = stat.length; i < longestName + 2; i++) - stat += ' '; - console.log(stat + value); - }); - }; - Repo.prototype.statsIncrementCounter = function (metric) { - this.stats_.incrementCounter(metric); - this.statsReporter_.includeStat(metric); - }; - /** - * @param {...*} var_args - * @private - */ - Repo.prototype.log_ = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var prefix = ''; - if (this.persistentConnection_) { - prefix = this.persistentConnection_.id + ':'; - } - log.apply(void 0, [prefix].concat(var_args)); - }; - /** - * @param {?function(?Error, *=)} callback - * @param {!string} status - * @param {?string=} errorReason - */ - Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) { - if (callback) { - exceptionGuard(function () { - if (status == 'ok') { - callback(null); - } - else { - var code = (status || 'error').toUpperCase(); - var message = code; - if (errorReason) - message += ': ' + errorReason; - var error$$1 = new Error(message); - error$$1.code = code; - callback(error$$1); - } - }); - } - }; - Object.defineProperty(Repo.prototype, "database", { - get: function () { - return this.__database || (this.__database = new Database(this)); - }, - enumerable: true, - configurable: true - }); - return Repo; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node - * - * @constructor - * @implements {NodeFilter} - */ -var RangedFilter = /** @class */ (function () { - /** - * @param {!QueryParams} params - */ - function RangedFilter(params) { - this.indexedFilter_ = new IndexedFilter(params.getIndex()); - this.index_ = params.getIndex(); - this.startPost_ = RangedFilter.getStartPost_(params); - this.endPost_ = RangedFilter.getEndPost_(params); - } - /** - * @return {!NamedNode} - */ - RangedFilter.prototype.getStartPost = function () { - return this.startPost_; - }; - /** - * @return {!NamedNode} - */ - RangedFilter.prototype.getEndPost = function () { - return this.endPost_; - }; - /** - * @param {!NamedNode} node - * @return {boolean} - */ - RangedFilter.prototype.matches = function (node) { - return (this.index_.compare(this.getStartPost(), node) <= 0 && - this.index_.compare(node, this.getEndPost()) <= 0); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - if (!this.matches(new NamedNode(key, newChild))) { - newChild = ChildrenNode.EMPTY_NODE; - } - return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - if (newSnap.isLeafNode()) { - // Make sure we have a children node with the correct index, not a leaf node; - newSnap = ChildrenNode.EMPTY_NODE; - } - var filtered = newSnap.withIndex(this.index_); - // Don't support priorities on queries - filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); - var self = this; - newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (!self.matches(new NamedNode(key, childNode))) { - filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); - } - }); - return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - // Don't support priorities on queries - return oldSnap; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.filtersNodes = function () { - return true; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.getIndexedFilter = function () { - return this.indexedFilter_; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.getIndex = function () { - return this.index_; - }; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - RangedFilter.getStartPost_ = function (params) { - if (params.hasStart()) { - var startName = params.getIndexStartName(); - return params.getIndex().makePost(params.getIndexStartValue(), startName); - } - else { - return params.getIndex().minPost(); - } - }; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - RangedFilter.getEndPost_ = function (params) { - if (params.hasEnd()) { - var endName = params.getIndexEndName(); - return params.getIndex().makePost(params.getIndexEndValue(), endName); - } - else { - return params.getIndex().maxPost(); - } - }; - return RangedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible - * - * @constructor - * @implements {NodeFilter} - */ -var LimitedFilter = /** @class */ (function () { - /** - * @param {!QueryParams} params - */ - function LimitedFilter(params) { - this.rangedFilter_ = new RangedFilter(params); - this.index_ = params.getIndex(); - this.limit_ = params.getLimit(); - this.reverse_ = !params.isViewFromLeft(); - } - /** - * @inheritDoc - */ - LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { - newChild = ChildrenNode.EMPTY_NODE; - } - if (snap.getImmediateChild(key).equals(newChild)) { - // No change - return snap; - } - else if (snap.numChildren() < this.limit_) { - return this.rangedFilter_ - .getIndexedFilter() - .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); - } - else { - return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); - } - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - var filtered; - if (newSnap.isLeafNode() || newSnap.isEmpty()) { - // Make sure we have a children node with the correct index, not a leaf node; - filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); - } - else { - if (this.limit_ * 2 < newSnap.numChildren() && - newSnap.isIndexed(this.index_)) { - // Easier to build up a snapshot, since what we're given has more than twice the elements we want - filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); - // anchor to the startPost, endPost, or last element as appropriate - var iterator = void 0; - if (this.reverse_) { - iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); - } - else { - iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); - } - var count = 0; - while (iterator.hasNext() && count < this.limit_) { - var next = iterator.getNext(); - var inRange = void 0; - if (this.reverse_) { - inRange = - this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0; - } - else { - inRange = - this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0; - } - if (inRange) { - filtered = filtered.updateImmediateChild(next.name, next.node); - count++; - } - else { - // if we have reached the end post, we cannot keep adding elemments - break; - } - } - } - else { - // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one - filtered = newSnap.withIndex(this.index_); - // Don't support priorities on queries - filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); - var startPost = void 0; - var endPost = void 0; - var cmp = void 0; - var iterator = void 0; - if (this.reverse_) { - iterator = filtered.getReverseIterator(this.index_); - startPost = this.rangedFilter_.getEndPost(); - endPost = this.rangedFilter_.getStartPost(); - var indexCompare_1 = this.index_.getCompare(); - cmp = function (a, b) { return indexCompare_1(b, a); }; - } - else { - iterator = filtered.getIterator(this.index_); - startPost = this.rangedFilter_.getStartPost(); - endPost = this.rangedFilter_.getEndPost(); - cmp = this.index_.getCompare(); - } - var count = 0; - var foundStartPost = false; - while (iterator.hasNext()) { - var next = iterator.getNext(); - if (!foundStartPost && cmp(startPost, next) <= 0) { - // start adding - foundStartPost = true; - } - var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0; - if (inRange) { - count++; - } - else { - filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); - } - } - } - } - return this.rangedFilter_ - .getIndexedFilter() - .updateFullNode(oldSnap, filtered, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - // Don't support priorities on queries - return oldSnap; - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.filtersNodes = function () { - return true; - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.getIndexedFilter = function () { - return this.rangedFilter_.getIndexedFilter(); - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.getIndex = function () { - return this.index_; - }; - /** - * @param {!Node} snap - * @param {string} childKey - * @param {!Node} childSnap - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} changeAccumulator - * @return {!Node} - * @private - */ - LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) { - // TODO: rename all cache stuff etc to general snap terminology - var cmp; - if (this.reverse_) { - var indexCmp_1 = this.index_.getCompare(); - cmp = function (a, b) { return indexCmp_1(b, a); }; - } - else { - cmp = this.index_.getCompare(); - } - var oldEventCache = snap; - util.assert(oldEventCache.numChildren() == this.limit_, ''); - var newChildNamedNode = new NamedNode(childKey, childSnap); - var windowBoundary = this.reverse_ - ? oldEventCache.getFirstChild(this.index_) - : oldEventCache.getLastChild(this.index_); - var inRange = this.rangedFilter_.matches(newChildNamedNode); - if (oldEventCache.hasChild(childKey)) { - var oldChildSnap = oldEventCache.getImmediateChild(childKey); - var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); - while (nextChild != null && - (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) { - // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't - // been applied to the limited filter yet. Ignore this next child which will be updated later in - // the limited filter... - nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); - } - var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); - var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; - if (remainsInWindow) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childChangedChange(childKey, childSnap, oldChildSnap)); - } - return oldEventCache.updateImmediateChild(childKey, childSnap); - } - else { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childRemovedChange(childKey, oldChildSnap)); - } - var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); - var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); - if (nextChildInRange) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childAddedChange(nextChild.name, nextChild.node)); - } - return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); - } - else { - return newEventCache; - } - } - } - else if (childSnap.isEmpty()) { - // we're deleting a node, but it was not in the window, so ignore it - return snap; - } - else if (inRange) { - if (cmp(windowBoundary, newChildNamedNode) >= 0) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childRemovedChange(windowBoundary.name, windowBoundary.node)); - changeAccumulator.trackChildChange(Change.childAddedChange(childKey, childSnap)); - } - return oldEventCache - .updateImmediateChild(childKey, childSnap) - .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); - } - else { - return snap; - } - } - else { - return snap; - } - }; - return LimitedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a - * range to be returned for a particular location. It is assumed that validation of parameters is done at the - * user-facing API level, so it is not done here. - * @constructor - */ -var QueryParams = /** @class */ (function () { - function QueryParams() { - this.limitSet_ = false; - this.startSet_ = false; - this.startNameSet_ = false; - this.endSet_ = false; - this.endNameSet_ = false; - this.limit_ = 0; - this.viewFrom_ = ''; - this.indexStartValue_ = null; - this.indexStartName_ = ''; - this.indexEndValue_ = null; - this.indexEndName_ = ''; - this.index_ = PRIORITY_INDEX; - } - /** - * @return {boolean} - */ - QueryParams.prototype.hasStart = function () { - return this.startSet_; - }; - /** - * @return {boolean} True if it would return from left. - */ - QueryParams.prototype.isViewFromLeft = function () { - if (this.viewFrom_ === '') { - // limit(), rather than limitToFirst or limitToLast was called. - // This means that only one of startSet_ and endSet_ is true. Use them - // to calculate which side of the view to anchor to. If neither is set, - // anchor to the end. - return this.startSet_; - } - else { - return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT); - } - }; - /** - * Only valid to call if hasStart() returns true - * @return {*} - */ - QueryParams.prototype.getIndexStartValue = function () { - util.assert(this.startSet_, 'Only valid if start has been set'); - return this.indexStartValue_; - }; - /** - * Only valid to call if hasStart() returns true. - * Returns the starting key name for the range defined by these query parameters - * @return {!string} - */ - QueryParams.prototype.getIndexStartName = function () { - util.assert(this.startSet_, 'Only valid if start has been set'); - if (this.startNameSet_) { - return this.indexStartName_; - } - else { - return MIN_NAME; - } - }; - /** - * @return {boolean} - */ - QueryParams.prototype.hasEnd = function () { - return this.endSet_; - }; - /** - * Only valid to call if hasEnd() returns true. - * @return {*} - */ - QueryParams.prototype.getIndexEndValue = function () { - util.assert(this.endSet_, 'Only valid if end has been set'); - return this.indexEndValue_; - }; - /** - * Only valid to call if hasEnd() returns true. - * Returns the end key name for the range defined by these query parameters - * @return {!string} - */ - QueryParams.prototype.getIndexEndName = function () { - util.assert(this.endSet_, 'Only valid if end has been set'); - if (this.endNameSet_) { - return this.indexEndName_; - } - else { - return MAX_NAME; - } - }; - /** - * @return {boolean} - */ - QueryParams.prototype.hasLimit = function () { - return this.limitSet_; - }; - /** - * @return {boolean} True if a limit has been set and it has been explicitly anchored - */ - QueryParams.prototype.hasAnchoredLimit = function () { - return this.limitSet_ && this.viewFrom_ !== ''; - }; - /** - * Only valid to call if hasLimit() returns true - * @return {!number} - */ - QueryParams.prototype.getLimit = function () { - util.assert(this.limitSet_, 'Only valid if limit has been set'); - return this.limit_; - }; - /** - * @return {!Index} - */ - QueryParams.prototype.getIndex = function () { - return this.index_; - }; - /** - * @return {!QueryParams} - * @private - */ - QueryParams.prototype.copy_ = function () { - var copy = new QueryParams(); - copy.limitSet_ = this.limitSet_; - copy.limit_ = this.limit_; - copy.startSet_ = this.startSet_; - copy.indexStartValue_ = this.indexStartValue_; - copy.startNameSet_ = this.startNameSet_; - copy.indexStartName_ = this.indexStartName_; - copy.endSet_ = this.endSet_; - copy.indexEndValue_ = this.indexEndValue_; - copy.endNameSet_ = this.endNameSet_; - copy.indexEndName_ = this.indexEndName_; - copy.index_ = this.index_; - copy.viewFrom_ = this.viewFrom_; - return copy; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limit = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = ''; - return newParams; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limitToFirst = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT; - return newParams; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limitToLast = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT; - return newParams; - }; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - QueryParams.prototype.startAt = function (indexValue, key) { - var newParams = this.copy_(); - newParams.startSet_ = true; - if (!(indexValue !== undefined)) { - indexValue = null; - } - newParams.indexStartValue_ = indexValue; - if (key != null) { - newParams.startNameSet_ = true; - newParams.indexStartName_ = key; - } - else { - newParams.startNameSet_ = false; - newParams.indexStartName_ = ''; - } - return newParams; - }; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - QueryParams.prototype.endAt = function (indexValue, key) { - var newParams = this.copy_(); - newParams.endSet_ = true; - if (!(indexValue !== undefined)) { - indexValue = null; - } - newParams.indexEndValue_ = indexValue; - if (key !== undefined) { - newParams.endNameSet_ = true; - newParams.indexEndName_ = key; - } - else { - newParams.endNameSet_ = false; - newParams.indexEndName_ = ''; - } - return newParams; - }; - /** - * @param {!Index} index - * @return {!QueryParams} - */ - QueryParams.prototype.orderBy = function (index) { - var newParams = this.copy_(); - newParams.index_ = index; - return newParams; - }; - /** - * @return {!Object} - */ - QueryParams.prototype.getQueryObject = function () { - var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_; - var obj = {}; - if (this.startSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_; - if (this.startNameSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_; - } - } - if (this.endSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_; - if (this.endNameSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_; - } - } - if (this.limitSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_; - var viewFrom = this.viewFrom_; - if (viewFrom === '') { - if (this.isViewFromLeft()) { - viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT; - } - else { - viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT; - } - } - obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom; - } - // For now, priority index is the default, so we only specify if it's some other index - if (this.index_ !== PRIORITY_INDEX) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString(); - } - return obj; - }; - /** - * @return {boolean} - */ - QueryParams.prototype.loadsAllData = function () { - return !(this.startSet_ || this.endSet_ || this.limitSet_); - }; - /** - * @return {boolean} - */ - QueryParams.prototype.isDefault = function () { - return this.loadsAllData() && this.index_ == PRIORITY_INDEX; - }; - /** - * @return {!NodeFilter} - */ - QueryParams.prototype.getNodeFilter = function () { - if (this.loadsAllData()) { - return new IndexedFilter(this.getIndex()); - } - else if (this.hasLimit()) { - return new LimitedFilter(this); - } - else { - return new RangedFilter(this); - } - }; - /** - * Returns a set of REST query string parameters representing this query. - * - * @return {!Object.} query string parameters - */ - QueryParams.prototype.toRestQueryStringParameters = function () { - var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_; - var qs = {}; - if (this.isDefault()) { - return qs; - } - var orderBy; - if (this.index_ === PRIORITY_INDEX) { - orderBy = REST_CONSTANTS.PRIORITY_INDEX; - } - else if (this.index_ === VALUE_INDEX) { - orderBy = REST_CONSTANTS.VALUE_INDEX; - } - else if (this.index_ === KEY_INDEX) { - orderBy = REST_CONSTANTS.KEY_INDEX; - } - else { - util.assert(this.index_ instanceof PathIndex, 'Unrecognized index type!'); - orderBy = this.index_.toString(); - } - qs[REST_CONSTANTS.ORDER_BY] = util.stringify(orderBy); - if (this.startSet_) { - qs[REST_CONSTANTS.START_AT] = util.stringify(this.indexStartValue_); - if (this.startNameSet_) { - qs[REST_CONSTANTS.START_AT] += ',' + util.stringify(this.indexStartName_); - } - } - if (this.endSet_) { - qs[REST_CONSTANTS.END_AT] = util.stringify(this.indexEndValue_); - if (this.endNameSet_) { - qs[REST_CONSTANTS.END_AT] += ',' + util.stringify(this.indexEndName_); - } - } - if (this.limitSet_) { - if (this.isViewFromLeft()) { - qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_; - } - else { - qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_; - } - } - return qs; - }; - /** - * Wire Protocol Constants - * @const - * @enum {string} - * @private - */ - QueryParams.WIRE_PROTOCOL_CONSTANTS_ = { - INDEX_START_VALUE: 'sp', - INDEX_START_NAME: 'sn', - INDEX_END_VALUE: 'ep', - INDEX_END_NAME: 'en', - LIMIT: 'l', - VIEW_FROM: 'vf', - VIEW_FROM_LEFT: 'l', - VIEW_FROM_RIGHT: 'r', - INDEX: 'i' - }; - /** - * REST Query Constants - * @const - * @enum {string} - * @private - */ - QueryParams.REST_QUERY_CONSTANTS_ = { - ORDER_BY: 'orderBy', - PRIORITY_INDEX: '$priority', - VALUE_INDEX: '$value', - KEY_INDEX: '$key', - START_AT: 'startAt', - END_AT: 'endAt', - LIMIT_TO_FIRST: 'limitToFirst', - LIMIT_TO_LAST: 'limitToLast' - }; - /** - * Default, empty query parameters - * @type {!QueryParams} - * @const - */ - QueryParams.DEFAULT = new QueryParams(); - return QueryParams; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Reference = /** @class */ (function (_super) { - tslib_1.__extends(Reference, _super); - /** - * Call options: - * new Reference(Repo, Path) or - * new Reference(url: string, string|RepoManager) - * - * Externally - this is the firebase.database.Reference type. - * - * @param {!Repo} repo - * @param {(!Path)} path - * @extends {Query} - */ - function Reference(repo, path) { - var _this = this; - if (!(repo instanceof Repo)) { - throw new Error('new Reference() no longer supported - use app.database().'); - } - // call Query's constructor, passing in the repo and path. - _this = _super.call(this, repo, path, QueryParams.DEFAULT, false) || this; - return _this; - } - /** @return {?string} */ - Reference.prototype.getKey = function () { - util.validateArgCount('Reference.key', 0, 0, arguments.length); - if (this.path.isEmpty()) - return null; - else - return this.path.getBack(); - }; - /** - * @param {!(string|Path)} pathString - * @return {!Reference} - */ - Reference.prototype.child = function (pathString) { - util.validateArgCount('Reference.child', 1, 1, arguments.length); - if (typeof pathString === 'number') { - pathString = String(pathString); - } - else if (!(pathString instanceof Path)) { - if (this.path.getFront() === null) - validateRootPathString('Reference.child', 1, pathString, false); - else - validatePathString('Reference.child', 1, pathString, false); - } - return new Reference(this.repo, this.path.child(pathString)); - }; - /** @return {?Reference} */ - Reference.prototype.getParent = function () { - util.validateArgCount('Reference.parent', 0, 0, arguments.length); - var parentPath = this.path.parent(); - return parentPath === null ? null : new Reference(this.repo, parentPath); - }; - /** @return {!Reference} */ - Reference.prototype.getRoot = function () { - util.validateArgCount('Reference.root', 0, 0, arguments.length); - var ref = this; - while (ref.getParent() !== null) { - ref = ref.getParent(); - } - return ref; - }; - /** @return {!Database} */ - Reference.prototype.databaseProp = function () { - return this.repo.database; - }; - /** - * @param {*} newVal - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.set = function (newVal, onComplete) { - util.validateArgCount('Reference.set', 1, 2, arguments.length); - validateWritablePath('Reference.set', this.path); - validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false); - util.validateCallback('Reference.set', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo.setWithPriority(this.path, newVal, - /*priority=*/ null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.update = function (objectToMerge, onComplete) { - util.validateArgCount('Reference.update', 1, 2, arguments.length); - validateWritablePath('Reference.update', this.path); - if (Array.isArray(objectToMerge)) { - var newObjectToMerge = {}; - for (var i = 0; i < objectToMerge.length; ++i) { - newObjectToMerge['' + i] = objectToMerge[i]; - } - objectToMerge = newObjectToMerge; - warn('Passing an Array to Firebase.update() is deprecated. ' + - 'Use set() if you want to overwrite the existing data, or ' + - 'an Object with integer keys if you really do want to ' + - 'only update some of the children.'); - } - validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false); - util.validateCallback('Reference.update', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} newVal - * @param {string|number|null} newPriority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) { - util.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); - validateWritablePath('Reference.setWithPriority', this.path); - validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false); - validatePriority('Reference.setWithPriority', 2, newPriority, false); - util.validateCallback('Reference.setWithPriority', 3, onComplete, true); - if (this.getKey() === '.length' || this.getKey() === '.keys') - throw 'Reference.setWithPriority failed: ' + - this.getKey() + - ' is a read-only object.'; - var deferred = new util.Deferred(); - this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.remove = function (onComplete) { - util.validateArgCount('Reference.remove', 0, 1, arguments.length); - validateWritablePath('Reference.remove', this.path); - util.validateCallback('Reference.remove', 1, onComplete, true); - return this.set(null, onComplete); - }; - /** - * @param {function(*):*} transactionUpdate - * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete - * @param {boolean=} applyLocally - * @return {!Promise} - */ - Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) { - util.validateArgCount('Reference.transaction', 1, 3, arguments.length); - validateWritablePath('Reference.transaction', this.path); - util.validateCallback('Reference.transaction', 1, transactionUpdate, false); - util.validateCallback('Reference.transaction', 2, onComplete, true); - // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how - // to expose it. - validateBoolean('Reference.transaction', 3, applyLocally, true); - if (this.getKey() === '.length' || this.getKey() === '.keys') - throw 'Reference.transaction failed: ' + - this.getKey() + - ' is a read-only object.'; - if (applyLocally === undefined) - applyLocally = true; - var deferred = new util.Deferred(); - if (typeof onComplete === 'function') { - deferred.promise.catch(function () { }); - } - var promiseComplete = function (error$$1, committed, snapshot) { - if (error$$1) { - deferred.reject(error$$1); - } - else { - deferred.resolve(new TransactionResult(committed, snapshot)); - } - if (typeof onComplete === 'function') { - onComplete(error$$1, committed, snapshot); - } - }; - this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally); - return deferred.promise; - }; - /** - * @param {string|number|null} priority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.setPriority = function (priority, onComplete) { - util.validateArgCount('Reference.setPriority', 1, 2, arguments.length); - validateWritablePath('Reference.setPriority', this.path); - validatePriority('Reference.setPriority', 1, priority, false); - util.validateCallback('Reference.setPriority', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*=} value - * @param {function(?Error)=} onComplete - * @return {!Reference} - */ - Reference.prototype.push = function (value, onComplete) { - util.validateArgCount('Reference.push', 0, 2, arguments.length); - validateWritablePath('Reference.push', this.path); - validateFirebaseDataArg('Reference.push', 1, value, this.path, true); - util.validateCallback('Reference.push', 2, onComplete, true); - var now = this.repo.serverTime(); - var name = nextPushId(now); - // push() returns a ThennableReference whose promise is fulfilled with a regular Reference. - // We use child() to create handles to two different references. The first is turned into a - // ThennableReference below by adding then() and catch() methods and is used as the - // return value of push(). The second remains a regular Reference and is used as the fulfilled - // value of the first ThennableReference. - var thennablePushRef = this.child(name); - var pushRef = this.child(name); - var promise; - if (value != null) { - promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; }); - } - else { - promise = Promise.resolve(pushRef); - } - thennablePushRef.then = promise.then.bind(promise); - thennablePushRef.catch = promise.then.bind(promise, undefined); - if (typeof onComplete === 'function') { - promise.catch(function () { }); - } - return thennablePushRef; - }; - /** - * @return {!OnDisconnect} - */ - Reference.prototype.onDisconnect = function () { - validateWritablePath('Reference.onDisconnect', this.path); - return new OnDisconnect(this.repo, this.path); - }; - Object.defineProperty(Reference.prototype, "database", { - get: function () { - return this.databaseProp(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "key", { - get: function () { - return this.getKey(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "parent", { - get: function () { - return this.getParent(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "root", { - get: function () { - return this.getRoot(); - }, - enumerable: true, - configurable: true - }); - return Reference; -}(Query)); -/** - * Define reference constructor in various modules - * - * We are doing this here to avoid several circular - * dependency issues - */ -Query.__referenceConstructor = Reference; -SyncPoint.__referenceConstructor = Reference; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Node in a Tree. - */ -var TreeNode = /** @class */ (function () { - function TreeNode() { - // TODO: Consider making accessors that create children and value lazily or - // separate Internal / Leaf 'types'. - this.children = {}; - this.childCount = 0; - this.value = null; - } - return TreeNode; -}()); -/** - * A light-weight tree, traversable by path. Nodes can have both values and children. - * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty - * children. - */ -var Tree = /** @class */ (function () { - /** - * @template T - * @param {string=} name_ Optional name of the node. - * @param {Tree=} parent_ Optional parent node. - * @param {TreeNode=} node_ Optional node to wrap. - */ - function Tree(name_, parent_, node_) { - if (name_ === void 0) { name_ = ''; } - if (parent_ === void 0) { parent_ = null; } - if (node_ === void 0) { node_ = new TreeNode(); } - this.name_ = name_; - this.parent_ = parent_; - this.node_ = node_; - } - /** - * Returns a sub-Tree for the given path. - * - * @param {!(string|Path)} pathObj Path to look up. - * @return {!Tree.} Tree for path. - */ - Tree.prototype.subTree = function (pathObj) { - // TODO: Require pathObj to be Path? - var path = pathObj instanceof Path ? pathObj : new Path(pathObj); - var child = this, next; - while ((next = path.getFront()) !== null) { - var childNode = util.safeGet(child.node_.children, next) || new TreeNode(); - child = new Tree(next, child, childNode); - path = path.popFront(); - } - return child; - }; - /** - * Returns the data associated with this tree node. - * - * @return {?T} The data or null if no data exists. - */ - Tree.prototype.getValue = function () { - return this.node_.value; - }; - /** - * Sets data to this tree node. - * - * @param {!T} value Value to set. - */ - Tree.prototype.setValue = function (value) { - util.assert(typeof value !== 'undefined', 'Cannot set value to undefined'); - this.node_.value = value; - this.updateParents_(); - }; - /** - * Clears the contents of the tree node (its value and all children). - */ - Tree.prototype.clear = function () { - this.node_.value = null; - this.node_.children = {}; - this.node_.childCount = 0; - this.updateParents_(); - }; - /** - * @return {boolean} Whether the tree has any children. - */ - Tree.prototype.hasChildren = function () { - return this.node_.childCount > 0; - }; - /** - * @return {boolean} Whether the tree is empty (no value or children). - */ - Tree.prototype.isEmpty = function () { - return this.getValue() === null && !this.hasChildren(); - }; - /** - * Calls action for each child of this tree node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - Tree.prototype.forEachChild = function (action) { - var _this = this; - util.forEach(this.node_.children, function (child, childTree) { - action(new Tree(child, _this, childTree)); - }); - }; - /** - * Does a depth-first traversal of this node's descendants, calling action for each one. - * - * @param {function(!Tree.)} action Action to be called for each child. - * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to - * false. - * @param {boolean=} childrenFirst Whether to call action on children before calling it on - * parent. - */ - Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) { - if (includeSelf && !childrenFirst) - action(this); - this.forEachChild(function (child) { - child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst); - }); - if (includeSelf && childrenFirst) - action(this); - }; - /** - * Calls action on each ancestor node. - * - * @param {function(!Tree.)} action Action to be called on each parent; return - * true to abort. - * @param {boolean=} includeSelf Whether to call action on this node as well. - * @return {boolean} true if the action callback returned true. - */ - Tree.prototype.forEachAncestor = function (action, includeSelf) { - var node = includeSelf ? this : this.parent(); - while (node !== null) { - if (action(node)) { - return true; - } - node = node.parent(); - } - return false; - }; - /** - * Does a depth-first traversal of this node's descendants. When a descendant with a value - * is found, action is called on it and traversal does not continue inside the node. - * Action is *not* called on this node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - Tree.prototype.forEachImmediateDescendantWithValue = function (action) { - this.forEachChild(function (child) { - if (child.getValue() !== null) - action(child); - else - child.forEachImmediateDescendantWithValue(action); - }); - }; - /** - * @return {!Path} The path of this tree node, as a Path. - */ - Tree.prototype.path = function () { - return new Path(this.parent_ === null - ? this.name_ - : this.parent_.path() + '/' + this.name_); - }; - /** - * @return {string} The name of the tree node. - */ - Tree.prototype.name = function () { - return this.name_; - }; - /** - * @return {?Tree} The parent tree node, or null if this is the root of the tree. - */ - Tree.prototype.parent = function () { - return this.parent_; - }; - /** - * Adds or removes this child from its parent based on whether it's empty or not. - * - * @private - */ - Tree.prototype.updateParents_ = function () { - if (this.parent_ !== null) - this.parent_.updateChild_(this.name_, this); - }; - /** - * Adds or removes the passed child to this tree node, depending on whether it's empty. - * - * @param {string} childName The name of the child to update. - * @param {!Tree.} child The child to update. - * @private - */ - Tree.prototype.updateChild_ = function (childName, child) { - var childEmpty = child.isEmpty(); - var childExists = util.contains(this.node_.children, childName); - if (childEmpty && childExists) { - delete this.node_.children[childName]; - this.node_.childCount--; - this.updateParents_(); - } - else if (!childEmpty && !childExists) { - this.node_.children[childName] = child.node_; - this.node_.childCount++; - this.updateParents_(); - } - }; - return Tree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific -// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well -// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first. -// For now it's part of Repo, but in its own file. -/** - * @enum {number} - */ -var TransactionStatus; -(function (TransactionStatus) { - // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the - // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to - // mismatched hash. - TransactionStatus[TransactionStatus["RUN"] = 0] = "RUN"; - // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted - // or rejected yet). - TransactionStatus[TransactionStatus["SENT"] = 1] = "SENT"; - // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be - // removed when we get a chance to prune completed ones. - TransactionStatus[TransactionStatus["COMPLETED"] = 2] = "COMPLETED"; - // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made). - // If it comes back as unsuccessful, we'll abort it. - TransactionStatus[TransactionStatus["SENT_NEEDS_ABORT"] = 3] = "SENT_NEEDS_ABORT"; - // Temporary state used to mark transactions that need to be aborted. - TransactionStatus[TransactionStatus["NEEDS_ABORT"] = 4] = "NEEDS_ABORT"; -})(TransactionStatus || (TransactionStatus = {})); -/** - * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's - * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely. - * @type {number} - * @const - * @private - */ -Repo.MAX_TRANSACTION_RETRIES_ = 25; -/** - * Setup the transaction data structures - * @private - */ -Repo.prototype.transactions_init_ = function () { - /** - * Stores queues of outstanding transactions for Firebase locations. - * - * @type {!Tree.>} - * @private - */ - this.transactionQueueTree_ = new Tree(); -}; -/** - * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible. - * - * @param {!Path} path Path at which to do transaction. - * @param {function(*):*} transactionUpdate Update callback. - * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback. - * @param {boolean} applyLocally Whether or not to make intermediate results visible - */ -Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) { - this.log_('transaction on ' + path); - // Add a watch to make sure we get server updates. - var valueCallback = function () { }; - var watchRef = new Reference(this, path); - watchRef.on('value', valueCallback); - var unwatcher = function () { - watchRef.off('value', valueCallback); - }; - // Initialize transaction. - var transaction = { - path: path, - update: transactionUpdate, - onComplete: onComplete, - // One of TransactionStatus enums. - status: null, - // Used when combining transactions at different locations to figure out which one goes first. - order: LUIDGenerator(), - // Whether to raise local events for this transaction. - applyLocally: applyLocally, - // Count of how many times we've retried the transaction. - retryCount: 0, - // Function to call to clean up our .on() listener. - unwatcher: unwatcher, - // Stores why a transaction was aborted. - abortReason: null, - currentWriteId: null, - currentInputSnapshot: null, - currentOutputSnapshotRaw: null, - currentOutputSnapshotResolved: null - }; - // Run transaction initially. - var currentState = this.getLatestState_(path); - transaction.currentInputSnapshot = currentState; - var newVal = transaction.update(currentState.val()); - if (newVal === undefined) { - // Abort transaction. - transaction.unwatcher(); - transaction.currentOutputSnapshotRaw = null; - transaction.currentOutputSnapshotResolved = null; - if (transaction.onComplete) { - // We just set the input snapshot, so this cast should be safe - var snapshot = new DataSnapshot(transaction.currentInputSnapshot, new Reference(this, transaction.path), PRIORITY_INDEX); - transaction.onComplete(null, false, snapshot); - } - } - else { - validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); - // Mark as run and add to our queue. - transaction.status = TransactionStatus.RUN; - var queueNode = this.transactionQueueTree_.subTree(path); - var nodeQueue = queueNode.getValue() || []; - nodeQueue.push(transaction); - queueNode.setValue(nodeQueue); - // Update visibleData and raise events - // Note: We intentionally raise events after updating all of our transaction state, since the user could - // start new transactions from the event callbacks. - var priorityForNode = void 0; - if (typeof newVal === 'object' && - newVal !== null && - util.contains(newVal, '.priority')) { - priorityForNode = util.safeGet(newVal, '.priority'); - util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + - 'Priority must be a valid string, finite number, server value, or null.'); - } - else { - var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) || - ChildrenNode.EMPTY_NODE; - priorityForNode = currentNode.getPriority().val(); - } - priorityForNode /** @type {null|number|string} */ = priorityForNode; - var serverValues = this.generateServerValues(); - var newNodeUnresolved = nodeFromJSON$1(newVal, priorityForNode); - var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - transaction.currentOutputSnapshotRaw = newNodeUnresolved; - transaction.currentOutputSnapshotResolved = newNode; - transaction.currentWriteId = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally); - this.eventQueue_.raiseEventsForChangedPath(path, events); - this.sendReadyTransactions_(); - } -}; -/** - * @param {!Path} path - * @param {Array.=} excludeSets A specific set to exclude - * @return {Node} - * @private - */ -Repo.prototype.getLatestState_ = function (path, excludeSets) { - return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) || - ChildrenNode.EMPTY_NODE); -}; -/** - * Sends any already-run transactions that aren't waiting for outstanding transactions to - * complete. - * - * Externally it's called with no arguments, but it calls itself recursively with a particular - * transactionQueueTree node to recurse through the tree. - * - * @param {Tree.>=} node transactionQueueTree node to start at. - * @private - */ -Repo.prototype.sendReadyTransactions_ = function (node) { - var _this = this; - if (node === void 0) { node = this.transactionQueueTree_; } - // Before recursing, make sure any completed transactions are removed. - if (!node) { - this.pruneCompletedTransactionsBelowNode_(node); - } - if (node.getValue() !== null) { - var queue = this.buildTransactionQueue_(node); - util.assert(queue.length > 0, 'Sending zero length transaction queue'); - var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; }); - // If they're all run (and not sent), we can send them. Else, we must wait. - if (allRun) { - this.sendTransactionQueue_(node.path(), queue); - } - } - else if (node.hasChildren()) { - node.forEachChild(function (childNode) { - _this.sendReadyTransactions_(childNode); - }); - } -}; -/** - * Given a list of run transactions, send them to the server and then handle the result (success or failure). - * - * @param {!Path} path The location of the queue. - * @param {!Array.} queue Queue of transactions under the specified location. - * @private - */ -Repo.prototype.sendTransactionQueue_ = function (path, queue) { - var _this = this; - // Mark transactions as sent and increment retry count! - var setsToIgnore = queue.map(function (txn) { - return txn.currentWriteId; - }); - var latestState = this.getLatestState_(path, setsToIgnore); - var snapToSend = latestState; - var latestHash = latestState.hash(); - for (var i = 0; i < queue.length; i++) { - var txn = queue[i]; - util.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.'); - txn.status = TransactionStatus.SENT; - txn.retryCount++; - var relativePath = Path.relativePath(path, txn.path); - // If we've gotten to this point, the output snapshot must be defined. - snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw); - } - var dataToSend = snapToSend.val(true); - var pathToSend = path; - // Send the put. - this.server_.put(pathToSend.toString(), dataToSend, function (status) { - _this.log_('transaction put response', { - path: pathToSend.toString(), - status: status - }); - var events = []; - if (status === 'ok') { - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - for (var i = 0; i < queue.length; i++) { - queue[i].status = TransactionStatus.COMPLETED; - events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId)); - if (queue[i].onComplete) { - // We never unset the output snapshot, and given that this transaction is complete, it should be set - var node = queue[i].currentOutputSnapshotResolved; - var ref = new Reference(_this, queue[i].path); - var snapshot = new DataSnapshot(node, ref, PRIORITY_INDEX); - callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot)); - } - queue[i].unwatcher(); - } - // Now remove the completed transactions. - _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path)); - // There may be pending transactions that we can now send. - _this.sendReadyTransactions_(); - _this.eventQueue_.raiseEventsForChangedPath(path, events); - // Finally, trigger onComplete callbacks. - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - } - else { - // transactions are no longer sent. Update their status appropriately. - if (status === 'datastale') { - for (var i = 0; i < queue.length; i++) { - if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) - queue[i].status = TransactionStatus.NEEDS_ABORT; - else - queue[i].status = TransactionStatus.RUN; - } - } - else { - warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); - for (var i = 0; i < queue.length; i++) { - queue[i].status = TransactionStatus.NEEDS_ABORT; - queue[i].abortReason = status; - } - } - _this.rerunTransactions_(path); - } - }, latestHash); -}; -/** - * Finds all transactions dependent on the data at changedPath and reruns them. - * - * Should be called any time cached data changes. - * - * Return the highest path that was affected by rerunning transactions. This is the path at which events need to - * be raised for. - * - * @param {!Path} changedPath The path in mergedData that changed. - * @return {!Path} The rootmost path that was affected by rerunning transactions. - * @private - */ -Repo.prototype.rerunTransactions_ = function (changedPath) { - var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath); - var path = rootMostTransactionNode.path(); - var queue = this.buildTransactionQueue_(rootMostTransactionNode); - this.rerunTransactionQueue_(queue, path); - return path; -}; -/** - * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot). - * - * @param {Array.} queue The queue of transactions to run. - * @param {!Path} path The path the queue is for. - * @private - */ -Repo.prototype.rerunTransactionQueue_ = function (queue, path) { - if (queue.length === 0) { - return; // Nothing to do! - } - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - var events = []; - // Ignore all of the sets we're going to re-run. - var txnsToRerun = queue.filter(function (q) { - return q.status === TransactionStatus.RUN; - }); - var setsToIgnore = txnsToRerun.map(function (q) { - return q.currentWriteId; - }); - for (var i = 0; i < queue.length; i++) { - var transaction = queue[i]; - var relativePath = Path.relativePath(path, transaction.path); - var abortTransaction = false, abortReason = void 0; - util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); - if (transaction.status === TransactionStatus.NEEDS_ABORT) { - abortTransaction = true; - abortReason = transaction.abortReason; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - else if (transaction.status === TransactionStatus.RUN) { - if (transaction.retryCount >= Repo.MAX_TRANSACTION_RETRIES_) { - abortTransaction = true; - abortReason = 'maxretry'; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - else { - // This code reruns a transaction - var currentNode = this.getLatestState_(transaction.path, setsToIgnore); - transaction.currentInputSnapshot = currentNode; - var newData = queue[i].update(currentNode.val()); - if (newData !== undefined) { - validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); - var newDataNode = nodeFromJSON$1(newData); - var hasExplicitPriority = typeof newData === 'object' && - newData != null && - util.contains(newData, '.priority'); - if (!hasExplicitPriority) { - // Keep the old priority if there wasn't a priority explicitly specified. - newDataNode = newDataNode.updatePriority(currentNode.getPriority()); - } - var oldWriteId = transaction.currentWriteId; - var serverValues = this.generateServerValues(); - var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, serverValues); - transaction.currentOutputSnapshotRaw = newDataNode; - transaction.currentOutputSnapshotResolved = newNodeResolved; - transaction.currentWriteId = this.getNextWriteId_(); - // Mutates setsToIgnore in place - setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); - events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); - events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true)); - } - else { - abortTransaction = true; - abortReason = 'nodata'; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - } - } - this.eventQueue_.raiseEventsForChangedPath(path, events); - events = []; - if (abortTransaction) { - // Abort. - queue[i].status = TransactionStatus.COMPLETED; - // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data). - // So defer the unwatcher until we're done. - (function (unwatcher) { - setTimeout(unwatcher, Math.floor(0)); - })(queue[i].unwatcher); - if (queue[i].onComplete) { - if (abortReason === 'nodata') { - var ref = new Reference(this, queue[i].path); - // We set this field immediately, so it's safe to cast to an actual snapshot - var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot; - var snapshot = new DataSnapshot(lastInput, ref, PRIORITY_INDEX); - callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot)); - } - else { - callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null)); - } - } - } - } - // Clean up completed transactions. - this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_); - // Now fire callbacks, now that we're in a good, known state. - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - // Try to send the transaction result to the server. - this.sendReadyTransactions_(); -}; -/** - * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns - * the node for the given path if there are no pending transactions on any ancestor. - * - * @param {!Path} path The location to start at. - * @return {!Tree.>} The rootmost node with a transaction. - * @private - */ -Repo.prototype.getAncestorTransactionNode_ = function (path) { - var front; - // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions. - var transactionNode = this.transactionQueueTree_; - while ((front = path.getFront()) !== null && - transactionNode.getValue() === null) { - transactionNode = transactionNode.subTree(front); - path = path.popFront(); - } - return transactionNode; -}; -/** - * Builds the queue of all transactions at or below the specified transactionNode. - * - * @param {!Tree.>} transactionNode - * @return {Array.} The generated queue. - * @private - */ -Repo.prototype.buildTransactionQueue_ = function (transactionNode) { - // Walk any child transaction queues and aggregate them into a single queue. - var transactionQueue = []; - this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue); - // Sort them by the order the transactions were created. - transactionQueue.sort(function (a, b) { - return a.order - b.order; - }); - return transactionQueue; -}; -/** - * @param {!Tree.>} node - * @param {Array.} queue - * @private - */ -Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) { - var _this = this; - var nodeQueue = node.getValue(); - if (nodeQueue !== null) { - for (var i = 0; i < nodeQueue.length; i++) { - queue.push(nodeQueue[i]); - } - } - node.forEachChild(function (child) { - _this.aggregateTransactionQueuesForNode_(child, queue); - }); -}; -/** - * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. - * - * @param {!Tree.>} node - * @private - */ -Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) { - var _this = this; - var queue = node.getValue(); - if (queue) { - var to = 0; - for (var from = 0; from < queue.length; from++) { - if (queue[from].status !== TransactionStatus.COMPLETED) { - queue[to] = queue[from]; - to++; - } - } - queue.length = to; - node.setValue(queue.length > 0 ? queue : null); - } - node.forEachChild(function (childNode) { - _this.pruneCompletedTransactionsBelowNode_(childNode); - }); -}; -/** - * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update() - * since we consider them incompatible with transactions. - * - * @param {!Path} path Path for which we want to abort related transactions. - * @return {!Path} - * @private - */ -Repo.prototype.abortTransactions_ = function (path) { - var _this = this; - var affectedPath = this.getAncestorTransactionNode_(path).path(); - var transactionNode = this.transactionQueueTree_.subTree(path); - transactionNode.forEachAncestor(function (node) { - _this.abortTransactionsOnNode_(node); - }); - this.abortTransactionsOnNode_(transactionNode); - transactionNode.forEachDescendant(function (node) { - _this.abortTransactionsOnNode_(node); - }); - return affectedPath; -}; -/** - * Abort transactions stored in this transaction queue node. - * - * @param {!Tree.>} node Node to abort transactions for. - * @private - */ -Repo.prototype.abortTransactionsOnNode_ = function (node) { - var queue = node.getValue(); - if (queue !== null) { - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones - // can be immediately aborted and removed. - var events = []; - var lastSent = -1; - for (var i = 0; i < queue.length; i++) { - if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) { - // Already marked. No action needed. - } - else if (queue[i].status === TransactionStatus.SENT) { - util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); - lastSent = i; - // Mark transaction for abort when it comes back. - queue[i].status = TransactionStatus.SENT_NEEDS_ABORT; - queue[i].abortReason = 'set'; - } - else { - util.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort'); - // We can abort it immediately. - queue[i].unwatcher(); - events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true)); - if (queue[i].onComplete) { - var snapshot = null; - callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot)); - } - } - } - if (lastSent === -1) { - // We're not waiting for any sent transactions. We can clear the queue. - node.setValue(null); - } - else { - // Remove the transactions we aborted. - queue.length = lastSent + 1; - } - // Now fire the callbacks. - this.eventQueue_.raiseEventsForChangedPath(node.path(), events); - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - } -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** @const {string} */ -var DATABASE_URL_OPTION = 'databaseURL'; -var _staticInstance; -/** - * Creates and caches Repo instances. - */ -var RepoManager = /** @class */ (function () { - function RepoManager() { - /** - * @private {!Object.>} - */ - this.repos_ = {}; - /** - * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes). - * @private {boolean} - */ - this.useRestClient_ = false; - } - RepoManager.getInstance = function () { - if (!_staticInstance) { - _staticInstance = new RepoManager(); - } - return _staticInstance; - }; - // TODO(koss): Remove these functions unless used in tests? - RepoManager.prototype.interrupt = function () { - for (var appName in this.repos_) { - for (var dbUrl in this.repos_[appName]) { - this.repos_[appName][dbUrl].interrupt(); - } - } - }; - RepoManager.prototype.resume = function () { - for (var appName in this.repos_) { - for (var dbUrl in this.repos_[appName]) { - this.repos_[appName][dbUrl].resume(); - } - } - }; - /** - * This function should only ever be called to CREATE a new database instance. - * - * @param {!FirebaseApp} app - * @return {!Database} - */ - RepoManager.prototype.databaseFromApp = function (app, url) { - var dbUrl = url || app.options[DATABASE_URL_OPTION]; - if (dbUrl === undefined) { - fatal("Can't determine Firebase Database URL. Be sure to include " + - DATABASE_URL_OPTION + - ' option when calling firebase.initializeApp().'); - } - var parsedUrl = parseRepoInfo(dbUrl); - var repoInfo = parsedUrl.repoInfo; - validateUrl('Invalid Firebase Database URL', 1, parsedUrl); - if (!parsedUrl.path.isEmpty()) { - fatal('Database URL must point to the root of a Firebase Database ' + - '(not including a child path).'); - } - var repo = this.createRepo(repoInfo, app); - return repo.database; - }; - /** - * Remove the repo and make sure it is disconnected. - * - * @param {!Repo} repo - */ - RepoManager.prototype.deleteRepo = function (repo) { - var appRepos = util.safeGet(this.repos_, repo.app.name); - // This should never happen... - if (!appRepos || util.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) { - fatal("Database " + repo.app.name + "(" + repo.repoInfo_ + ") has already been deleted."); - } - repo.interrupt(); - delete appRepos[repo.repoInfo_.toURLString()]; - }; - /** - * Ensures a repo doesn't already exist and then creates one using the - * provided app. - * - * @param {!RepoInfo} repoInfo The metadata about the Repo - * @param {!FirebaseApp} app - * @return {!Repo} The Repo object for the specified server / repoName. - */ - RepoManager.prototype.createRepo = function (repoInfo, app) { - var appRepos = util.safeGet(this.repos_, app.name); - if (!appRepos) { - appRepos = {}; - this.repos_[app.name] = appRepos; - } - var repo = util.safeGet(appRepos, repoInfo.toURLString()); - if (repo) { - fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); - } - repo = new Repo(repoInfo, this.useRestClient_, app); - appRepos[repoInfo.toURLString()] = repo; - return repo; - }; - /** - * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. - * @param {boolean} forceRestClient - */ - RepoManager.prototype.forceRestClient = function (forceRestClient) { - this.useRestClient_ = forceRestClient; - }; - return RepoManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class representing a firebase database. - * @implements {FirebaseService} - */ -var Database = /** @class */ (function () { - /** - * The constructor should not be called by users of our public API. - * @param {!Repo} repo_ - */ - function Database(repo_) { - this.repo_ = repo_; - if (!(repo_ instanceof Repo)) { - fatal("Don't call new Database() directly - please use firebase.database()."); - } - /** @type {Reference} */ - this.root_ = new Reference(repo_, Path.Empty); - this.INTERNAL = new DatabaseInternals(this); - } - Object.defineProperty(Database.prototype, "app", { - get: function () { - return this.repo_.app; - }, - enumerable: true, - configurable: true - }); - Database.prototype.ref = function (path) { - this.checkDeleted_('ref'); - util.validateArgCount('database.ref', 0, 1, arguments.length); - if (path instanceof Reference) { - return this.refFromURL(path.toString()); - } - return path !== undefined ? this.root_.child(path) : this.root_; - }; - /** - * Returns a reference to the root or the path specified in url. - * We throw a exception if the url is not in the same domain as the - * current repo. - * @param {string} url - * @return {!Reference} Firebase reference. - */ - Database.prototype.refFromURL = function (url) { - /** @const {string} */ - var apiName = 'database.refFromURL'; - this.checkDeleted_(apiName); - util.validateArgCount(apiName, 1, 1, arguments.length); - var parsedURL = parseRepoInfo(url); - validateUrl(apiName, 1, parsedURL); - var repoInfo = parsedURL.repoInfo; - if (repoInfo.host !== this.repo_.repoInfo_.host) { - fatal(apiName + - ': Host name does not match the current database: ' + - '(found ' + - repoInfo.host + - ' but expected ' + - this.repo_.repoInfo_.host + - ')'); - } - return this.ref(parsedURL.path.toString()); - }; - /** - * @param {string} apiName - */ - Database.prototype.checkDeleted_ = function (apiName) { - if (this.repo_ === null) { - fatal('Cannot call ' + apiName + ' on a deleted database.'); - } - }; - // Make individual repo go offline. - Database.prototype.goOffline = function () { - util.validateArgCount('database.goOffline', 0, 0, arguments.length); - this.checkDeleted_('goOffline'); - this.repo_.interrupt(); - }; - Database.prototype.goOnline = function () { - util.validateArgCount('database.goOnline', 0, 0, arguments.length); - this.checkDeleted_('goOnline'); - this.repo_.resume(); - }; - Database.ServerValue = { - TIMESTAMP: { - '.sv': 'timestamp' - } - }; - return Database; -}()); -var DatabaseInternals = /** @class */ (function () { - /** @param {!Database} database */ - function DatabaseInternals(database) { - this.database = database; - } - /** @return {Promise} */ - DatabaseInternals.prototype.delete = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - return tslib_1.__generator(this, function (_a) { - this.database.checkDeleted_('delete'); - RepoManager.getInstance().deleteRepo(this.database.repo_); - this.database.repo_ = null; - this.database.root_ = null; - this.database.INTERNAL = null; - this.database = null; - return [2 /*return*/]; - }); - }); - }; - return DatabaseInternals; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * INTERNAL methods for internal-use only (tests, etc.). - * - * Customers shouldn't use these or else should be aware that they could break at any time. - * - * @const - */ -var forceLongPolling = function () { - WebSocketConnection.forceDisallow(); - BrowserPollConnection.forceAllow(); -}; -var forceWebSockets = function () { - BrowserPollConnection.forceDisallow(); -}; -/* Used by App Manager */ -var isWebSocketsAvailable = function () { - return WebSocketConnection['isAvailable'](); -}; -var setSecurityDebugCallback = function (ref, callback) { - ref.repo.persistentConnection_.securityDebugCallback_ = callback; -}; -var stats = function (ref, showDelta) { - ref.repo.stats(showDelta); -}; -var statsIncrementCounter = function (ref, metric) { - ref.repo.statsIncrementCounter(metric); -}; -var dataUpdateCount = function (ref) { - return ref.repo.dataUpdateCount; -}; -var interceptServerData = function (ref, callback) { - return ref.repo.interceptServerData_(callback); -}; - -var INTERNAL = /*#__PURE__*/Object.freeze({ - forceLongPolling: forceLongPolling, - forceWebSockets: forceWebSockets, - isWebSocketsAvailable: isWebSocketsAvailable, - setSecurityDebugCallback: setSecurityDebugCallback, - stats: stats, - statsIncrementCounter: statsIncrementCounter, - dataUpdateCount: dataUpdateCount, - interceptServerData: interceptServerData -}); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DataConnection = PersistentConnection; -/** - * @param {!string} pathString - * @param {function(*)} onComplete - */ -PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { - this.sendRequest('q', { p: pathString }, onComplete); -}; -/** - * @param {*} data - * @param {function(*)} onEcho - */ -PersistentConnection.prototype.echo = function (data, onEcho) { - this.sendRequest('echo', { d: data }, onEcho); -}; -// RealTimeConnection properties that we use in tests. -var RealTimeConnection = Connection; -/** - * @param {function(): string} newHash - * @return {function()} - */ -var hijackHash = function (newHash) { - var oldPut = PersistentConnection.prototype.put; - PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) { - if (opt_hash !== undefined) { - opt_hash = newHash(); - } - oldPut.call(this, pathString, data, opt_onComplete, opt_hash); - }; - return function () { - PersistentConnection.prototype.put = oldPut; - }; -}; -/** - * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined} - */ -var ConnectionTarget = RepoInfo; -/** - * @param {!Query} query - * @return {!string} - */ -var queryIdentifier = function (query) { - return query.queryIdentifier(); -}; -/** - * @param {!Query} firebaseRef - * @return {!Object} - */ -var listens = function (firebaseRef) { - return firebaseRef.repo.persistentConnection_.listens_; -}; -/** - * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. - * - * @param {boolean} forceRestClient - */ -var forceRestClient = function (forceRestClient) { - RepoManager.getInstance().forceRestClient(forceRestClient); -}; - -var TEST_ACCESS = /*#__PURE__*/Object.freeze({ - DataConnection: DataConnection, - RealTimeConnection: RealTimeConnection, - hijackHash: hijackHash, - ConnectionTarget: ConnectionTarget, - queryIdentifier: queryIdentifier, - listens: listens, - forceRestClient: forceRestClient -}); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ServerValue = Database.ServerValue; -function registerDatabase(instance) { - // Register the Database Service with the 'firebase' namespace. - var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager.getInstance().databaseFromApp(app, url); }, - // firebase.database namespace properties - { - Reference: Reference, - Query: Query, - Database: Database, - enableLogging: enableLogging, - INTERNAL: INTERNAL, - ServerValue: ServerValue, - TEST_ACCESS: TEST_ACCESS - }, null, true); - if (util.isNodeSdk()) { - module.exports = namespace; - } -} -registerDatabase(firebase); - -exports.registerDatabase = registerDatabase; -exports.Database = Database; -exports.Query = Query; -exports.Reference = Reference; -exports.enableLogging = enableLogging; -exports.ServerValue = ServerValue; -exports.DataSnapshot = DataSnapshot; -exports.OnDisconnect = OnDisconnect; diff --git a/functions/node_modules/@firebase/database/dist/index.d.ts b/functions/node_modules/@firebase/database/dist/index.d.ts deleted file mode 100644 index abc5dc3d..00000000 --- a/functions/node_modules/@firebase/database/dist/index.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { FirebaseNamespace } from '@firebase/app-types'; -import { Database } from './src/api/Database'; -import { Query } from './src/api/Query'; -import { Reference } from './src/api/Reference'; -import { enableLogging } from './src/core/util/util'; -import * as types from '@firebase/database-types'; -declare const ServerValue: { - TIMESTAMP: { - '.sv': string; - }; -}; -export declare function registerDatabase(instance: FirebaseNamespace): void; -export { Database, Query, Reference, enableLogging, ServerValue }; -export { DataSnapshot } from './src/api/DataSnapshot'; -export { OnDisconnect } from './src/api/onDisconnect'; -declare module '@firebase/app-types' { - interface FirebaseNamespace { - database?: { - (app?: FirebaseApp): types.FirebaseDatabase; - enableLogging: typeof types.enableLogging; - ServerValue: types.ServerValue; - Database: typeof types.FirebaseDatabase; - }; - } - interface FirebaseApp { - database?(databaseURL?: string): types.FirebaseDatabase; - } -} diff --git a/functions/node_modules/@firebase/database/dist/index.esm.js b/functions/node_modules/@firebase/database/dist/index.esm.js deleted file mode 100644 index c04a8d35..00000000 --- a/functions/node_modules/@firebase/database/dist/index.esm.js +++ /dev/null @@ -1,15341 +0,0 @@ -import { jsonEval, stringify, contains, assert, forEach, base64, Sha1, stringToByteArray, isNodeSdk, stringLength, safeGet, errorPrefix, validateArgCount, validateCallback, Deferred, assertionError, clone, map, getCount, getAnyKey, every, validateContextObject, isEmpty, getValues, findValue, findKey, deepCopy, isMobileCordova, base64Encode, CONSTANTS, isAdmin, isValidFormat, isReactNative, querystring } from '@firebase/util'; -import { Logger, LogLevel } from '@firebase/logger'; -import { __awaiter, __generator, __extends } from 'tslib'; -import firebase from '@firebase/app'; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Wraps a DOM Storage object and: - * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. - * - prefixes names with "firebase:" to avoid collisions with app data. - * - * We automatically (see storage.js) create two such wrappers, one for sessionStorage, - * and one for localStorage. - * - * @constructor - */ -var DOMStorageWrapper = /** @class */ (function () { - /** - * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage) - */ - function DOMStorageWrapper(domStorage_) { - this.domStorage_ = domStorage_; - // Use a prefix to avoid collisions with other stuff saved by the app. - this.prefix_ = 'firebase:'; - } - /** - * @param {string} key The key to save the value under - * @param {?Object} value The value being stored, or null to remove the key. - */ - DOMStorageWrapper.prototype.set = function (key, value) { - if (value == null) { - this.domStorage_.removeItem(this.prefixedName_(key)); - } - else { - this.domStorage_.setItem(this.prefixedName_(key), stringify(value)); - } - }; - /** - * @param {string} key - * @return {*} The value that was stored under this key, or null - */ - DOMStorageWrapper.prototype.get = function (key) { - var storedVal = this.domStorage_.getItem(this.prefixedName_(key)); - if (storedVal == null) { - return null; - } - else { - return jsonEval(storedVal); - } - }; - /** - * @param {string} key - */ - DOMStorageWrapper.prototype.remove = function (key) { - this.domStorage_.removeItem(this.prefixedName_(key)); - }; - /** - * @param {string} name - * @return {string} - */ - DOMStorageWrapper.prototype.prefixedName_ = function (name) { - return this.prefix_ + name; - }; - DOMStorageWrapper.prototype.toString = function () { - return this.domStorage_.toString(); - }; - return DOMStorageWrapper; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An in-memory storage implementation that matches the API of DOMStorageWrapper - * (TODO: create interface for both to implement). - * - * @constructor - */ -var MemoryStorage = /** @class */ (function () { - function MemoryStorage() { - this.cache_ = {}; - this.isInMemoryStorage = true; - } - MemoryStorage.prototype.set = function (key, value) { - if (value == null) { - delete this.cache_[key]; - } - else { - this.cache_[key] = value; - } - }; - MemoryStorage.prototype.get = function (key) { - if (contains(this.cache_, key)) { - return this.cache_[key]; - } - return null; - }; - MemoryStorage.prototype.remove = function (key) { - delete this.cache_[key]; - }; - return MemoryStorage; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. - * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change - * to reflect this type - * - * @param {string} domStorageName Name of the underlying storage object - * (e.g. 'localStorage' or 'sessionStorage'). - * @return {?} Turning off type information until a common interface is defined. - */ -var createStoragefor = function (domStorageName) { - try { - // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, - // so it must be inside the try/catch. - if (typeof window !== 'undefined' && - typeof window[domStorageName] !== 'undefined') { - // Need to test cache. Just because it's here doesn't mean it works - var domStorage = window[domStorageName]; - domStorage.setItem('firebase:sentinel', 'cache'); - domStorage.removeItem('firebase:sentinel'); - return new DOMStorageWrapper(domStorage); - } - } - catch (e) { } - // Failed to create wrapper. Just return in-memory storage. - // TODO: log? - return new MemoryStorage(); -}; -/** A storage object that lasts across sessions */ -var PersistentStorage = createStoragefor('localStorage'); -/** A storage object that only lasts one session */ -var SessionStorage = createStoragefor('sessionStorage'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var logClient = new Logger('@firebase/database'); -/** - * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). - * @type {function(): number} Generated ID. - */ -var LUIDGenerator = (function () { - var id = 1; - return function () { - return id++; - }; -})(); -/** - * Sha1 hash of the input string - * @param {!string} str The string to hash - * @return {!string} The resulting hash - */ -var sha1 = function (str) { - var utf8Bytes = stringToByteArray(str); - var sha1 = new Sha1(); - sha1.update(utf8Bytes); - var sha1Bytes = sha1.digest(); - return base64.encodeByteArray(sha1Bytes); -}; -/** - * @param {...*} var_args - * @return {string} - * @private - */ -var buildLogMessage_ = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = ''; - for (var i = 0; i < var_args.length; i++) { - if (Array.isArray(var_args[i]) || - (var_args[i] && - typeof var_args[i] === 'object' && - typeof var_args[i].length === 'number')) { - message += buildLogMessage_.apply(null, var_args[i]); - } - else if (typeof var_args[i] === 'object') { - message += stringify(var_args[i]); - } - else { - message += var_args[i]; - } - message += ' '; - } - return message; -}; -/** - * Use this for all debug messages in Firebase. - * @type {?function(string)} - */ -var logger = null; -/** - * Flag to check for log availability on first log message - * @type {boolean} - * @private - */ -var firstLog_ = true; -/** - * The implementation of Firebase.enableLogging (defined here to break dependencies) - * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger - * @param {boolean=} persistent Whether or not to persist logging settings across refreshes - */ -var enableLogging = function (logger_, persistent) { - assert(!persistent || (logger_ === true || logger_ === false), "Can't turn on custom loggers persistently."); - if (logger_ === true) { - logClient.logLevel = LogLevel.VERBOSE; - logger = logClient.log.bind(logClient); - if (persistent) - SessionStorage.set('logging_enabled', true); - } - else if (typeof logger_ === 'function') { - logger = logger_; - } - else { - logger = null; - SessionStorage.remove('logging_enabled'); - } -}; -/** - * - * @param {...(string|Arguments)} var_args - */ -var log = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - if (firstLog_ === true) { - firstLog_ = false; - if (logger === null && SessionStorage.get('logging_enabled') === true) - enableLogging(true); - } - if (logger) { - var message = buildLogMessage_.apply(null, var_args); - logger(message); - } -}; -/** - * @param {!string} prefix - * @return {function(...[*])} - */ -var logWrapper = function (prefix) { - return function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - log.apply(void 0, [prefix].concat(var_args)); - }; -}; -/** - * @param {...string} var_args - */ -var error = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args); - logClient.error(message); -}; -/** - * @param {...string} var_args - */ -var fatal = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = "FIREBASE FATAL ERROR: " + buildLogMessage_.apply(void 0, var_args); - logClient.error(message); - throw new Error(message); -}; -/** - * @param {...*} var_args - */ -var warn = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args); - logClient.warn(message); -}; -/** - * Logs a warning if the containing page uses https. Called when a call to new Firebase - * does not use https. - */ -var warnIfPageIsSecure = function () { - // Be very careful accessing browser globals. Who knows what may or may not exist. - if (typeof window !== 'undefined' && - window.location && - window.location.protocol && - window.location.protocol.indexOf('https:') !== -1) { - warn('Insecure Firebase access from a secure page. ' + - 'Please use https in calls to new Firebase().'); - } -}; -/** - * Returns true if data is NaN, or +/- Infinity. - * @param {*} data - * @return {boolean} - */ -var isInvalidJSONNumber = function (data) { - return (typeof data === 'number' && - (data != data || // NaN - data == Number.POSITIVE_INFINITY || - data == Number.NEGATIVE_INFINITY)); -}; -/** - * @param {function()} fn - */ -var executeWhenDOMReady = function (fn) { - if (isNodeSdk() || document.readyState === 'complete') { - fn(); - } - else { - // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which - // fire before onload), but fall back to onload. - var called_1 = false; - var wrappedFn_1 = function () { - if (!document.body) { - setTimeout(wrappedFn_1, Math.floor(10)); - return; - } - if (!called_1) { - called_1 = true; - fn(); - } - }; - if (document.addEventListener) { - document.addEventListener('DOMContentLoaded', wrappedFn_1, false); - // fallback to onload. - window.addEventListener('load', wrappedFn_1, false); - } - else if (document.attachEvent) { - // IE. - document.attachEvent('onreadystatechange', function () { - if (document.readyState === 'complete') - wrappedFn_1(); - }); - // fallback to onload. - window.attachEvent('onload', wrappedFn_1); - // jQuery has an extra hack for IE that we could employ (based on - // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. - // I'm hoping we don't need it. - } - } -}; -/** - * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names - * @type {!string} - */ -var MIN_NAME = '[MIN_NAME]'; -/** - * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names - * @type {!string} - */ -var MAX_NAME = '[MAX_NAME]'; -/** - * Compares valid Firebase key names, plus min and max name - * @param {!string} a - * @param {!string} b - * @return {!number} - */ -var nameCompare = function (a, b) { - if (a === b) { - return 0; - } - else if (a === MIN_NAME || b === MAX_NAME) { - return -1; - } - else if (b === MIN_NAME || a === MAX_NAME) { - return 1; - } - else { - var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); - if (aAsInt !== null) { - if (bAsInt !== null) { - return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt; - } - else { - return -1; - } - } - else if (bAsInt !== null) { - return 1; - } - else { - return a < b ? -1 : 1; - } - } -}; -/** - * @param {!string} a - * @param {!string} b - * @return {!number} comparison result. - */ -var stringCompare = function (a, b) { - if (a === b) { - return 0; - } - else if (a < b) { - return -1; - } - else { - return 1; - } -}; -/** - * @param {string} key - * @param {Object} obj - * @return {*} - */ -var requireKey = function (key, obj) { - if (obj && key in obj) { - return obj[key]; - } - else { - throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj)); - } -}; -/** - * @param {*} obj - * @return {string} - */ -var ObjectToUniqueKey = function (obj) { - if (typeof obj !== 'object' || obj === null) - return stringify(obj); - var keys = []; - for (var k in obj) { - keys.push(k); - } - // Export as json, but with the keys sorted. - keys.sort(); - var key = '{'; - for (var i = 0; i < keys.length; i++) { - if (i !== 0) - key += ','; - key += stringify(keys[i]); - key += ':'; - key += ObjectToUniqueKey(obj[keys[i]]); - } - key += '}'; - return key; -}; -/** - * Splits a string into a number of smaller segments of maximum size - * @param {!string} str The string - * @param {!number} segsize The maximum number of chars in the string. - * @return {Array.} The string, split into appropriately-sized chunks - */ -var splitStringBySize = function (str, segsize) { - var len = str.length; - if (len <= segsize) { - return [str]; - } - var dataSegs = []; - for (var c = 0; c < len; c += segsize) { - if (c + segsize > len) { - dataSegs.push(str.substring(c, len)); - } - else { - dataSegs.push(str.substring(c, c + segsize)); - } - } - return dataSegs; -}; -/** - * Apply a function to each (key, value) pair in an object or - * apply a function to each (index, value) pair in an array - * @param {!(Object|Array)} obj The object or array to iterate over - * @param {function(?, ?)} fn The function to apply - */ -var each = function (obj, fn) { - if (Array.isArray(obj)) { - for (var i = 0; i < obj.length; ++i) { - fn(i, obj[i]); - } - } - else { - /** - * in the conversion of code we removed the goog.object.forEach - * function which did a value,key callback. We standardized on - * a single impl that does a key, value callback. So we invert - * to not have to touch the `each` code points - */ - forEach(obj, function (key, val) { return fn(val, key); }); - } -}; -/** - * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) - * I made one modification at the end and removed the NaN / Infinity - * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. - * @param {!number} v A double - * @return {string} - */ -var doubleToIEEE754String = function (v) { - assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL - var ebits = 11, fbits = 52; - var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str; - // Compute sign, exponent, fraction - // Skip NaN / Infinity handling --MJL. - if (v === 0) { - e = 0; - f = 0; - s = 1 / v === -Infinity ? 1 : 0; - } - else { - s = v < 0; - v = Math.abs(v); - if (v >= Math.pow(2, 1 - bias)) { - // Normalized - ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); - e = ln + bias; - f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); - } - else { - // Denormalized - e = 0; - f = Math.round(v / Math.pow(2, 1 - bias - fbits)); - } - } - // Pack sign, exponent, fraction - bits = []; - for (i = fbits; i; i -= 1) { - bits.push(f % 2 ? 1 : 0); - f = Math.floor(f / 2); - } - for (i = ebits; i; i -= 1) { - bits.push(e % 2 ? 1 : 0); - e = Math.floor(e / 2); - } - bits.push(s ? 1 : 0); - bits.reverse(); - str = bits.join(''); - // Return the data as a hex string. --MJL - var hexByteString = ''; - for (i = 0; i < 64; i += 8) { - var hexByte = parseInt(str.substr(i, 8), 2).toString(16); - if (hexByte.length === 1) - hexByte = '0' + hexByte; - hexByteString = hexByteString + hexByte; - } - return hexByteString.toLowerCase(); -}; -/** - * Used to detect if we're in a Chrome content script (which executes in an - * isolated environment where long-polling doesn't work). - * @return {boolean} - */ -var isChromeExtensionContentScript = function () { - return !!(typeof window === 'object' && - window['chrome'] && - window['chrome']['extension'] && - !/^chrome/.test(window.location.href)); -}; -/** - * Used to detect if we're in a Windows 8 Store app. - * @return {boolean} - */ -var isWindowsStoreApp = function () { - // Check for the presence of a couple WinRT globals - return typeof Windows === 'object' && typeof Windows.UI === 'object'; -}; -/** - * Converts a server error code to a Javascript Error - * @param {!string} code - * @param {!Query} query - * @return {Error} - */ -var errorForServerCode = function (code, query) { - var reason = 'Unknown Error'; - if (code === 'too_big') { - reason = - 'The data requested exceeds the maximum size ' + - 'that can be accessed with a single request.'; - } - else if (code == 'permission_denied') { - reason = "Client doesn't have permission to access the desired data."; - } - else if (code == 'unavailable') { - reason = 'The service is unavailable'; - } - var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason); - error.code = code.toUpperCase(); - return error; -}; -/** - * Used to test for integer-looking strings - * @type {RegExp} - * @private - */ -var INTEGER_REGEXP_ = new RegExp('^-?\\d{1,10}$'); -/** - * If the string contains a 32-bit integer, return it. Else return null. - * @param {!string} str - * @return {?number} - */ -var tryParseInt = function (str) { - if (INTEGER_REGEXP_.test(str)) { - var intVal = Number(str); - if (intVal >= -2147483648 && intVal <= 2147483647) { - return intVal; - } - } - return null; -}; -/** - * Helper to run some code but catch any exceptions and re-throw them later. - * Useful for preventing user callbacks from breaking internal code. - * - * Re-throwing the exception from a setTimeout is a little evil, but it's very - * convenient (we don't have to try to figure out when is a safe point to - * re-throw it), and the behavior seems reasonable: - * - * * If you aren't pausing on exceptions, you get an error in the console with - * the correct stack trace. - * * If you're pausing on all exceptions, the debugger will pause on your - * exception and then again when we rethrow it. - * * If you're only pausing on uncaught exceptions, the debugger will only pause - * on us re-throwing it. - * - * @param {!function()} fn The code to guard. - */ -var exceptionGuard = function (fn) { - try { - fn(); - } - catch (e) { - // Re-throw exception when it's safe. - setTimeout(function () { - // It used to be that "throw e" would result in a good console error with - // relevant context, but as of Chrome 39, you just get the firebase.js - // file/line number where we re-throw it, which is useless. So we log - // e.stack explicitly. - var stack = e.stack || ''; - warn('Exception was thrown by user callback.', stack); - throw e; - }, Math.floor(0)); - } -}; -/** - * @return {boolean} true if we think we're currently being crawled. - */ -var beingCrawled = function () { - var userAgent = (typeof window === 'object' && - window['navigator'] && - window['navigator']['userAgent']) || - ''; - // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we - // believe to support JavaScript/AJAX rendering. - // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website - // would have seen the page" is flaky if we don't treat it as a crawler. - return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); -}; -/** - * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. - * - * It is removed with clearTimeout() as normal. - * - * @param {Function} fn Function to run. - * @param {number} time Milliseconds to wait before running. - * @return {number|Object} The setTimeout() return value. - */ -var setTimeoutNonBlocking = function (fn, time) { - var timeout = setTimeout(fn, time); - if (typeof timeout === 'object' && timeout['unref']) { - timeout['unref'](); - } - return timeout; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An immutable object representing a parsed path. It's immutable so that you - * can pass them around to other functions without worrying about them changing - * it. - */ -var Path = /** @class */ (function () { - /** - * @param {string|Array.} pathOrString Path string to parse, - * or another path, or the raw tokens array - * @param {number=} pieceNum - */ - function Path(pathOrString, pieceNum) { - if (pieceNum === void 0) { - this.pieces_ = pathOrString.split('/'); - // Remove empty pieces. - var copyTo = 0; - for (var i = 0; i < this.pieces_.length; i++) { - if (this.pieces_[i].length > 0) { - this.pieces_[copyTo] = this.pieces_[i]; - copyTo++; - } - } - this.pieces_.length = copyTo; - this.pieceNum_ = 0; - } - else { - this.pieces_ = pathOrString; - this.pieceNum_ = pieceNum; - } - } - Object.defineProperty(Path, "Empty", { - /** - * Singleton to represent an empty path - * - * @const - */ - get: function () { - return new Path(''); - }, - enumerable: true, - configurable: true - }); - Path.prototype.getFront = function () { - if (this.pieceNum_ >= this.pieces_.length) - return null; - return this.pieces_[this.pieceNum_]; - }; - /** - * @return {number} The number of segments in this path - */ - Path.prototype.getLength = function () { - return this.pieces_.length - this.pieceNum_; - }; - /** - * @return {!Path} - */ - Path.prototype.popFront = function () { - var pieceNum = this.pieceNum_; - if (pieceNum < this.pieces_.length) { - pieceNum++; - } - return new Path(this.pieces_, pieceNum); - }; - /** - * @return {?string} - */ - Path.prototype.getBack = function () { - if (this.pieceNum_ < this.pieces_.length) - return this.pieces_[this.pieces_.length - 1]; - return null; - }; - Path.prototype.toString = function () { - var pathString = ''; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) { - if (this.pieces_[i] !== '') - pathString += '/' + this.pieces_[i]; - } - return pathString || '/'; - }; - Path.prototype.toUrlEncodedString = function () { - var pathString = ''; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) { - if (this.pieces_[i] !== '') - pathString += '/' + encodeURIComponent(String(this.pieces_[i])); - } - return pathString || '/'; - }; - /** - * Shallow copy of the parts of the path. - * - * @param {number=} begin - * @return {!Array} - */ - Path.prototype.slice = function (begin) { - if (begin === void 0) { begin = 0; } - return this.pieces_.slice(this.pieceNum_ + begin); - }; - /** - * @return {?Path} - */ - Path.prototype.parent = function () { - if (this.pieceNum_ >= this.pieces_.length) - return null; - var pieces = []; - for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++) - pieces.push(this.pieces_[i]); - return new Path(pieces, 0); - }; - /** - * @param {string|!Path} childPathObj - * @return {!Path} - */ - Path.prototype.child = function (childPathObj) { - var pieces = []; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) - pieces.push(this.pieces_[i]); - if (childPathObj instanceof Path) { - for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { - pieces.push(childPathObj.pieces_[i]); - } - } - else { - var childPieces = childPathObj.split('/'); - for (var i = 0; i < childPieces.length; i++) { - if (childPieces[i].length > 0) - pieces.push(childPieces[i]); - } - } - return new Path(pieces, 0); - }; - /** - * @return {boolean} True if there are no segments in this path - */ - Path.prototype.isEmpty = function () { - return this.pieceNum_ >= this.pieces_.length; - }; - /** - * @param {!Path} outerPath - * @param {!Path} innerPath - * @return {!Path} The path from outerPath to innerPath - */ - Path.relativePath = function (outerPath, innerPath) { - var outer = outerPath.getFront(), inner = innerPath.getFront(); - if (outer === null) { - return innerPath; - } - else if (outer === inner) { - return Path.relativePath(outerPath.popFront(), innerPath.popFront()); - } - else { - throw new Error('INTERNAL ERROR: innerPath (' + - innerPath + - ') is not within ' + - 'outerPath (' + - outerPath + - ')'); - } - }; - /** - * @param {!Path} left - * @param {!Path} right - * @return {number} -1, 0, 1 if left is less, equal, or greater than the right. - */ - Path.comparePaths = function (left, right) { - var leftKeys = left.slice(); - var rightKeys = right.slice(); - for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) { - var cmp = nameCompare(leftKeys[i], rightKeys[i]); - if (cmp !== 0) - return cmp; - } - if (leftKeys.length === rightKeys.length) - return 0; - return leftKeys.length < rightKeys.length ? -1 : 1; - }; - /** - * - * @param {Path} other - * @return {boolean} true if paths are the same. - */ - Path.prototype.equals = function (other) { - if (this.getLength() !== other.getLength()) { - return false; - } - for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) { - if (this.pieces_[i] !== other.pieces_[j]) { - return false; - } - } - return true; - }; - /** - * - * @param {!Path} other - * @return {boolean} True if this path is a parent (or the same as) other - */ - Path.prototype.contains = function (other) { - var i = this.pieceNum_; - var j = other.pieceNum_; - if (this.getLength() > other.getLength()) { - return false; - } - while (i < this.pieces_.length) { - if (this.pieces_[i] !== other.pieces_[j]) { - return false; - } - ++i; - ++j; - } - return true; - }; - return Path; -}()); // end Path -/** - * Dynamic (mutable) path used to count path lengths. - * - * This class is used to efficiently check paths for valid - * length (in UTF8 bytes) and depth (used in path validation). - * - * Throws Error exception if path is ever invalid. - * - * The definition of a path always begins with '/'. - */ -var ValidationPath = /** @class */ (function () { - /** - * @param {!Path} path Initial Path. - * @param {string} errorPrefix_ Prefix for any error messages. - */ - function ValidationPath(path, errorPrefix_) { - this.errorPrefix_ = errorPrefix_; - /** @type {!Array} */ - this.parts_ = path.slice(); - /** @type {number} Initialize to number of '/' chars needed in path. */ - this.byteLength_ = Math.max(1, this.parts_.length); - for (var i = 0; i < this.parts_.length; i++) { - this.byteLength_ += stringLength(this.parts_[i]); - } - this.checkValid_(); - } - Object.defineProperty(ValidationPath, "MAX_PATH_DEPTH", { - /** @const {number} Maximum key depth. */ - get: function () { - return 32; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ValidationPath, "MAX_PATH_LENGTH_BYTES", { - /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */ - get: function () { - return 768; - }, - enumerable: true, - configurable: true - }); - /** @param {string} child */ - ValidationPath.prototype.push = function (child) { - // Count the needed '/' - if (this.parts_.length > 0) { - this.byteLength_ += 1; - } - this.parts_.push(child); - this.byteLength_ += stringLength(child); - this.checkValid_(); - }; - ValidationPath.prototype.pop = function () { - var last = this.parts_.pop(); - this.byteLength_ -= stringLength(last); - // Un-count the previous '/' - if (this.parts_.length > 0) { - this.byteLength_ -= 1; - } - }; - ValidationPath.prototype.checkValid_ = function () { - if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) { - throw new Error(this.errorPrefix_ + - 'has a key path longer than ' + - ValidationPath.MAX_PATH_LENGTH_BYTES + - ' bytes (' + - this.byteLength_ + - ').'); - } - if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) { - throw new Error(this.errorPrefix_ + - 'path specified exceeds the maximum depth that can be written (' + - ValidationPath.MAX_PATH_DEPTH + - ') or object contains a cycle ' + - this.toErrorString()); - } - }; - /** - * String for use in error messages - uses '.' notation for path. - * - * @return {string} - */ - ValidationPath.prototype.toErrorString = function () { - if (this.parts_.length == 0) { - return ''; - } - return "in property '" + this.parts_.join('.') + "'"; - }; - return ValidationPath; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var PROTOCOL_VERSION = '5'; -var VERSION_PARAM = 'v'; -var TRANSPORT_SESSION_PARAM = 's'; -var REFERER_PARAM = 'r'; -var FORGE_REF = 'f'; -var FORGE_DOMAIN = 'firebaseio.com'; -var LAST_SESSION_PARAM = 'ls'; -var WEBSOCKET = 'websocket'; -var LONG_POLLING = 'long_polling'; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A class that holds metadata about a Repo object - * - * @constructor - */ -var RepoInfo = /** @class */ (function () { - /** - * @param {string} host Hostname portion of the url for the repo - * @param {boolean} secure Whether or not this repo is accessed over ssl - * @param {string} namespace The namespace represented by the repo - * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest). - * @param {string=} persistenceKey Override the default session persistence storage key - */ - function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) { - if (persistenceKey === void 0) { persistenceKey = ''; } - this.secure = secure; - this.namespace = namespace; - this.webSocketOnly = webSocketOnly; - this.persistenceKey = persistenceKey; - this.host = host.toLowerCase(); - this.domain = this.host.substr(this.host.indexOf('.') + 1); - this.internalHost = PersistentStorage.get('host:' + host) || this.host; - } - RepoInfo.prototype.needsQueryParam = function () { - return this.host !== this.internalHost || this.isCustomHost(); - }; - RepoInfo.prototype.isCacheableHost = function () { - return this.internalHost.substr(0, 2) === 's-'; - }; - RepoInfo.prototype.isDemoHost = function () { - return this.domain === 'firebaseio-demo.com'; - }; - RepoInfo.prototype.isCustomHost = function () { - return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com'); - }; - RepoInfo.prototype.updateHost = function (newHost) { - if (newHost !== this.internalHost) { - this.internalHost = newHost; - if (this.isCacheableHost()) { - PersistentStorage.set('host:' + this.host, this.internalHost); - } - } - }; - /** - * Returns the websocket URL for this repo - * @param {string} type of connection - * @param {Object} params list - * @return {string} The URL for this repo - */ - RepoInfo.prototype.connectionURL = function (type, params) { - assert(typeof type === 'string', 'typeof type must == string'); - assert(typeof params === 'object', 'typeof params must == object'); - var connURL; - if (type === WEBSOCKET) { - connURL = - (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?'; - } - else if (type === LONG_POLLING) { - connURL = - (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?'; - } - else { - throw new Error('Unknown connection type: ' + type); - } - if (this.needsQueryParam()) { - params['ns'] = this.namespace; - } - var pairs = []; - forEach(params, function (key, value) { - pairs.push(key + '=' + value); - }); - return connURL + pairs.join('&'); - }; - /** @return {string} */ - RepoInfo.prototype.toString = function () { - var str = this.toURLString(); - if (this.persistenceKey) { - str += '<' + this.persistenceKey + '>'; - } - return str; - }; - /** @return {string} */ - RepoInfo.prototype.toURLString = function () { - return (this.secure ? 'https://' : 'http://') + this.host; - }; - return RepoInfo; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!string} pathString - * @return {string} - */ -function decodePath(pathString) { - var pathStringDecoded = ''; - var pieces = pathString.split('/'); - for (var i = 0; i < pieces.length; i++) { - if (pieces[i].length > 0) { - var piece = pieces[i]; - try { - piece = decodeURIComponent(piece.replace(/\+/g, ' ')); - } - catch (e) { } - pathStringDecoded += '/' + piece; - } - } - return pathStringDecoded; -} -/** - * @param {!string} queryString - * @return {!{[key:string]:string}} key value hash - */ -function decodeQuery(queryString) { - var results = {}; - if (queryString.charAt(0) === '?') { - queryString = queryString.substring(1); - } - for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) { - var segment = _a[_i]; - if (segment.length === 0) { - continue; - } - var kv = segment.split('='); - if (kv.length === 2) { - results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); - } - else { - warn("Invalid query segment '" + segment + "' in query '" + queryString + "'"); - } - } - return results; -} -/** - * - * @param {!string} dataURL - * @return {{repoInfo: !RepoInfo, path: !Path}} - */ -var parseRepoInfo = function (dataURL) { - var parsedUrl = parseURL(dataURL), namespace = parsedUrl.subdomain; - if (parsedUrl.domain === 'firebase') { - fatal(parsedUrl.host + - ' is no longer supported. ' + - 'Please use .firebaseio.com instead'); - } - // Catch common error of uninitialized namespace value. - if ((!namespace || namespace == 'undefined') && - parsedUrl.domain !== 'localhost') { - fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); - } - if (!parsedUrl.secure) { - warnIfPageIsSecure(); - } - var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; - return { - repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly), - path: new Path(parsedUrl.pathString) - }; -}; -/** - * - * @param {!string} dataURL - * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}} - */ -var parseURL = function (dataURL) { - // Default to empty strings in the event of a malformed string. - var host = '', domain = '', subdomain = '', pathString = ''; - // Always default to SSL, unless otherwise specified. - var secure = true, scheme = 'https', port = 443; - // Don't do any validation here. The caller is responsible for validating the result of parsing. - if (typeof dataURL === 'string') { - // Parse scheme. - var colonInd = dataURL.indexOf('//'); - if (colonInd >= 0) { - scheme = dataURL.substring(0, colonInd - 1); - dataURL = dataURL.substring(colonInd + 2); - } - // Parse host, path, and query string. - var slashInd = dataURL.indexOf('/'); - if (slashInd === -1) { - slashInd = dataURL.length; - } - var questionMarkInd = dataURL.indexOf('?'); - if (questionMarkInd === -1) { - questionMarkInd = dataURL.length; - } - host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); - if (slashInd < questionMarkInd) { - // For pathString, questionMarkInd will always come after slashInd - pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); - } - var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); - // If we have a port, use scheme for determining if it's secure. - colonInd = host.indexOf(':'); - if (colonInd >= 0) { - secure = scheme === 'https' || scheme === 'wss'; - port = parseInt(host.substring(colonInd + 1), 10); - } - else { - colonInd = dataURL.length; - } - var parts = host.split('.'); - if (parts.length === 3) { - // Normalize namespaces to lowercase to share storage / connection. - domain = parts[1]; - subdomain = parts[0].toLowerCase(); - } - else if (parts.length === 2) { - domain = parts[0]; - } - else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') { - domain = 'localhost'; - } - // Support `ns` query param if subdomain not already set - if (subdomain === '' && 'ns' in queryParams) { - subdomain = queryParams['ns']; - } - } - return { - host: host, - port: port, - domain: domain, - subdomain: subdomain, - secure: secure, - scheme: scheme, - pathString: pathString - }; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * True for invalid Firebase keys - * @type {RegExp} - * @private - */ -var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; -/** - * True for invalid Firebase paths. - * Allows '/' in paths. - * @type {RegExp} - * @private - */ -var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; -/** - * Maximum number of characters to allow in leaf value - * @type {number} - * @private - */ -var MAX_LEAF_SIZE_ = 10 * 1024 * 1024; -/** - * @param {*} key - * @return {boolean} - */ -var isValidKey = function (key) { - return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); -}; -/** - * @param {string} pathString - * @return {boolean} - */ -var isValidPathString = function (pathString) { - return (typeof pathString === 'string' && - pathString.length !== 0 && - !INVALID_PATH_REGEX_.test(pathString)); -}; -/** - * @param {string} pathString - * @return {boolean} - */ -var isValidRootPathString = function (pathString) { - if (pathString) { - // Allow '/.info/' at the beginning. - pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); - } - return isValidPathString(pathString); -}; -/** - * @param {*} priority - * @return {boolean} - */ -var isValidPriority = function (priority) { - return (priority === null || - typeof priority === 'string' || - (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || - (priority && typeof priority === 'object' && contains(priority, '.sv'))); -}; -/** - * Pre-validate a datum passed as an argument to Firebase function. - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -var validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) { - if (optional && data === undefined) - return; - validateFirebaseData(errorPrefix(fnName, argumentNumber, optional), data, path); -}; -/** - * Validate a data object client-side before sending to server. - * - * @param {string} errorPrefix - * @param {*} data - * @param {!Path|!ValidationPath} path_ - */ -var validateFirebaseData = function (errorPrefix$$1, data, path_) { - var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix$$1) : path_; - if (data === undefined) { - throw new Error(errorPrefix$$1 + 'contains undefined ' + path.toErrorString()); - } - if (typeof data === 'function') { - throw new Error(errorPrefix$$1 + - 'contains a function ' + - path.toErrorString() + - ' with contents = ' + - data.toString()); - } - if (isInvalidJSONNumber(data)) { - throw new Error(errorPrefix$$1 + 'contains ' + data.toString() + ' ' + path.toErrorString()); - } - // Check max leaf size, but try to avoid the utf8 conversion if we can. - if (typeof data === 'string' && - data.length > MAX_LEAF_SIZE_ / 3 && - stringLength(data) > MAX_LEAF_SIZE_) { - throw new Error(errorPrefix$$1 + - 'contains a string greater than ' + - MAX_LEAF_SIZE_ + - ' utf8 bytes ' + - path.toErrorString() + - " ('" + - data.substring(0, 50) + - "...')"); - } - // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON - // to save extra walking of large objects. - if (data && typeof data === 'object') { - var hasDotValue_1 = false, hasActualChild_1 = false; - forEach(data, function (key, value) { - if (key === '.value') { - hasDotValue_1 = true; - } - else if (key !== '.priority' && key !== '.sv') { - hasActualChild_1 = true; - if (!isValidKey(key)) { - throw new Error(errorPrefix$$1 + - ' contains an invalid key (' + - key + - ') ' + - path.toErrorString() + - '. Keys must be non-empty strings ' + - 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); - } - } - path.push(key); - validateFirebaseData(errorPrefix$$1, value, path); - path.pop(); - }); - if (hasDotValue_1 && hasActualChild_1) { - throw new Error(errorPrefix$$1 + - ' contains ".value" child ' + - path.toErrorString() + - ' in addition to actual children.'); - } - } -}; -/** - * Pre-validate paths passed in the firebase function. - * - * @param {string} errorPrefix - * @param {Array} mergePaths - */ -var validateFirebaseMergePaths = function (errorPrefix$$1, mergePaths) { - var i, curPath; - for (i = 0; i < mergePaths.length; i++) { - curPath = mergePaths[i]; - var keys = curPath.slice(); - for (var j = 0; j < keys.length; j++) { - if (keys[j] === '.priority' && j === keys.length - 1) { - // .priority is OK - } - else if (!isValidKey(keys[j])) { - throw new Error(errorPrefix$$1 + - 'contains an invalid key (' + - keys[j] + - ') in path ' + - curPath.toString() + - '. Keys must be non-empty strings ' + - 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); - } - } - } - // Check that update keys are not descendants of each other. - // We rely on the property that sorting guarantees that ancestors come - // right before descendants. - mergePaths.sort(Path.comparePaths); - var prevPath = null; - for (i = 0; i < mergePaths.length; i++) { - curPath = mergePaths[i]; - if (prevPath !== null && prevPath.contains(curPath)) { - throw new Error(errorPrefix$$1 + - 'contains a path ' + - prevPath.toString() + - ' that is ancestor of another path ' + - curPath.toString()); - } - prevPath = curPath; - } -}; -/** - * pre-validate an object passed as an argument to firebase function ( - * must be an object - e.g. for firebase.update()). - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -var validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) { - if (optional && data === undefined) - return; - var errorPrefix$$1 = errorPrefix(fnName, argumentNumber, optional); - if (!(data && typeof data === 'object') || Array.isArray(data)) { - throw new Error(errorPrefix$$1 + ' must be an object containing the children to replace.'); - } - var mergePaths = []; - forEach(data, function (key, value) { - var curPath = new Path(key); - validateFirebaseData(errorPrefix$$1, value, path.child(curPath)); - if (curPath.getBack() === '.priority') { - if (!isValidPriority(value)) { - throw new Error(errorPrefix$$1 + - "contains an invalid value for '" + - curPath.toString() + - "', which must be a valid " + - 'Firebase priority (a string, finite number, server value, or null).'); - } - } - mergePaths.push(curPath); - }); - validateFirebaseMergePaths(errorPrefix$$1, mergePaths); -}; -var validatePriority = function (fnName, argumentNumber, priority, optional) { - if (optional && priority === undefined) - return; - if (isInvalidJSONNumber(priority)) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'is ' + - priority.toString() + - ', but must be a valid Firebase priority (a string, finite number, ' + - 'server value, or null).'); - // Special case to allow importing data with a .sv. - if (!isValidPriority(priority)) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid Firebase priority ' + - '(a string, finite number, server value, or null).'); -}; -var validateEventType = function (fnName, argumentNumber, eventType, optional) { - if (optional && eventType === undefined) - return; - switch (eventType) { - case 'value': - case 'child_added': - case 'child_removed': - case 'child_changed': - case 'child_moved': - break; - default: - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid event type = "value", "child_added", "child_removed", ' + - '"child_changed", or "child_moved".'); - } -}; -var validateKey = function (fnName, argumentNumber, key, optional) { - if (optional && key === undefined) - return; - if (!isValidKey(key)) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'was an invalid key = "' + - key + - '". Firebase keys must be non-empty strings and ' + - 'can\'t contain ".", "#", "$", "/", "[", or "]").'); -}; -var validatePathString = function (fnName, argumentNumber, pathString, optional) { - if (optional && pathString === undefined) - return; - if (!isValidPathString(pathString)) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'was an invalid path = "' + - pathString + - '". Paths must be non-empty strings and ' + - 'can\'t contain ".", "#", "$", "[", or "]"'); -}; -var validateRootPathString = function (fnName, argumentNumber, pathString, optional) { - if (pathString) { - // Allow '/.info/' at the beginning. - pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); - } - validatePathString(fnName, argumentNumber, pathString, optional); -}; -var validateWritablePath = function (fnName, path) { - if (path.getFront() === '.info') { - throw new Error(fnName + " failed = Can't modify data under /.info/"); - } -}; -var validateUrl = function (fnName, argumentNumber, parsedUrl) { - // TODO = Validate server better. - var pathString = parsedUrl.path.toString(); - if (!(typeof parsedUrl.repoInfo.host === 'string') || - parsedUrl.repoInfo.host.length === 0 || - (!isValidKey(parsedUrl.repoInfo.namespace) && - parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || - (pathString.length !== 0 && !isValidRootPathString(pathString))) { - throw new Error(errorPrefix(fnName, argumentNumber, false) + - 'must be a valid firebase URL and ' + - 'the path can\'t contain ".", "#", "$", "[", or "]".'); - } -}; -var validateBoolean = function (fnName, argumentNumber, bool, optional) { - if (optional && bool === undefined) - return; - if (typeof bool !== 'boolean') - throw new Error(errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.'); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - */ -var OnDisconnect = /** @class */ (function () { - /** - * @param {!Repo} repo_ - * @param {!Path} path_ - */ - function OnDisconnect(repo_, path_) { - this.repo_ = repo_; - this.path_ = path_; - } - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.cancel = function (onComplete) { - validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); - validateCallback('OnDisconnect.cancel', 1, onComplete, true); - var deferred = new Deferred(); - this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.remove = function (onComplete) { - validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); - validateWritablePath('OnDisconnect.remove', this.path_); - validateCallback('OnDisconnect.remove', 1, onComplete, true); - var deferred = new Deferred(); - this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} value - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.set = function (value, onComplete) { - validateArgCount('OnDisconnect.set', 1, 2, arguments.length); - validateWritablePath('OnDisconnect.set', this.path_); - validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false); - validateCallback('OnDisconnect.set', 2, onComplete, true); - var deferred = new Deferred(); - this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} value - * @param {number|string|null} priority - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) { - validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); - validateWritablePath('OnDisconnect.setWithPriority', this.path_); - validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false); - validatePriority('OnDisconnect.setWithPriority', 2, priority, false); - validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true); - var deferred = new Deferred(); - this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.update = function (objectToMerge, onComplete) { - validateArgCount('OnDisconnect.update', 1, 2, arguments.length); - validateWritablePath('OnDisconnect.update', this.path_); - if (Array.isArray(objectToMerge)) { - var newObjectToMerge = {}; - for (var i = 0; i < objectToMerge.length; ++i) { - newObjectToMerge['' + i] = objectToMerge[i]; - } - objectToMerge = newObjectToMerge; - warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + - 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); - } - validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false); - validateCallback('OnDisconnect.update', 2, onComplete, true); - var deferred = new Deferred(); - this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - return OnDisconnect; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var TransactionResult = /** @class */ (function () { - /** - * A type for the resolve value of Firebase.transaction. - * @constructor - * @dict - * @param {boolean} committed - * @param {DataSnapshot} snapshot - */ - function TransactionResult(committed, snapshot) { - this.committed = committed; - this.snapshot = snapshot; - } - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users - TransactionResult.prototype.toJSON = function () { - validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); - return { committed: this.committed, snapshot: this.snapshot.toJSON() }; - }; - return TransactionResult; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Fancy ID generator that creates 20-character string identifiers with the - * following properties: - * - * 1. They're based on timestamp so that they sort *after* any existing ids. - * 2. They contain 72-bits of random data after the timestamp so that IDs won't - * collide with other clients' IDs. - * 3. They sort *lexicographically* (so the timestamp is converted to characters - * that will sort properly). - * 4. They're monotonically increasing. Even if you generate more than one in - * the same timestamp, the latter ones will sort after the former ones. We do - * this by using the previous random bits but "incrementing" them by 1 (only - * in the case of a timestamp collision). - */ -var nextPushId = (function () { - // Modeled after base64 web-safe chars, but ordered by ASCII. - var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; - // Timestamp of last push, used to prevent local collisions if you push twice - // in one ms. - var lastPushTime = 0; - // We generate 72-bits of randomness which get turned into 12 characters and - // appended to the timestamp to prevent collisions with other clients. We - // store the last characters we generated because in the event of a collision, - // we'll use those same characters except "incremented" by one. - var lastRandChars = []; - return function (now) { - var duplicateTime = now === lastPushTime; - lastPushTime = now; - var i; - var timeStampChars = new Array(8); - for (i = 7; i >= 0; i--) { - timeStampChars[i] = PUSH_CHARS.charAt(now % 64); - // NOTE: Can't use << here because javascript will convert to int and lose - // the upper bits. - now = Math.floor(now / 64); - } - assert(now === 0, 'Cannot push at time == 0'); - var id = timeStampChars.join(''); - if (!duplicateTime) { - for (i = 0; i < 12; i++) { - lastRandChars[i] = Math.floor(Math.random() * 64); - } - } - else { - // If the timestamp hasn't changed since last push, use the same random - // number, except incremented by 1. - for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { - lastRandChars[i] = 0; - } - lastRandChars[i]++; - } - for (i = 0; i < 12; i++) { - id += PUSH_CHARS.charAt(lastRandChars[i]); - } - assert(id.length === 20, 'nextPushId: Length should be 20.'); - return id; - }; -})(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @param {!string} name - * @param {!Node} node - * @constructor - * @struct - */ -var NamedNode = /** @class */ (function () { - function NamedNode(name, node) { - this.name = name; - this.node = node; - } - /** - * - * @param {!string} name - * @param {!Node} node - * @return {NamedNode} - */ - NamedNode.Wrap = function (name, node) { - return new NamedNode(name, node); - }; - return NamedNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @constructor - */ -var Index = /** @class */ (function () { - function Index() { - } - /** - * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for - * this index - */ - Index.prototype.getCompare = function () { - return this.compare.bind(this); - }; - /** - * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, - * it's possible that the changes are isolated to parts of the snapshot that are not indexed. - * - * @param {!Node} oldNode - * @param {!Node} newNode - * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode - */ - Index.prototype.indexedValueChanged = function (oldNode, newNode) { - var oldWrapped = new NamedNode(MIN_NAME, oldNode); - var newWrapped = new NamedNode(MIN_NAME, newNode); - return this.compare(oldWrapped, newWrapped) !== 0; - }; - /** - * @return {!NamedNode} a node wrapper that will sort equal to or less than - * any other node wrapper, using this index - */ - Index.prototype.minPost = function () { - return NamedNode.MIN; - }; - return Index; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __EMPTY_NODE; -var KeyIndex = /** @class */ (function (_super) { - __extends(KeyIndex, _super); - function KeyIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(KeyIndex, "__EMPTY_NODE", { - get: function () { - return __EMPTY_NODE; - }, - set: function (val) { - __EMPTY_NODE = val; - }, - enumerable: true, - configurable: true - }); - /** - * @inheritDoc - */ - KeyIndex.prototype.compare = function (a, b) { - return nameCompare(a.name, b.name); - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.isDefinedOn = function (node) { - // We could probably return true here (since every node has a key), but it's never called - // so just leaving unimplemented for now. - throw assertionError('KeyIndex.isDefinedOn not expected to be called.'); - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return false; // The key for a node never changes. - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.maxPost = function () { - // TODO: This should really be created once and cached in a static property, but - // NamedNode isn't defined yet, so I can't use it in a static. Bleh. - return new NamedNode(MAX_NAME, __EMPTY_NODE); - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - KeyIndex.prototype.makePost = function (indexValue, name) { - assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); - // We just use empty node, but it'll never be compared, since our comparator only looks at name. - return new NamedNode(indexValue, __EMPTY_NODE); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - KeyIndex.prototype.toString = function () { - return '.key'; - }; - return KeyIndex; -}(Index)); -var KEY_INDEX = new KeyIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MAX_NODE; -function setMaxNode(val) { - MAX_NODE = val; -} -/** - * @param {(!string|!number)} priority - * @return {!string} - */ -var priorityHashText = function (priority) { - if (typeof priority === 'number') - return 'number:' + doubleToIEEE754String(priority); - else - return 'string:' + priority; -}; -/** - * Validates that a priority snapshot Node is valid. - * - * @param {!Node} priorityNode - */ -var validatePriorityNode = function (priorityNode) { - if (priorityNode.isLeafNode()) { - var val = priorityNode.val(); - assert(typeof val === 'string' || - typeof val === 'number' || - (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.'); - } - else { - assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.'); - } - // Don't call getPriority() on MAX_NODE to avoid hitting assertion. - assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __childrenNodeConstructor; -/** - * LeafNode is a class for storing leaf nodes in a DataSnapshot. It - * implements Node and stores the value of the node (a string, - * number, or boolean) accessible via getValue(). - */ -var LeafNode = /** @class */ (function () { - /** - * @implements {Node} - * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node. - * The object type is possible in the event of a deferred value - * @param {!Node=} priorityNode_ The priority of this node. - */ - function LeafNode(value_, priorityNode_) { - if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; } - this.value_ = value_; - this.priorityNode_ = priorityNode_; - this.lazyHash_ = null; - assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); - validatePriorityNode(this.priorityNode_); - } - Object.defineProperty(LeafNode, "__childrenNodeConstructor", { - get: function () { - return __childrenNodeConstructor; - }, - set: function (val) { - __childrenNodeConstructor = val; - }, - enumerable: true, - configurable: true - }); - /** @inheritDoc */ - LeafNode.prototype.isLeafNode = function () { - return true; - }; - /** @inheritDoc */ - LeafNode.prototype.getPriority = function () { - return this.priorityNode_; - }; - /** @inheritDoc */ - LeafNode.prototype.updatePriority = function (newPriorityNode) { - return new LeafNode(this.value_, newPriorityNode); - }; - /** @inheritDoc */ - LeafNode.prototype.getImmediateChild = function (childName) { - // Hack to treat priority as a regular child - if (childName === '.priority') { - return this.priorityNode_; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE; - } - }; - /** @inheritDoc */ - LeafNode.prototype.getChild = function (path) { - if (path.isEmpty()) { - return this; - } - else if (path.getFront() === '.priority') { - return this.priorityNode_; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE; - } - }; - /** - * @inheritDoc - */ - LeafNode.prototype.hasChild = function () { - return false; - }; - /** @inheritDoc */ - LeafNode.prototype.getPredecessorChildName = function (childName, childNode) { - return null; - }; - /** @inheritDoc */ - LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) { - if (childName === '.priority') { - return this.updatePriority(newChildNode); - } - else if (newChildNode.isEmpty() && childName !== '.priority') { - return this; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); - } - }; - /** @inheritDoc */ - LeafNode.prototype.updateChild = function (path, newChildNode) { - var front = path.getFront(); - if (front === null) { - return newChildNode; - } - else if (newChildNode.isEmpty() && front !== '.priority') { - return this; - } - else { - assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path'); - return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode)); - } - }; - /** @inheritDoc */ - LeafNode.prototype.isEmpty = function () { - return false; - }; - /** @inheritDoc */ - LeafNode.prototype.numChildren = function () { - return 0; - }; - /** @inheritDoc */ - LeafNode.prototype.forEachChild = function (index, action) { - return false; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.val = function (exportFormat) { - if (exportFormat && !this.getPriority().isEmpty()) - return { - '.value': this.getValue(), - '.priority': this.getPriority().val() - }; - else - return this.getValue(); - }; - /** @inheritDoc */ - LeafNode.prototype.hash = function () { - if (this.lazyHash_ === null) { - var toHash = ''; - if (!this.priorityNode_.isEmpty()) - toHash += - 'priority:' + - priorityHashText(this.priorityNode_.val()) + - ':'; - var type = typeof this.value_; - toHash += type + ':'; - if (type === 'number') { - toHash += doubleToIEEE754String(this.value_); - } - else { - toHash += this.value_; - } - this.lazyHash_ = sha1(toHash); - } - return this.lazyHash_; - }; - /** - * Returns the value of the leaf node. - * @return {Object|string|number|boolean} The value of the node. - */ - LeafNode.prototype.getValue = function () { - return this.value_; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.compareTo = function (other) { - if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { - return 1; - } - else if (other instanceof LeafNode.__childrenNodeConstructor) { - return -1; - } - else { - assert(other.isLeafNode(), 'Unknown node type'); - return this.compareToLeafNode_(other); - } - }; - /** - * Comparison specifically for two leaf nodes - * @param {!LeafNode} otherLeaf - * @return {!number} - * @private - */ - LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) { - var otherLeafType = typeof otherLeaf.value_; - var thisLeafType = typeof this.value_; - var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); - var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); - assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); - assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); - if (otherIndex === thisIndex) { - // Same type, compare values - if (thisLeafType === 'object') { - // Deferred value nodes are all equal, but we should also never get to this point... - return 0; - } - else { - // Note that this works because true > false, all others are number or string comparisons - if (this.value_ < otherLeaf.value_) { - return -1; - } - else if (this.value_ === otherLeaf.value_) { - return 0; - } - else { - return 1; - } - } - } - else { - return thisIndex - otherIndex; - } - }; - /** - * @inheritDoc - */ - LeafNode.prototype.withIndex = function () { - return this; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.isIndexed = function () { - return true; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.equals = function (other) { - /** - * @inheritDoc - */ - if (other === this) { - return true; - } - else if (other.isLeafNode()) { - var otherLeaf = other; - return (this.value_ === otherLeaf.value_ && - this.priorityNode_.equals(otherLeaf.priorityNode_)); - } - else { - return false; - } - }; - /** - * The sort order for comparing leaf nodes of different types. If two leaf nodes have - * the same type, the comparison falls back to their value - * @type {Array.} - * @const - */ - LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; - return LeafNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var nodeFromJSON; -var MAX_NODE$1; -function setNodeFromJSON(val) { - nodeFromJSON = val; -} -function setMaxNode$1(val) { - MAX_NODE$1 = val; -} -/** - * @constructor - * @extends {Index} - * @private - */ -var PriorityIndex = /** @class */ (function (_super) { - __extends(PriorityIndex, _super); - function PriorityIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - PriorityIndex.prototype.compare = function (a, b) { - var aPriority = a.node.getPriority(); - var bPriority = b.node.getPriority(); - var indexCmp = aPriority.compareTo(bPriority); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.isDefinedOn = function (node) { - return !node.getPriority().isEmpty(); - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return !oldNode.getPriority().equals(newNode.getPriority()); - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.maxPost = function () { - return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - PriorityIndex.prototype.makePost = function (indexValue, name) { - var priorityNode = nodeFromJSON(indexValue); - return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - PriorityIndex.prototype.toString = function () { - return '.priority'; - }; - return PriorityIndex; -}(Index)); -var PRIORITY_INDEX = new PriorityIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An iterator over an LLRBNode. - */ -var SortedMapIterator = /** @class */ (function () { - /** - * @template K, V, T - * @param {LLRBNode|LLRBEmptyNode} node Node to iterate. - * @param {?K} startKey - * @param {function(K, K): number} comparator - * @param {boolean} isReverse_ Whether or not to iterate in reverse - * @param {(function(K, V):T)=} resultGenerator_ - */ - function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) { - if (resultGenerator_ === void 0) { resultGenerator_ = null; } - this.isReverse_ = isReverse_; - this.resultGenerator_ = resultGenerator_; - /** @private - * @type {Array.} - */ - this.nodeStack_ = []; - var cmp = 1; - while (!node.isEmpty()) { - node = node; - cmp = startKey ? comparator(node.key, startKey) : 1; - // flip the comparison if we're going in reverse - if (isReverse_) - cmp *= -1; - if (cmp < 0) { - // This node is less than our start key. ignore it - if (this.isReverse_) { - node = node.left; - } - else { - node = node.right; - } - } - else if (cmp === 0) { - // This node is exactly equal to our start key. Push it on the stack, but stop iterating; - this.nodeStack_.push(node); - break; - } - else { - // This node is greater than our start key, add it to the stack and move to the next one - this.nodeStack_.push(node); - if (this.isReverse_) { - node = node.right; - } - else { - node = node.left; - } - } - } - } - SortedMapIterator.prototype.getNext = function () { - if (this.nodeStack_.length === 0) - return null; - var node = this.nodeStack_.pop(); - var result; - if (this.resultGenerator_) - result = this.resultGenerator_(node.key, node.value); - else - result = { key: node.key, value: node.value }; - if (this.isReverse_) { - node = node.left; - while (!node.isEmpty()) { - this.nodeStack_.push(node); - node = node.right; - } - } - else { - node = node.right; - while (!node.isEmpty()) { - this.nodeStack_.push(node); - node = node.left; - } - } - return result; - }; - SortedMapIterator.prototype.hasNext = function () { - return this.nodeStack_.length > 0; - }; - SortedMapIterator.prototype.peek = function () { - if (this.nodeStack_.length === 0) - return null; - var node = this.nodeStack_[this.nodeStack_.length - 1]; - if (this.resultGenerator_) { - return this.resultGenerator_(node.key, node.value); - } - else { - return { key: node.key, value: node.value }; - } - }; - return SortedMapIterator; -}()); -/** - * Represents a node in a Left-leaning Red-Black tree. - */ -var LLRBNode = /** @class */ (function () { - /** - * @template K, V - * @param {!K} key Key associated with this node. - * @param {!V} value Value associated with this node. - * @param {?boolean} color Whether this node is red. - * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child. - * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child. - */ - function LLRBNode(key, value, color, left, right) { - this.key = key; - this.value = value; - this.color = color != null ? color : LLRBNode.RED; - this.left = - left != null ? left : SortedMap.EMPTY_NODE; - this.right = - right != null ? right : SortedMap.EMPTY_NODE; - } - /** - * Returns a copy of the current node, optionally replacing pieces of it. - * - * @param {?K} key New key for the node, or null. - * @param {?V} value New value for the node, or null. - * @param {?boolean} color New color for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null. - * @return {!LLRBNode} The node copy. - */ - LLRBNode.prototype.copy = function (key, value, color, left, right) { - return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); - }; - /** - * @return {number} The total number of nodes in the tree. - */ - LLRBNode.prototype.count = function () { - return this.left.count() + 1 + this.right.count(); - }; - /** - * @return {boolean} True if the tree is empty. - */ - LLRBNode.prototype.isEmpty = function () { - return false; - }; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - LLRBNode.prototype.inorderTraversal = function (action) { - return (this.left.inorderTraversal(action) || - action(this.key, this.value) || - this.right.inorderTraversal(action)); - }; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!Object, !Object)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} True if traversal was aborted. - */ - LLRBNode.prototype.reverseTraversal = function (action) { - return (this.right.reverseTraversal(action) || - action(this.key, this.value) || - this.left.reverseTraversal(action)); - }; - /** - * @return {!Object} The minimum node in the tree. - * @private - */ - LLRBNode.prototype.min_ = function () { - if (this.left.isEmpty()) { - return this; - } - else { - return this.left.min_(); - } - }; - /** - * @return {!K} The maximum key in the tree. - */ - LLRBNode.prototype.minKey = function () { - return this.min_().key; - }; - /** - * @return {!K} The maximum key in the tree. - */ - LLRBNode.prototype.maxKey = function () { - if (this.right.isEmpty()) { - return this.key; - } - else { - return this.right.maxKey(); - } - }; - /** - * - * @param {!Object} key Key to insert. - * @param {!Object} value Value to insert. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with the key/value added. - */ - LLRBNode.prototype.insert = function (key, value, comparator) { - var cmp, n; - n = this; - cmp = comparator(key, n.key); - if (cmp < 0) { - n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); - } - else if (cmp === 0) { - n = n.copy(null, value, null, null, null); - } - else { - n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); - } - return n.fixUp_(); - }; - /** - * @private - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed. - */ - LLRBNode.prototype.removeMin_ = function () { - if (this.left.isEmpty()) { - return SortedMap.EMPTY_NODE; - } - var n = this; - if (!n.left.isRed_() && !n.left.left.isRed_()) - n = n.moveRedLeft_(); - n = n.copy(null, null, null, n.left.removeMin_(), null); - return n.fixUp_(); - }; - /** - * @param {!Object} key The key of the item to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed. - */ - LLRBNode.prototype.remove = function (key, comparator) { - var n, smallest; - n = this; - if (comparator(key, n.key) < 0) { - if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { - n = n.moveRedLeft_(); - } - n = n.copy(null, null, null, n.left.remove(key, comparator), null); - } - else { - if (n.left.isRed_()) - n = n.rotateRight_(); - if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { - n = n.moveRedRight_(); - } - if (comparator(key, n.key) === 0) { - if (n.right.isEmpty()) { - return SortedMap.EMPTY_NODE; - } - else { - smallest = n.right.min_(); - n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); - } - } - n = n.copy(null, null, null, null, n.right.remove(key, comparator)); - } - return n.fixUp_(); - }; - /** - * @private - * @return {boolean} Whether this is a RED node. - */ - LLRBNode.prototype.isRed_ = function () { - return this.color; - }; - /** - * @private - * @return {!LLRBNode} New tree after performing any needed rotations. - */ - LLRBNode.prototype.fixUp_ = function () { - var n = this; - if (n.right.isRed_() && !n.left.isRed_()) - n = n.rotateLeft_(); - if (n.left.isRed_() && n.left.left.isRed_()) - n = n.rotateRight_(); - if (n.left.isRed_() && n.right.isRed_()) - n = n.colorFlip_(); - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after moveRedLeft. - */ - LLRBNode.prototype.moveRedLeft_ = function () { - var n = this.colorFlip_(); - if (n.right.left.isRed_()) { - n = n.copy(null, null, null, null, n.right.rotateRight_()); - n = n.rotateLeft_(); - n = n.colorFlip_(); - } - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after moveRedRight. - */ - LLRBNode.prototype.moveRedRight_ = function () { - var n = this.colorFlip_(); - if (n.left.left.isRed_()) { - n = n.rotateRight_(); - n = n.colorFlip_(); - } - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after rotateLeft. - */ - LLRBNode.prototype.rotateLeft_ = function () { - var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); - return this.right.copy(null, null, this.color, nl, null); - }; - /** - * @private - * @return {!LLRBNode} New tree, after rotateRight. - */ - LLRBNode.prototype.rotateRight_ = function () { - var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); - return this.left.copy(null, null, this.color, null, nr); - }; - /** - * @private - * @return {!LLRBNode} New tree, after colorFlip. - */ - LLRBNode.prototype.colorFlip_ = function () { - var left = this.left.copy(null, null, !this.left.color, null, null); - var right = this.right.copy(null, null, !this.right.color, null, null); - return this.copy(null, null, !this.color, left, right); - }; - /** - * For testing. - * - * @private - * @return {boolean} True if all is well. - */ - LLRBNode.prototype.checkMaxDepth_ = function () { - var blackDepth = this.check_(); - return Math.pow(2.0, blackDepth) <= this.count() + 1; - }; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - LLRBNode.prototype.check_ = function () { - var blackDepth; - if (this.isRed_() && this.left.isRed_()) { - throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); - } - if (this.right.isRed_()) { - throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); - } - blackDepth = this.left.check_(); - if (blackDepth !== this.right.check_()) { - throw new Error('Black depths differ'); - } - else { - return blackDepth + (this.isRed_() ? 0 : 1); - } - }; - LLRBNode.RED = true; - LLRBNode.BLACK = false; - return LLRBNode; -}()); -/** - * Represents an empty node (a leaf node in the Red-Black Tree). - */ -var LLRBEmptyNode = /** @class */ (function () { - function LLRBEmptyNode() { - } - /** - * Returns a copy of the current node. - * - * @return {!LLRBEmptyNode} The node copy. - */ - LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) { - return this; - }; - /** - * Returns a copy of the tree, with the specified key/value added. - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with item added. - */ - LLRBEmptyNode.prototype.insert = function (key, value, comparator) { - return new LLRBNode(key, value, null); - }; - /** - * Returns a copy of the tree, with the specified key removed. - * - * @param {!K} key The key to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBEmptyNode} New tree, with item removed. - */ - LLRBEmptyNode.prototype.remove = function (key, comparator) { - return this; - }; - /** - * @return {number} The total number of nodes in the tree. - */ - LLRBEmptyNode.prototype.count = function () { - return 0; - }; - /** - * @return {boolean} True if the tree is empty. - */ - LLRBEmptyNode.prototype.isEmpty = function () { - return true; - }; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - LLRBEmptyNode.prototype.inorderTraversal = function (action) { - return false; - }; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - LLRBEmptyNode.prototype.reverseTraversal = function (action) { - return false; - }; - /** - * @return {null} - */ - LLRBEmptyNode.prototype.minKey = function () { - return null; - }; - /** - * @return {null} - */ - LLRBEmptyNode.prototype.maxKey = function () { - return null; - }; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - LLRBEmptyNode.prototype.check_ = function () { - return 0; - }; - /** - * @private - * @return {boolean} Whether this node is red. - */ - LLRBEmptyNode.prototype.isRed_ = function () { - return false; - }; - return LLRBEmptyNode; -}()); -/** - * An immutable sorted map implementation, based on a Left-leaning Red-Black - * tree. - */ -var SortedMap = /** @class */ (function () { - /** - * @template K, V - * @param {function(K, K):number} comparator_ Key comparator. - * @param {LLRBNode=} root_ (Optional) Root node for the map. - */ - function SortedMap(comparator_, root_) { - if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; } - this.comparator_ = comparator_; - this.root_ = root_; - } - /** - * Returns a copy of the map, with the specified key/value added or replaced. - * (TODO: We should perhaps rename this method to 'put') - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @return {!SortedMap.} New map, with item added. - */ - SortedMap.prototype.insert = function (key, value) { - return new SortedMap(this.comparator_, this.root_ - .insert(key, value, this.comparator_) - .copy(null, null, LLRBNode.BLACK, null, null)); - }; - /** - * Returns a copy of the map, with the specified key removed. - * - * @param {!K} key The key to remove. - * @return {!SortedMap.} New map, with item removed. - */ - SortedMap.prototype.remove = function (key) { - return new SortedMap(this.comparator_, this.root_ - .remove(key, this.comparator_) - .copy(null, null, LLRBNode.BLACK, null, null)); - }; - /** - * Returns the value of the node with the given key, or null. - * - * @param {!K} key The key to look up. - * @return {?V} The value of the node with the given key, or null if the - * key doesn't exist. - */ - SortedMap.prototype.get = function (key) { - var cmp; - var node = this.root_; - while (!node.isEmpty()) { - cmp = this.comparator_(key, node.key); - if (cmp === 0) { - return node.value; - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - node = node.right; - } - } - return null; - }; - /** - * Returns the key of the item *before* the specified key, or null if key is the first item. - * @param {K} key The key to find the predecessor of - * @return {?K} The predecessor key. - */ - SortedMap.prototype.getPredecessorKey = function (key) { - var cmp, node = this.root_, rightParent = null; - while (!node.isEmpty()) { - cmp = this.comparator_(key, node.key); - if (cmp === 0) { - if (!node.left.isEmpty()) { - node = node.left; - while (!node.right.isEmpty()) - node = node.right; - return node.key; - } - else if (rightParent) { - return rightParent.key; - } - else { - return null; // first item. - } - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - rightParent = node; - node = node.right; - } - } - throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); - }; - /** - * @return {boolean} True if the map is empty. - */ - SortedMap.prototype.isEmpty = function () { - return this.root_.isEmpty(); - }; - /** - * @return {number} The total number of nodes in the map. - */ - SortedMap.prototype.count = function () { - return this.root_.count(); - }; - /** - * @return {?K} The minimum key in the map. - */ - SortedMap.prototype.minKey = function () { - return this.root_.minKey(); - }; - /** - * @return {?K} The maximum key in the map. - */ - SortedMap.prototype.maxKey = function () { - return this.root_.maxKey(); - }; - /** - * Traverses the map in key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!K, !V):*} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - SortedMap.prototype.inorderTraversal = function (action) { - return this.root_.inorderTraversal(action); - }; - /** - * Traverses the map in reverse key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!Object, !Object)} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} True if the traversal was aborted. - */ - SortedMap.prototype.reverseTraversal = function (action) { - return this.root_.reverseTraversal(action); - }; - /** - * Returns an iterator over the SortedMap. - * @template T - * @param {(function(K, V):T)=} resultGenerator - * @return {SortedMapIterator.} The iterator. - */ - SortedMap.prototype.getIterator = function (resultGenerator) { - return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); - }; - SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) { - return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); - }; - SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) { - return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); - }; - SortedMap.prototype.getReverseIterator = function (resultGenerator) { - return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); - }; - /** - * Always use the same empty node, to reduce memory. - * @const - */ - SortedMap.EMPTY_NODE = new LLRBEmptyNode(); - return SortedMap; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var LOG_2 = Math.log(2); -/** - * @constructor - */ -var Base12Num = /** @class */ (function () { - /** - * @param {number} length - */ - function Base12Num(length) { - var logBase2 = function (num) { - return parseInt((Math.log(num) / LOG_2), 10); - }; - var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); }; - this.count = logBase2(length + 1); - this.current_ = this.count - 1; - var mask = bitMask(this.count); - this.bits_ = (length + 1) & mask; - } - /** - * @return {boolean} - */ - Base12Num.prototype.nextBitIsOne = function () { - //noinspection JSBitwiseOperatorUsage - var result = !(this.bits_ & (0x1 << this.current_)); - this.current_--; - return result; - }; - return Base12Num; -}()); -/** - * Takes a list of child nodes and constructs a SortedSet using the given comparison - * function - * - * Uses the algorithm described in the paper linked here: - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 - * - * @template K, V - * @param {Array.} childList Unsorted list of children - * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used - * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's - * type is not NamedNode - * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map - * @return {SortedMap.} - */ -var buildChildSet = function (childList, cmp, keyFn, mapSortFn) { - childList.sort(cmp); - var buildBalancedTree = function (low, high) { - var length = high - low; - var namedNode; - var key; - if (length == 0) { - return null; - } - else if (length == 1) { - namedNode = childList[low]; - key = keyFn ? keyFn(namedNode) : namedNode; - return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); - } - else { - var middle = parseInt((length / 2), 10) + low; - var left = buildBalancedTree(low, middle); - var right = buildBalancedTree(middle + 1, high); - namedNode = childList[middle]; - key = keyFn ? keyFn(namedNode) : namedNode; - return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); - } - }; - var buildFrom12Array = function (base12) { - var node = null; - var root = null; - var index = childList.length; - var buildPennant = function (chunkSize, color) { - var low = index - chunkSize; - var high = index; - index -= chunkSize; - var childTree = buildBalancedTree(low + 1, high); - var namedNode = childList[low]; - var key = keyFn ? keyFn(namedNode) : namedNode; - attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); - }; - var attachPennant = function (pennant) { - if (node) { - node.left = pennant; - node = pennant; - } - else { - root = pennant; - node = pennant; - } - }; - for (var i = 0; i < base12.count; ++i) { - var isOne = base12.nextBitIsOne(); - // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) - var chunkSize = Math.pow(2, base12.count - (i + 1)); - if (isOne) { - buildPennant(chunkSize, LLRBNode.BLACK); - } - else { - // current == 2 - buildPennant(chunkSize, LLRBNode.BLACK); - buildPennant(chunkSize, LLRBNode.RED); - } - } - return root; - }; - var base12 = new Base12Num(childList.length); - var root = buildFrom12Array(base12); - return new SortedMap(mapSortFn || cmp, root); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var _defaultIndexMap; -var fallbackObject = {}; -/** - * - * @param {Object.>} indexes - * @param {Object.} indexSet - * @constructor - */ -var IndexMap = /** @class */ (function () { - function IndexMap(indexes_, indexSet_) { - this.indexes_ = indexes_; - this.indexSet_ = indexSet_; - } - Object.defineProperty(IndexMap, "Default", { - /** - * The default IndexMap for nodes without a priority - * @type {!IndexMap} - * @const - */ - get: function () { - assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); - _defaultIndexMap = - _defaultIndexMap || - new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); - return _defaultIndexMap; - }, - enumerable: true, - configurable: true - }); - /** - * - * @param {!string} indexKey - * @return {?SortedMap.} - */ - IndexMap.prototype.get = function (indexKey) { - var sortedMap = safeGet(this.indexes_, indexKey); - if (!sortedMap) - throw new Error('No index defined for ' + indexKey); - if (sortedMap === fallbackObject) { - // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the - // regular child map - return null; - } - else { - return sortedMap; - } - }; - /** - * @param {!Index} indexDefinition - * @return {boolean} - */ - IndexMap.prototype.hasIndex = function (indexDefinition) { - return contains(this.indexSet_, indexDefinition.toString()); - }; - /** - * @param {!Index} indexDefinition - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) { - assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); - var childList = []; - var sawIndexedValue = false; - var iter = existingChildren.getIterator(NamedNode.Wrap); - var next = iter.getNext(); - while (next) { - sawIndexedValue = - sawIndexedValue || indexDefinition.isDefinedOn(next.node); - childList.push(next); - next = iter.getNext(); - } - var newIndex; - if (sawIndexedValue) { - newIndex = buildChildSet(childList, indexDefinition.getCompare()); - } - else { - newIndex = fallbackObject; - } - var indexName = indexDefinition.toString(); - var newIndexSet = clone(this.indexSet_); - newIndexSet[indexName] = indexDefinition; - var newIndexes = clone(this.indexes_); - newIndexes[indexName] = newIndex; - return new IndexMap(newIndexes, newIndexSet); - }; - /** - * Ensure that this node is properly tracked in any indexes that we're maintaining - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) { - var _this = this; - var newIndexes = map(this.indexes_, function (indexedChildren, indexName) { - var index = safeGet(_this.indexSet_, indexName); - assert(index, 'Missing index implementation for ' + indexName); - if (indexedChildren === fallbackObject) { - // Check to see if we need to index everything - if (index.isDefinedOn(namedNode.node)) { - // We need to build this index - var childList = []; - var iter = existingChildren.getIterator(NamedNode.Wrap); - var next = iter.getNext(); - while (next) { - if (next.name != namedNode.name) { - childList.push(next); - } - next = iter.getNext(); - } - childList.push(namedNode); - return buildChildSet(childList, index.getCompare()); - } - else { - // No change, this remains a fallback - return fallbackObject; - } - } - else { - var existingSnap = existingChildren.get(namedNode.name); - var newChildren = indexedChildren; - if (existingSnap) { - newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); - } - return newChildren.insert(namedNode, namedNode.node); - } - }); - return new IndexMap(newIndexes, this.indexSet_); - }; - /** - * Create a new IndexMap instance with the given value removed - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) { - var newIndexes = map(this.indexes_, function (indexedChildren) { - if (indexedChildren === fallbackObject) { - // This is the fallback. Just return it, nothing to do in this case - return indexedChildren; - } - else { - var existingSnap = existingChildren.get(namedNode.name); - if (existingSnap) { - return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); - } - else { - // No record of this child - return indexedChildren; - } - } - }); - return new IndexMap(newIndexes, this.indexSet_); - }; - return IndexMap; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function NAME_ONLY_COMPARATOR(left, right) { - return nameCompare(left.name, right.name); -} -function NAME_COMPARATOR(left, right) { - return nameCompare(left, right); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// TODO: For memory savings, don't store priorityNode_ if it's empty. -var EMPTY_NODE; -/** - * ChildrenNode is a class for storing internal nodes in a DataSnapshot - * (i.e. nodes with children). It implements Node and stores the - * list of children in the children property, sorted by child name. - * - * @constructor - * @implements {Node} - */ -var ChildrenNode = /** @class */ (function () { - /** - * - * @param {!SortedMap.} children_ List of children - * of this node.. - * @param {?Node} priorityNode_ The priority of this node (as a snapshot node). - * @param {!IndexMap} indexMap_ - */ - function ChildrenNode(children_, priorityNode_, indexMap_) { - this.children_ = children_; - this.priorityNode_ = priorityNode_; - this.indexMap_ = indexMap_; - this.lazyHash_ = null; - /** - * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use - * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own - * class instead of an empty ChildrenNode. - */ - if (this.priorityNode_) { - validatePriorityNode(this.priorityNode_); - } - if (this.children_.isEmpty()) { - assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); - } - } - Object.defineProperty(ChildrenNode, "EMPTY_NODE", { - get: function () { - return (EMPTY_NODE || - (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); - }, - enumerable: true, - configurable: true - }); - /** @inheritDoc */ - ChildrenNode.prototype.isLeafNode = function () { - return false; - }; - /** @inheritDoc */ - ChildrenNode.prototype.getPriority = function () { - return this.priorityNode_ || EMPTY_NODE; - }; - /** @inheritDoc */ - ChildrenNode.prototype.updatePriority = function (newPriorityNode) { - if (this.children_.isEmpty()) { - // Don't allow priorities on empty nodes - return this; - } - else { - return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.getImmediateChild = function (childName) { - // Hack to treat priority as a regular child - if (childName === '.priority') { - return this.getPriority(); - } - else { - var child = this.children_.get(childName); - return child === null ? EMPTY_NODE : child; - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.getChild = function (path) { - var front = path.getFront(); - if (front === null) - return this; - return this.getImmediateChild(front).getChild(path.popFront()); - }; - /** @inheritDoc */ - ChildrenNode.prototype.hasChild = function (childName) { - return this.children_.get(childName) !== null; - }; - /** @inheritDoc */ - ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) { - assert(newChildNode, 'We should always be passing snapshot nodes'); - if (childName === '.priority') { - return this.updatePriority(newChildNode); - } - else { - var namedNode = new NamedNode(childName, newChildNode); - var newChildren = void 0, newIndexMap = void 0, newPriority = void 0; - if (newChildNode.isEmpty()) { - newChildren = this.children_.remove(childName); - newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); - } - else { - newChildren = this.children_.insert(childName, newChildNode); - newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); - } - newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_; - return new ChildrenNode(newChildren, newPriority, newIndexMap); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.updateChild = function (path, newChildNode) { - var front = path.getFront(); - if (front === null) { - return newChildNode; - } - else { - assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path'); - var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode); - return this.updateImmediateChild(front, newImmediateChild); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.isEmpty = function () { - return this.children_.isEmpty(); - }; - /** @inheritDoc */ - ChildrenNode.prototype.numChildren = function () { - return this.children_.count(); - }; - /** @inheritDoc */ - ChildrenNode.prototype.val = function (exportFormat) { - if (this.isEmpty()) - return null; - var obj = {}; - var numKeys = 0, maxKey = 0, allIntegerKeys = true; - this.forEachChild(PRIORITY_INDEX, function (key, childNode) { - obj[key] = childNode.val(exportFormat); - numKeys++; - if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { - maxKey = Math.max(maxKey, Number(key)); - } - else { - allIntegerKeys = false; - } - }); - if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { - // convert to array. - var array = []; - for (var key in obj) - array[key] = obj[key]; - return array; - } - else { - if (exportFormat && !this.getPriority().isEmpty()) { - obj['.priority'] = this.getPriority().val(); - } - return obj; - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.hash = function () { - if (this.lazyHash_ === null) { - var toHash_1 = ''; - if (!this.getPriority().isEmpty()) - toHash_1 += - 'priority:' + - priorityHashText(this.getPriority().val()) + - ':'; - this.forEachChild(PRIORITY_INDEX, function (key, childNode) { - var childHash = childNode.hash(); - if (childHash !== '') - toHash_1 += ':' + key + ':' + childHash; - }); - this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1); - } - return this.lazyHash_; - }; - /** @inheritDoc */ - ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) { - var idx = this.resolveIndex_(index); - if (idx) { - var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); - return predecessor ? predecessor.name : null; - } - else { - return this.children_.getPredecessorKey(childName); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?string} - */ - ChildrenNode.prototype.getFirstChildName = function (indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - var minKey = idx.minKey(); - return minKey && minKey.name; - } - else { - return this.children_.minKey(); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - ChildrenNode.prototype.getFirstChild = function (indexDefinition) { - var minKey = this.getFirstChildName(indexDefinition); - if (minKey) { - return new NamedNode(minKey, this.children_.get(minKey)); - } - else { - return null; - } - }; - /** - * Given an index, return the key name of the largest value we have, according to that index - * @param {!Index} indexDefinition - * @return {?string} - */ - ChildrenNode.prototype.getLastChildName = function (indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - var maxKey = idx.maxKey(); - return maxKey && maxKey.name; - } - else { - return this.children_.maxKey(); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - ChildrenNode.prototype.getLastChild = function (indexDefinition) { - var maxKey = this.getLastChildName(indexDefinition); - if (maxKey) { - return new NamedNode(maxKey, this.children_.get(maxKey)); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.forEachChild = function (index, action) { - var idx = this.resolveIndex_(index); - if (idx) { - return idx.inorderTraversal(function (wrappedNode) { - return action(wrappedNode.name, wrappedNode.node); - }); - } - else { - return this.children_.inorderTraversal(action); - } - }; - /** - * @param {!Index} indexDefinition - * @return {SortedMapIterator} - */ - ChildrenNode.prototype.getIterator = function (indexDefinition) { - return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); - }; - /** - * - * @param {!NamedNode} startPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - return idx.getIteratorFrom(startPost, function (key) { return key; }); - } - else { - var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); - var next = iterator.peek(); - while (next != null && indexDefinition.compare(next, startPost) < 0) { - iterator.getNext(); - next = iterator.peek(); - } - return iterator; - } - }; - /** - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getReverseIterator = function (indexDefinition) { - return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); - }; - /** - * @param {!NamedNode} endPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - return idx.getReverseIteratorFrom(endPost, function (key) { - return key; - }); - } - else { - var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); - var next = iterator.peek(); - while (next != null && indexDefinition.compare(next, endPost) > 0) { - iterator.getNext(); - next = iterator.peek(); - } - return iterator; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.compareTo = function (other) { - if (this.isEmpty()) { - if (other.isEmpty()) { - return 0; - } - else { - return -1; - } - } - else if (other.isLeafNode() || other.isEmpty()) { - return 1; - } - else if (other === MAX_NODE$2) { - return -1; - } - else { - // Must be another node with children. - return 0; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.withIndex = function (indexDefinition) { - if (indexDefinition === KEY_INDEX || - this.indexMap_.hasIndex(indexDefinition)) { - return this; - } - else { - var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); - return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.isIndexed = function (index) { - return index === KEY_INDEX || this.indexMap_.hasIndex(index); - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.equals = function (other) { - if (other === this) { - return true; - } - else if (other.isLeafNode()) { - return false; - } - else { - var otherChildrenNode = other; - if (!this.getPriority().equals(otherChildrenNode.getPriority())) { - return false; - } - else if (this.children_.count() === otherChildrenNode.children_.count()) { - var thisIter = this.getIterator(PRIORITY_INDEX); - var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); - var thisCurrent = thisIter.getNext(); - var otherCurrent = otherIter.getNext(); - while (thisCurrent && otherCurrent) { - if (thisCurrent.name !== otherCurrent.name || - !thisCurrent.node.equals(otherCurrent.node)) { - return false; - } - thisCurrent = thisIter.getNext(); - otherCurrent = otherIter.getNext(); - } - return thisCurrent === null && otherCurrent === null; - } - else { - return false; - } - } - }; - /** - * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used - * instead. - * - * @private - * @param {!Index} indexDefinition - * @return {?SortedMap.} - */ - ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) { - if (indexDefinition === KEY_INDEX) { - return null; - } - else { - return this.indexMap_.get(indexDefinition.toString()); - } - }; - /** - * @private - * @type {RegExp} - */ - ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; - return ChildrenNode; -}()); -/** - * @constructor - * @extends {ChildrenNode} - * @private - */ -var MaxNode = /** @class */ (function (_super) { - __extends(MaxNode, _super); - function MaxNode() { - return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this; - } - MaxNode.prototype.compareTo = function (other) { - if (other === this) { - return 0; - } - else { - return 1; - } - }; - MaxNode.prototype.equals = function (other) { - // Not that we every compare it, but MAX_NODE is only ever equal to itself - return other === this; - }; - MaxNode.prototype.getPriority = function () { - return this; - }; - MaxNode.prototype.getImmediateChild = function (childName) { - return ChildrenNode.EMPTY_NODE; - }; - MaxNode.prototype.isEmpty = function () { - return false; - }; - return MaxNode; -}(ChildrenNode)); -/** - * Marker that will sort higher than any other snapshot. - * @type {!MAX_NODE} - * @const - */ -var MAX_NODE$2 = new MaxNode(); -Object.defineProperties(NamedNode, { - MIN: { - value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) - }, - MAX: { - value: new NamedNode(MAX_NAME, MAX_NODE$2) - } -}); -/** - * Reference Extensions - */ -KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; -LeafNode.__childrenNodeConstructor = ChildrenNode; -setMaxNode(MAX_NODE$2); -setMaxNode$1(MAX_NODE$2); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var USE_HINZE = true; -/** - * Constructs a snapshot node representing the passed JSON and returns it. - * @param {*} json JSON to create a node for. - * @param {?string|?number=} priority Optional priority to use. This will be ignored if the - * passed JSON contains a .priority property. - * @return {!Node} - */ -function nodeFromJSON$1(json, priority) { - if (priority === void 0) { priority = null; } - if (json === null) { - return ChildrenNode.EMPTY_NODE; - } - if (typeof json === 'object' && '.priority' in json) { - priority = json['.priority']; - } - assert(priority === null || - typeof priority === 'string' || - typeof priority === 'number' || - (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); - if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { - json = json['.value']; - } - // Valid leaf nodes include non-objects or server-value wrapper objects - if (typeof json !== 'object' || '.sv' in json) { - var jsonLeaf = json; - return new LeafNode(jsonLeaf, nodeFromJSON$1(priority)); - } - if (!(json instanceof Array) && USE_HINZE) { - var children_1 = []; - var childrenHavePriority_1 = false; - var hinzeJsonObj_1 = json; - forEach(hinzeJsonObj_1, function (key, child) { - if (typeof key !== 'string' || key.substring(0, 1) !== '.') { - // Ignore metadata nodes - var childNode = nodeFromJSON$1(hinzeJsonObj_1[key]); - if (!childNode.isEmpty()) { - childrenHavePriority_1 = - childrenHavePriority_1 || !childNode.getPriority().isEmpty(); - children_1.push(new NamedNode(key, childNode)); - } - } - }); - if (children_1.length == 0) { - return ChildrenNode.EMPTY_NODE; - } - var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR); - if (childrenHavePriority_1) { - var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare()); - return new ChildrenNode(childSet, nodeFromJSON$1(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); - } - else { - return new ChildrenNode(childSet, nodeFromJSON$1(priority), IndexMap.Default); - } - } - else { - var node_1 = ChildrenNode.EMPTY_NODE; - var jsonObj_1 = json; - forEach(jsonObj_1, function (key, childData) { - if (contains(jsonObj_1, key)) { - if (key.substring(0, 1) !== '.') { - // ignore metadata nodes. - var childNode = nodeFromJSON$1(childData); - if (childNode.isLeafNode() || !childNode.isEmpty()) - node_1 = node_1.updateImmediateChild(key, childNode); - } - } - }); - return node_1.updatePriority(nodeFromJSON$1(priority)); - } -} -setNodeFromJSON(nodeFromJSON$1); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @extends {Index} - * @private - */ -var ValueIndex = /** @class */ (function (_super) { - __extends(ValueIndex, _super); - function ValueIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - ValueIndex.prototype.compare = function (a, b) { - var indexCmp = a.node.compareTo(b.node); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.isDefinedOn = function (node) { - return true; - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return !oldNode.equals(newNode); - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.maxPost = function () { - return NamedNode.MAX; - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - ValueIndex.prototype.makePost = function (indexValue, name) { - var valueNode = nodeFromJSON$1(indexValue); - return new NamedNode(name, valueNode); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - ValueIndex.prototype.toString = function () { - return '.value'; - }; - return ValueIndex; -}(Index)); -var VALUE_INDEX = new ValueIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!Path} indexPath - * @constructor - * @extends {Index} - */ -var PathIndex = /** @class */ (function (_super) { - __extends(PathIndex, _super); - function PathIndex(indexPath_) { - var _this = _super.call(this) || this; - _this.indexPath_ = indexPath_; - assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', "Can't create PathIndex with empty path or .priority key"); - return _this; - } - /** - * @param {!Node} snap - * @return {!Node} - * @protected - */ - PathIndex.prototype.extractChild = function (snap) { - return snap.getChild(this.indexPath_); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.isDefinedOn = function (node) { - return !node.getChild(this.indexPath_).isEmpty(); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.compare = function (a, b) { - var aChild = this.extractChild(a.node); - var bChild = this.extractChild(b.node); - var indexCmp = aChild.compareTo(bChild); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - PathIndex.prototype.makePost = function (indexValue, name) { - var valueNode = nodeFromJSON$1(indexValue); - var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); - return new NamedNode(name, node); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.maxPost = function () { - var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE$2); - return new NamedNode(MAX_NAME, node); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.toString = function () { - return this.indexPath_.slice().join('/'); - }; - return PathIndex; -}(Index)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class representing a firebase data snapshot. It wraps a SnapshotNode and - * surfaces the public methods (val, forEach, etc.) we want to expose. - */ -var DataSnapshot = /** @class */ (function () { - /** - * @param {!Node} node_ A SnapshotNode to wrap. - * @param {!Reference} ref_ The ref of the location this snapshot came from. - * @param {!Index} index_ The iteration order for this snapshot - */ - function DataSnapshot(node_, ref_, index_) { - this.node_ = node_; - this.ref_ = ref_; - this.index_ = index_; - } - /** - * Retrieves the snapshot contents as JSON. Returns null if the snapshot is - * empty. - * - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - DataSnapshot.prototype.val = function () { - validateArgCount('DataSnapshot.val', 0, 0, arguments.length); - return this.node_.val(); - }; - /** - * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting - * the entire node contents. - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - DataSnapshot.prototype.exportVal = function () { - validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); - return this.node_.val(true); - }; - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users - DataSnapshot.prototype.toJSON = function () { - // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content - validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); - return this.exportVal(); - }; - /** - * Returns whether the snapshot contains a non-null value. - * - * @return {boolean} Whether the snapshot contains a non-null value, or is empty. - */ - DataSnapshot.prototype.exists = function () { - validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); - return !this.node_.isEmpty(); - }; - /** - * Returns a DataSnapshot of the specified child node's contents. - * - * @param {!string} childPathString Path to a child. - * @return {!DataSnapshot} DataSnapshot for child node. - */ - DataSnapshot.prototype.child = function (childPathString) { - validateArgCount('DataSnapshot.child', 0, 1, arguments.length); - // Ensure the childPath is a string (can be a number) - childPathString = String(childPathString); - validatePathString('DataSnapshot.child', 1, childPathString, false); - var childPath = new Path(childPathString); - var childRef = this.ref_.child(childPath); - return new DataSnapshot(this.node_.getChild(childPath), childRef, PRIORITY_INDEX); - }; - /** - * Returns whether the snapshot contains a child at the specified path. - * - * @param {!string} childPathString Path to a child. - * @return {boolean} Whether the child exists. - */ - DataSnapshot.prototype.hasChild = function (childPathString) { - validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); - validatePathString('DataSnapshot.hasChild', 1, childPathString, false); - var childPath = new Path(childPathString); - return !this.node_.getChild(childPath).isEmpty(); - }; - /** - * Returns the priority of the object, or null if no priority was set. - * - * @return {string|number|null} The priority. - */ - DataSnapshot.prototype.getPriority = function () { - validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); - // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) - return this.node_.getPriority().val(); - }; - /** - * Iterates through child nodes and calls the specified action for each one. - * - * @param {function(!DataSnapshot)} action Callback function to be called - * for each child. - * @return {boolean} True if forEach was canceled by action returning true for - * one of the child nodes. - */ - DataSnapshot.prototype.forEach = function (action) { - var _this = this; - validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); - validateCallback('DataSnapshot.forEach', 1, action, false); - if (this.node_.isLeafNode()) - return false; - var childrenNode = this.node_; - // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... - return !!childrenNode.forEachChild(this.index_, function (key, node) { - return action(new DataSnapshot(node, _this.ref_.child(key), PRIORITY_INDEX)); - }); - }; - /** - * Returns whether this DataSnapshot has children. - * @return {boolean} True if the DataSnapshot contains 1 or more child nodes. - */ - DataSnapshot.prototype.hasChildren = function () { - validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); - if (this.node_.isLeafNode()) - return false; - else - return !this.node_.isEmpty(); - }; - Object.defineProperty(DataSnapshot.prototype, "key", { - get: function () { - return this.ref_.getKey(); - }, - enumerable: true, - configurable: true - }); - /** - * Returns the number of children for this DataSnapshot. - * @return {number} The number of children that this DataSnapshot contains. - */ - DataSnapshot.prototype.numChildren = function () { - validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); - return this.node_.numChildren(); - }; - /** - * @return {Reference} The Firebase reference for the location this snapshot's data came from. - */ - DataSnapshot.prototype.getRef = function () { - validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); - return this.ref_; - }; - Object.defineProperty(DataSnapshot.prototype, "ref", { - get: function () { - return this.getRef(); - }, - enumerable: true, - configurable: true - }); - return DataSnapshot; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Encapsulates the data needed to raise an event - * @implements {Event} - */ -var DataEvent = /** @class */ (function () { - /** - * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed - * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided - * @param {!DataSnapshot} snapshot The data backing the event - * @param {?string=} prevName Optional, the name of the previous child for child_* events. - */ - function DataEvent(eventType, eventRegistration, snapshot, prevName) { - this.eventType = eventType; - this.eventRegistration = eventRegistration; - this.snapshot = snapshot; - this.prevName = prevName; - } - /** - * @inheritDoc - */ - DataEvent.prototype.getPath = function () { - var ref = this.snapshot.getRef(); - if (this.eventType === 'value') { - return ref.path; - } - else { - return ref.getParent().path; - } - }; - /** - * @inheritDoc - */ - DataEvent.prototype.getEventType = function () { - return this.eventType; - }; - /** - * @inheritDoc - */ - DataEvent.prototype.getEventRunner = function () { - return this.eventRegistration.getEventRunner(this); - }; - /** - * @inheritDoc - */ - DataEvent.prototype.toString = function () { - return (this.getPath().toString() + - ':' + - this.eventType + - ':' + - stringify(this.snapshot.exportVal())); - }; - return DataEvent; -}()); -var CancelEvent = /** @class */ (function () { - /** - * @param {EventRegistration} eventRegistration - * @param {Error} error - * @param {!Path} path - */ - function CancelEvent(eventRegistration, error, path) { - this.eventRegistration = eventRegistration; - this.error = error; - this.path = path; - } - /** - * @inheritDoc - */ - CancelEvent.prototype.getPath = function () { - return this.path; - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.getEventType = function () { - return 'cancel'; - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.getEventRunner = function () { - return this.eventRegistration.getEventRunner(this); - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.toString = function () { - return this.path.toString() + ':cancel'; - }; - return CancelEvent; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Represents registration for 'value' events. - */ -var ValueEventRegistration = /** @class */ (function () { - /** - * @param {?function(!DataSnapshot)} callback_ - * @param {?function(Error)} cancelCallback_ - * @param {?Object} context_ - */ - function ValueEventRegistration(callback_, cancelCallback_, context_) { - this.callback_ = callback_; - this.cancelCallback_ = cancelCallback_; - this.context_ = context_; - } - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.respondsTo = function (eventType) { - return eventType === 'value'; - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.createEvent = function (change, query) { - var index = query.getQueryParams().getIndex(); - return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, query.getRef(), index)); - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.getEventRunner = function (eventData) { - var ctx = this.context_; - if (eventData.getEventType() === 'cancel') { - assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback'); - var cancelCB_1 = this.cancelCallback_; - return function () { - // We know that error exists, we checked above that this is a cancel event - cancelCB_1.call(ctx, eventData.error); - }; - } - else { - var cb_1 = this.callback_; - return function () { - cb_1.call(ctx, eventData.snapshot); - }; - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.createCancelEvent = function (error, path) { - if (this.cancelCallback_) { - return new CancelEvent(this, error, path); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.matches = function (other) { - if (!(other instanceof ValueEventRegistration)) { - return false; - } - else if (!other.callback_ || !this.callback_) { - // If no callback specified, we consider it to match any callback. - return true; - } - else { - return (other.callback_ === this.callback_ && other.context_ === this.context_); - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.hasAnyCallback = function () { - return this.callback_ !== null; - }; - return ValueEventRegistration; -}()); -/** - * Represents the registration of 1 or more child_xxx events. - * - * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you - * register a group of callbacks together in the future. - * - * @constructor - * @implements {EventRegistration} - */ -var ChildEventRegistration = /** @class */ (function () { - /** - * @param {?Object.} callbacks_ - * @param {?function(Error)} cancelCallback_ - * @param {Object=} context_ - */ - function ChildEventRegistration(callbacks_, cancelCallback_, context_) { - this.callbacks_ = callbacks_; - this.cancelCallback_ = cancelCallback_; - this.context_ = context_; - } - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.respondsTo = function (eventType) { - var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; - eventToCheck = - eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; - return contains(this.callbacks_, eventToCheck); - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.createCancelEvent = function (error, path) { - if (this.cancelCallback_) { - return new CancelEvent(this, error, path); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.createEvent = function (change, query) { - assert(change.childName != null, 'Child events should have a childName.'); - var ref = query.getRef().child(/** @type {!string} */ (change.childName)); - var index = query.getQueryParams().getIndex(); - return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, ref, index), change.prevName); - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.getEventRunner = function (eventData) { - var ctx = this.context_; - if (eventData.getEventType() === 'cancel') { - assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback'); - var cancelCB_2 = this.cancelCallback_; - return function () { - // We know that error exists, we checked above that this is a cancel event - cancelCB_2.call(ctx, eventData.error); - }; - } - else { - var cb_2 = this.callbacks_[eventData.eventType]; - return function () { - cb_2.call(ctx, eventData.snapshot, eventData.prevName); - }; - } - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.matches = function (other) { - if (other instanceof ChildEventRegistration) { - if (!this.callbacks_ || !other.callbacks_) { - return true; - } - else if (this.context_ === other.context_) { - var otherCount = getCount(other.callbacks_); - var thisCount = getCount(this.callbacks_); - if (otherCount === thisCount) { - // If count is 1, do an exact match on eventType, if either is defined but null, it's a match. - // If event types don't match, not a match - // If count is not 1, exact match across all - if (otherCount === 1) { - var otherKey /** @type {!string} */ = getAnyKey(other.callbacks_); - var thisKey /** @type {!string} */ = getAnyKey(this.callbacks_); - return (thisKey === otherKey && - (!other.callbacks_[otherKey] || - !this.callbacks_[thisKey] || - other.callbacks_[otherKey] === this.callbacks_[thisKey])); - } - else { - // Exact match on each key. - return every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; }); - } - } - } - } - return false; - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.hasAnyCallback = function () { - return this.callbacks_ !== null; - }; - return ChildEventRegistration; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __referenceConstructor; -/** - * A Query represents a filter to be applied to a firebase location. This object purely represents the - * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. - * - * Since every Firebase reference is a query, Firebase inherits from this object. - */ -var Query = /** @class */ (function () { - function Query(repo, path, queryParams_, orderByCalled_) { - this.repo = repo; - this.path = path; - this.queryParams_ = queryParams_; - this.orderByCalled_ = orderByCalled_; - } - Object.defineProperty(Query, "__referenceConstructor", { - get: function () { - assert(__referenceConstructor, 'Reference.ts has not been loaded'); - return __referenceConstructor; - }, - set: function (val) { - __referenceConstructor = val; - }, - enumerable: true, - configurable: true - }); - /** - * Validates start/end values for queries. - * @param {!QueryParams} params - * @private - */ - Query.validateQueryEndpoints_ = function (params) { - var startNode = null; - var endNode = null; - if (params.hasStart()) { - startNode = params.getIndexStartValue(); - } - if (params.hasEnd()) { - endNode = params.getIndexEndValue(); - } - if (params.getIndex() === KEY_INDEX) { - var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + - 'startAt(), endAt(), or equalTo().'; - var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' + - 'or equalTo() must be a string.'; - if (params.hasStart()) { - var startName = params.getIndexStartName(); - if (startName != MIN_NAME) { - throw new Error(tooManyArgsError); - } - else if (typeof startNode !== 'string') { - throw new Error(wrongArgTypeError); - } - } - if (params.hasEnd()) { - var endName = params.getIndexEndName(); - if (endName != MAX_NAME) { - throw new Error(tooManyArgsError); - } - else if (typeof endNode !== 'string') { - throw new Error(wrongArgTypeError); - } - } - } - else if (params.getIndex() === PRIORITY_INDEX) { - if ((startNode != null && !isValidPriority(startNode)) || - (endNode != null && !isValidPriority(endNode))) { - throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + - 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).'); - } - } - else { - assert(params.getIndex() instanceof PathIndex || - params.getIndex() === VALUE_INDEX, 'unknown index type.'); - if ((startNode != null && typeof startNode === 'object') || - (endNode != null && typeof endNode === 'object')) { - throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' + - 'an object.'); - } - } - }; - /** - * Validates that limit* has been called with the correct combination of parameters - * @param {!QueryParams} params - * @private - */ - Query.validateLimit_ = function (params) { - if (params.hasStart() && - params.hasEnd() && - params.hasLimit() && - !params.hasAnchoredLimit()) { - throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead."); - } - }; - /** - * Validates that no other order by call has been made - * @param {!string} fnName - * @private - */ - Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) { - if (this.orderByCalled_ === true) { - throw new Error(fnName + ": You can't combine multiple orderBy calls."); - } - }; - /** - * @return {!QueryParams} - */ - Query.prototype.getQueryParams = function () { - return this.queryParams_; - }; - /** - * @return {!Reference} - */ - Query.prototype.getRef = function () { - validateArgCount('Query.ref', 0, 0, arguments.length); - // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query. - // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this - // method gets called. - return new Query.__referenceConstructor(this.repo, this.path); - }; - /** - * @param {!string} eventType - * @param {!function(DataSnapshot, string=)} callback - * @param {(function(Error)|Object)=} cancelCallbackOrContext - * @param {Object=} context - * @return {!function(DataSnapshot, string=)} - */ - Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) { - validateArgCount('Query.on', 2, 4, arguments.length); - validateEventType('Query.on', 1, eventType, false); - validateCallback('Query.on', 2, callback, false); - var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); - if (eventType === 'value') { - this.onValueEvent(callback, ret.cancel, ret.context); - } - else { - var callbacks = {}; - callbacks[eventType] = callback; - this.onChildEvent(callbacks, ret.cancel, ret.context); - } - return callback; - }; - /** - * @param {!function(!DataSnapshot)} callback - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - Query.prototype.onValueEvent = function (callback, cancelCallback, context) { - var container = new ValueEventRegistration(callback, cancelCallback || null, context || null); - this.repo.addEventCallbackForQuery(this, container); - }; - /** - * @param {!Object.} callbacks - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) { - var container = new ChildEventRegistration(callbacks, cancelCallback, context); - this.repo.addEventCallbackForQuery(this, container); - }; - /** - * @param {string=} eventType - * @param {(function(!DataSnapshot, ?string=))=} callback - * @param {Object=} context - */ - Query.prototype.off = function (eventType, callback, context) { - validateArgCount('Query.off', 0, 3, arguments.length); - validateEventType('Query.off', 1, eventType, true); - validateCallback('Query.off', 2, callback, true); - validateContextObject('Query.off', 3, context, true); - var container = null; - var callbacks = null; - if (eventType === 'value') { - var valueCallback = callback || null; - container = new ValueEventRegistration(valueCallback, null, context || null); - } - else if (eventType) { - if (callback) { - callbacks = {}; - callbacks[eventType] = callback; - } - container = new ChildEventRegistration(callbacks, null, context || null); - } - this.repo.removeEventCallbackForQuery(this, container); - }; - /** - * Attaches a listener, waits for the first event, and then removes the listener - * @param {!string} eventType - * @param {!function(!DataSnapshot, string=)} userCallback - * @param cancelOrContext - * @param context - * @return {!firebase.Promise} - */ - Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) { - var _this = this; - validateArgCount('Query.once', 1, 4, arguments.length); - validateEventType('Query.once', 1, eventType, false); - validateCallback('Query.once', 2, userCallback, true); - var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context); - // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event) - // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change - // because the API currently expects callbacks will be called synchronously if the data is cached, but this is - // against the Promise specification. - var firstCall = true; - var deferred = new Deferred(); - // A dummy error handler in case a user wasn't expecting promises - deferred.promise.catch(function () { }); - var onceCallback = function (snapshot) { - // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON) - // triggers multiple events (e.g. child_added or child_changed). - if (firstCall) { - firstCall = false; - _this.off(eventType, onceCallback); - if (userCallback) { - userCallback.bind(ret.context)(snapshot); - } - deferred.resolve(snapshot); - } - }; - this.on(eventType, onceCallback, - /*cancel=*/ function (err) { - _this.off(eventType, onceCallback); - if (ret.cancel) - ret.cancel.bind(ret.context)(err); - deferred.reject(err); - }); - return deferred.promise; - }; - /** - * Set a limit and anchor it to the start of the window. - * @param {!number} limit - * @return {!Query} - */ - Query.prototype.limitToFirst = function (limit) { - validateArgCount('Query.limitToFirst', 1, 1, arguments.length); - if (typeof limit !== 'number' || - Math.floor(limit) !== limit || - limit <= 0) { - throw new Error('Query.limitToFirst: First argument must be a positive integer.'); - } - if (this.queryParams_.hasLimit()) { - throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' + - 'limitToFirst, or limitToLast).'); - } - return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_); - }; - /** - * Set a limit and anchor it to the end of the window. - * @param {!number} limit - * @return {!Query} - */ - Query.prototype.limitToLast = function (limit) { - validateArgCount('Query.limitToLast', 1, 1, arguments.length); - if (typeof limit !== 'number' || - Math.floor(limit) !== limit || - limit <= 0) { - throw new Error('Query.limitToLast: First argument must be a positive integer.'); - } - if (this.queryParams_.hasLimit()) { - throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' + - 'limitToFirst, or limitToLast).'); - } - return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_); - }; - /** - * Given a child path, return a new query ordered by the specified grandchild path. - * @param {!string} path - * @return {!Query} - */ - Query.prototype.orderByChild = function (path) { - validateArgCount('Query.orderByChild', 1, 1, arguments.length); - if (path === '$key') { - throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.'); - } - else if (path === '$priority') { - throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.'); - } - else if (path === '$value') { - throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.'); - } - validatePathString('Query.orderByChild', 1, path, false); - this.validateNoPreviousOrderByCall_('Query.orderByChild'); - var parsedPath = new Path(path); - if (parsedPath.isEmpty()) { - throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.'); - } - var index = new PathIndex(parsedPath); - var newParams = this.queryParams_.orderBy(index); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the KeyIndex - * @return {!Query} - */ - Query.prototype.orderByKey = function () { - validateArgCount('Query.orderByKey', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByKey'); - var newParams = this.queryParams_.orderBy(KEY_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the PriorityIndex - * @return {!Query} - */ - Query.prototype.orderByPriority = function () { - validateArgCount('Query.orderByPriority', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByPriority'); - var newParams = this.queryParams_.orderBy(PRIORITY_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the ValueIndex - * @return {!Query} - */ - Query.prototype.orderByValue = function () { - validateArgCount('Query.orderByValue', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByValue'); - var newParams = this.queryParams_.orderBy(VALUE_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - Query.prototype.startAt = function (value, name) { - if (value === void 0) { value = null; } - validateArgCount('Query.startAt', 0, 2, arguments.length); - validateFirebaseDataArg('Query.startAt', 1, value, this.path, true); - validateKey('Query.startAt', 2, name, true); - var newParams = this.queryParams_.startAt(value, name); - Query.validateLimit_(newParams); - Query.validateQueryEndpoints_(newParams); - if (this.queryParams_.hasStart()) { - throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' + - 'or equalTo).'); - } - // Calling with no params tells us to start at the beginning. - if (value === undefined) { - value = null; - name = null; - } - return new Query(this.repo, this.path, newParams, this.orderByCalled_); - }; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - Query.prototype.endAt = function (value, name) { - if (value === void 0) { value = null; } - validateArgCount('Query.endAt', 0, 2, arguments.length); - validateFirebaseDataArg('Query.endAt', 1, value, this.path, true); - validateKey('Query.endAt', 2, name, true); - var newParams = this.queryParams_.endAt(value, name); - Query.validateLimit_(newParams); - Query.validateQueryEndpoints_(newParams); - if (this.queryParams_.hasEnd()) { - throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' + - 'equalTo).'); - } - return new Query(this.repo, this.path, newParams, this.orderByCalled_); - }; - /** - * Load the selection of children with exactly the specified value, and, optionally, - * the specified name. - * @param {number|string|boolean|null} value - * @param {string=} name - * @return {!Query} - */ - Query.prototype.equalTo = function (value, name) { - validateArgCount('Query.equalTo', 1, 2, arguments.length); - validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false); - validateKey('Query.equalTo', 2, name, true); - if (this.queryParams_.hasStart()) { - throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' + - 'equalTo).'); - } - if (this.queryParams_.hasEnd()) { - throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' + - 'equalTo).'); - } - return this.startAt(value, name).endAt(value, name); - }; - /** - * @return {!string} URL for this location. - */ - Query.prototype.toString = function () { - validateArgCount('Query.toString', 0, 0, arguments.length); - return this.repo.toString() + this.path.toUrlEncodedString(); - }; - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users. - Query.prototype.toJSON = function () { - // An optional spacer argument is unnecessary for a string. - validateArgCount('Query.toJSON', 0, 1, arguments.length); - return this.toString(); - }; - /** - * An object representation of the query parameters used by this Query. - * @return {!Object} - */ - Query.prototype.queryObject = function () { - return this.queryParams_.getQueryObject(); - }; - /** - * @return {!string} - */ - Query.prototype.queryIdentifier = function () { - var obj = this.queryObject(); - var id = ObjectToUniqueKey(obj); - return id === '{}' ? 'default' : id; - }; - /** - * Return true if this query and the provided query are equivalent; otherwise, return false. - * @param {Query} other - * @return {boolean} - */ - Query.prototype.isEqual = function (other) { - validateArgCount('Query.isEqual', 1, 1, arguments.length); - if (!(other instanceof Query)) { - var error$$1 = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; - throw new Error(error$$1); - } - var sameRepo = this.repo === other.repo; - var samePath = this.path.equals(other.path); - var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier(); - return sameRepo && samePath && sameQueryIdentifier; - }; - /** - * Helper used by .on and .once to extract the context and or cancel arguments. - * @param {!string} fnName The function name (on or once) - * @param {(function(Error)|Object)=} cancelOrContext - * @param {Object=} context - * @return {{cancel: ?function(Error), context: ?Object}} - * @private - */ - Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) { - var ret = { cancel: null, context: null }; - if (cancelOrContext && context) { - ret.cancel = cancelOrContext; - validateCallback(fnName, 3, ret.cancel, true); - ret.context = context; - validateContextObject(fnName, 4, ret.context, true); - } - else if (cancelOrContext) { - // we have either a cancel callback or a context. - if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { - // it's a context! - ret.context = cancelOrContext; - } - else if (typeof cancelOrContext === 'function') { - ret.cancel = cancelOrContext; - } - else { - throw new Error(errorPrefix(fnName, 3, true) + - ' must either be a cancel callback or a context object.'); - } - } - return ret; - }; - Object.defineProperty(Query.prototype, "ref", { - get: function () { - return this.getRef(); - }, - enumerable: true, - configurable: true - }); - return Query; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Implements a set with a count of elements. - * - * @template K, V - */ -var CountedSet = /** @class */ (function () { - function CountedSet() { - this.set = {}; - } - /** - * @param {!K} item - * @param {V} val - */ - CountedSet.prototype.add = function (item, val) { - this.set[item] = val !== null ? val : true; - }; - /** - * @param {!K} key - * @return {boolean} - */ - CountedSet.prototype.contains = function (key) { - return contains(this.set, key); - }; - /** - * @param {!K} item - * @return {V} - */ - CountedSet.prototype.get = function (item) { - return this.contains(item) ? this.set[item] : undefined; - }; - /** - * @param {!K} item - */ - CountedSet.prototype.remove = function (item) { - delete this.set[item]; - }; - /** - * Deletes everything in the set - */ - CountedSet.prototype.clear = function () { - this.set = {}; - }; - /** - * True if there's nothing in the set - * @return {boolean} - */ - CountedSet.prototype.isEmpty = function () { - return isEmpty(this.set); - }; - /** - * @return {number} The number of items in the set - */ - CountedSet.prototype.count = function () { - return getCount(this.set); - }; - /** - * Run a function on each k,v pair in the set - * @param {function(K, V)} fn - */ - CountedSet.prototype.each = function (fn) { - forEach(this.set, function (k, v) { return fn(k, v); }); - }; - /** - * Mostly for debugging - * @return {Array.} The keys present in this CountedSet - */ - CountedSet.prototype.keys = function () { - var keys = []; - forEach(this.set, function (k) { - keys.push(k); - }); - return keys; - }; - return CountedSet; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Helper class to store a sparse set of snapshots. - * - * @constructor - */ -var SparseSnapshotTree = /** @class */ (function () { - function SparseSnapshotTree() { - /** - * @private - * @type {Node} - */ - this.value_ = null; - /** - * @private - * @type {CountedSet} - */ - this.children_ = null; - } - /** - * Gets the node stored at the given path if one exists. - * - * @param {!Path} path Path to look up snapshot for. - * @return {?Node} The retrieved node, or null. - */ - SparseSnapshotTree.prototype.find = function (path) { - if (this.value_ != null) { - return this.value_.getChild(path); - } - else if (!path.isEmpty() && this.children_ != null) { - var childKey = path.getFront(); - path = path.popFront(); - if (this.children_.contains(childKey)) { - var childTree = this.children_.get(childKey); - return childTree.find(path); - } - else { - return null; - } - } - else { - return null; - } - }; - /** - * Stores the given node at the specified path. If there is already a node - * at a shallower path, it merges the new data into that snapshot node. - * - * @param {!Path} path Path to look up snapshot for. - * @param {!Node} data The new data, or null. - */ - SparseSnapshotTree.prototype.remember = function (path, data) { - if (path.isEmpty()) { - this.value_ = data; - this.children_ = null; - } - else if (this.value_ !== null) { - this.value_ = this.value_.updateChild(path, data); - } - else { - if (this.children_ == null) { - this.children_ = new CountedSet(); - } - var childKey = path.getFront(); - if (!this.children_.contains(childKey)) { - this.children_.add(childKey, new SparseSnapshotTree()); - } - var child = this.children_.get(childKey); - path = path.popFront(); - child.remember(path, data); - } - }; - /** - * Purge the data at path from the cache. - * - * @param {!Path} path Path to look up snapshot for. - * @return {boolean} True if this node should now be removed. - */ - SparseSnapshotTree.prototype.forget = function (path) { - if (path.isEmpty()) { - this.value_ = null; - this.children_ = null; - return true; - } - else { - if (this.value_ !== null) { - if (this.value_.isLeafNode()) { - // We're trying to forget a node that doesn't exist - return false; - } - else { - var value = this.value_; - this.value_ = null; - var self_1 = this; - value.forEachChild(PRIORITY_INDEX, function (key, tree) { - self_1.remember(new Path(key), tree); - }); - return this.forget(path); - } - } - else if (this.children_ !== null) { - var childKey = path.getFront(); - path = path.popFront(); - if (this.children_.contains(childKey)) { - var safeToRemove = this.children_.get(childKey).forget(path); - if (safeToRemove) { - this.children_.remove(childKey); - } - } - if (this.children_.isEmpty()) { - this.children_ = null; - return true; - } - else { - return false; - } - } - else { - return true; - } - } - }; - /** - * Recursively iterates through all of the stored tree and calls the - * callback on each one. - * - * @param {!Path} prefixPath Path to look up node for. - * @param {!Function} func The function to invoke for each tree. - */ - SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) { - if (this.value_ !== null) { - func(prefixPath, this.value_); - } - else { - this.forEachChild(function (key, tree) { - var path = new Path(prefixPath.toString() + '/' + key); - tree.forEachTree(path, func); - }); - } - }; - /** - * Iterates through each immediate child and triggers the callback. - * - * @param {!Function} func The function to invoke for each child. - */ - SparseSnapshotTree.prototype.forEachChild = function (func) { - if (this.children_ !== null) { - this.children_.each(function (key, tree) { - func(key, tree); - }); - } - }; - return SparseSnapshotTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Generate placeholders for deferred values. - * @param {?Object} values - * @return {!Object} - */ -var generateWithValues = function (values) { - values = values || {}; - values['timestamp'] = values['timestamp'] || new Date().getTime(); - return values; -}; -/** - * Value to use when firing local events. When writing server values, fire - * local events with an approximate value, otherwise return value as-is. - * @param {(Object|string|number|boolean)} value - * @param {!Object} serverValues - * @return {!(string|number|boolean)} - */ -var resolveDeferredValue = function (value, serverValues) { - if (!value || typeof value !== 'object') { - return value; - } - else { - assert('.sv' in value, 'Unexpected leaf node or priority contents'); - return serverValues[value['.sv']]; - } -}; -/** - * Recursively replace all deferred values and priorities in the tree with the - * specified generated replacement values. - * @param {!SparseSnapshotTree} tree - * @param {!Object} serverValues - * @return {!SparseSnapshotTree} - */ -var resolveDeferredValueTree = function (tree, serverValues) { - var resolvedTree = new SparseSnapshotTree(); - tree.forEachTree(new Path(''), function (path, node) { - resolvedTree.remember(path, resolveDeferredValueSnapshot(node, serverValues)); - }); - return resolvedTree; -}; -/** - * Recursively replace all deferred values and priorities in the node with the - * specified generated replacement values. If there are no server values in the node, - * it'll be returned as-is. - * @param {!Node} node - * @param {!Object} serverValues - * @return {!Node} - */ -var resolveDeferredValueSnapshot = function (node, serverValues) { - var rawPri = node.getPriority().val(); - var priority = resolveDeferredValue(rawPri, serverValues); - var newNode; - if (node.isLeafNode()) { - var leafNode = node; - var value = resolveDeferredValue(leafNode.getValue(), serverValues); - if (value !== leafNode.getValue() || - priority !== leafNode.getPriority().val()) { - return new LeafNode(value, nodeFromJSON$1(priority)); - } - else { - return node; - } - } - else { - var childrenNode = node; - newNode = childrenNode; - if (priority !== childrenNode.getPriority().val()) { - newNode = newNode.updatePriority(new LeafNode(priority)); - } - childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - var newChildNode = resolveDeferredValueSnapshot(childNode, serverValues); - if (newChildNode !== childNode) { - newNode = newNode.updateImmediateChild(childName, newChildNode); - } - }); - return newNode; - } -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @enum - */ -var OperationType; -(function (OperationType) { - OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; - OperationType[OperationType["MERGE"] = 1] = "MERGE"; - OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; - OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; -})(OperationType || (OperationType = {})); -/** - * @param {boolean} fromUser - * @param {boolean} fromServer - * @param {?string} queryId - * @param {boolean} tagged - * @constructor - */ -var OperationSource = /** @class */ (function () { - function OperationSource(fromUser, fromServer, queryId, tagged) { - this.fromUser = fromUser; - this.fromServer = fromServer; - this.queryId = queryId; - this.tagged = tagged; - assert(!tagged || fromServer, 'Tagged queries must be from server.'); - } - /** - * @const - * @type {!OperationSource} - */ - OperationSource.User = new OperationSource( - /*fromUser=*/ true, false, null, - /*tagged=*/ false); - /** - * @const - * @type {!OperationSource} - */ - OperationSource.Server = new OperationSource(false, - /*fromServer=*/ true, null, - /*tagged=*/ false); - /** - * @param {string} queryId - * @return {!OperationSource} - */ - OperationSource.forServerTaggedQuery = function (queryId) { - return new OperationSource(false, - /*fromServer=*/ true, queryId, - /*tagged=*/ true); - }; - return OperationSource; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var AckUserWrite = /** @class */ (function () { - /** - * - * @param {!Path} path - * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap. - * @param {!boolean} revert - */ - function AckUserWrite( - /**@inheritDoc */ path, - /**@inheritDoc */ affectedTree, - /**@inheritDoc */ revert) { - this.path = path; - this.affectedTree = affectedTree; - this.revert = revert; - /** @inheritDoc */ - this.type = OperationType.ACK_USER_WRITE; - /** @inheritDoc */ - this.source = OperationSource.User; - } - /** - * @inheritDoc - */ - AckUserWrite.prototype.operationForChild = function (childName) { - if (!this.path.isEmpty()) { - assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.'); - return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert); - } - else if (this.affectedTree.value != null) { - assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); - // All child locations are affected as well; just return same operation. - return this; - } - else { - var childTree = this.affectedTree.subtree(new Path(childName)); - return new AckUserWrite(Path.Empty, childTree, this.revert); - } - }; - return AckUserWrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var emptyChildrenSingleton; -/** - * Singleton empty children collection. - * - * @const - * @type {!SortedMap.>} - */ -var EmptyChildren = function () { - if (!emptyChildrenSingleton) { - emptyChildrenSingleton = new SortedMap(stringCompare); - } - return emptyChildrenSingleton; -}; -/** - * A tree with immutable elements. - */ -var ImmutableTree = /** @class */ (function () { - /** - * @template T - * @param {?T} value - * @param {SortedMap.>=} children - */ - function ImmutableTree(value, children) { - if (children === void 0) { children = EmptyChildren(); } - this.value = value; - this.children = children; - } - /** - * @template T - * @param {!Object.} obj - * @return {!ImmutableTree.} - */ - ImmutableTree.fromObject = function (obj) { - var tree = ImmutableTree.Empty; - forEach(obj, function (childPath, childSnap) { - tree = tree.set(new Path(childPath), childSnap); - }); - return tree; - }; - /** - * True if the value is empty and there are no children - * @return {boolean} - */ - ImmutableTree.prototype.isEmpty = function () { - return this.value === null && this.children.isEmpty(); - }; - /** - * Given a path and predicate, return the first node and the path to that node - * where the predicate returns true. - * - * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects - * on the way back out, it may be better to pass down a pathSoFar obj. - * - * @param {!Path} relativePath The remainder of the path - * @param {function(T):boolean} predicate The predicate to satisfy to return a - * node - * @return {?{path:!Path, value:!T}} - */ - ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) { - if (this.value != null && predicate(this.value)) { - return { path: Path.Empty, value: this.value }; - } - else { - if (relativePath.isEmpty()) { - return null; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child !== null) { - var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate); - if (childExistingPathAndValue != null) { - var fullPath = new Path(front).child(childExistingPathAndValue.path); - return { path: fullPath, value: childExistingPathAndValue.value }; - } - else { - return null; - } - } - else { - return null; - } - } - } - }; - /** - * Find, if it exists, the shortest subpath of the given path that points a defined - * value in the tree - * @param {!Path} relativePath - * @return {?{path: !Path, value: !T}} - */ - ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) { - return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; }); - }; - /** - * @param {!Path} relativePath - * @return {!ImmutableTree.} The subtree at the given path - */ - ImmutableTree.prototype.subtree = function (relativePath) { - if (relativePath.isEmpty()) { - return this; - } - else { - var front = relativePath.getFront(); - var childTree = this.children.get(front); - if (childTree !== null) { - return childTree.subtree(relativePath.popFront()); - } - else { - return ImmutableTree.Empty; - } - } - }; - /** - * Sets a value at the specified path. - * - * @param {!Path} relativePath Path to set value at. - * @param {?T} toSet Value to set. - * @return {!ImmutableTree.} Resulting tree. - */ - ImmutableTree.prototype.set = function (relativePath, toSet) { - if (relativePath.isEmpty()) { - return new ImmutableTree(toSet, this.children); - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front) || ImmutableTree.Empty; - var newChild = child.set(relativePath.popFront(), toSet); - var newChildren = this.children.insert(front, newChild); - return new ImmutableTree(this.value, newChildren); - } - }; - /** - * Removes the value at the specified path. - * - * @param {!Path} relativePath Path to value to remove. - * @return {!ImmutableTree.} Resulting tree. - */ - ImmutableTree.prototype.remove = function (relativePath) { - if (relativePath.isEmpty()) { - if (this.children.isEmpty()) { - return ImmutableTree.Empty; - } - else { - return new ImmutableTree(null, this.children); - } - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child) { - var newChild = child.remove(relativePath.popFront()); - var newChildren = void 0; - if (newChild.isEmpty()) { - newChildren = this.children.remove(front); - } - else { - newChildren = this.children.insert(front, newChild); - } - if (this.value === null && newChildren.isEmpty()) { - return ImmutableTree.Empty; - } - else { - return new ImmutableTree(this.value, newChildren); - } - } - else { - return this; - } - } - }; - /** - * Gets a value from the tree. - * - * @param {!Path} relativePath Path to get value for. - * @return {?T} Value at path, or null. - */ - ImmutableTree.prototype.get = function (relativePath) { - if (relativePath.isEmpty()) { - return this.value; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child) { - return child.get(relativePath.popFront()); - } - else { - return null; - } - } - }; - /** - * Replace the subtree at the specified path with the given new tree. - * - * @param {!Path} relativePath Path to replace subtree for. - * @param {!ImmutableTree} newTree New tree. - * @return {!ImmutableTree} Resulting tree. - */ - ImmutableTree.prototype.setTree = function (relativePath, newTree) { - if (relativePath.isEmpty()) { - return newTree; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front) || ImmutableTree.Empty; - var newChild = child.setTree(relativePath.popFront(), newTree); - var newChildren = void 0; - if (newChild.isEmpty()) { - newChildren = this.children.remove(front); - } - else { - newChildren = this.children.insert(front, newChild); - } - return new ImmutableTree(this.value, newChildren); - } - }; - /** - * Performs a depth first fold on this tree. Transforms a tree into a single - * value, given a function that operates on the path to a node, an optional - * current value, and a map of child names to folded subtrees - * @template V - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - */ - ImmutableTree.prototype.fold = function (fn) { - return this.fold_(Path.Empty, fn); - }; - /** - * Recursive helper for public-facing fold() method - * @template V - * @param {!Path} pathSoFar - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - * @private - */ - ImmutableTree.prototype.fold_ = function (pathSoFar, fn) { - var accum = {}; - this.children.inorderTraversal(function (childKey, childTree) { - accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn); - }); - return fn(pathSoFar, this.value, accum); - }; - /** - * Find the first matching value on the given path. Return the result of applying f to it. - * @template V - * @param {!Path} path - * @param {!function(!Path, !T):?V} f - * @return {?V} - */ - ImmutableTree.prototype.findOnPath = function (path, f) { - return this.findOnPath_(path, Path.Empty, f); - }; - ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) { - var result = this.value ? f(pathSoFar, this.value) : false; - if (result) { - return result; - } - else { - if (pathToFollow.isEmpty()) { - return null; - } - else { - var front = pathToFollow.getFront(); - var nextChild = this.children.get(front); - if (nextChild) { - return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f); - } - else { - return null; - } - } - } - }; - /** - * - * @param {!Path} path - * @param {!function(!Path, !T)} f - * @returns {!ImmutableTree.} - */ - ImmutableTree.prototype.foreachOnPath = function (path, f) { - return this.foreachOnPath_(path, Path.Empty, f); - }; - ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) { - if (pathToFollow.isEmpty()) { - return this; - } - else { - if (this.value) { - f(currentRelativePath, this.value); - } - var front = pathToFollow.getFront(); - var nextChild = this.children.get(front); - if (nextChild) { - return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f); - } - else { - return ImmutableTree.Empty; - } - } - }; - /** - * Calls the given function for each node in the tree that has a value. - * - * @param {function(!Path, !T)} f A function to be called with - * the path from the root of the tree to a node, and the value at that node. - * Called in depth-first order. - */ - ImmutableTree.prototype.foreach = function (f) { - this.foreach_(Path.Empty, f); - }; - ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) { - this.children.inorderTraversal(function (childName, childTree) { - childTree.foreach_(currentRelativePath.child(childName), f); - }); - if (this.value) { - f(currentRelativePath, this.value); - } - }; - /** - * - * @param {function(string, !T)} f - */ - ImmutableTree.prototype.foreachChild = function (f) { - this.children.inorderTraversal(function (childName, childTree) { - if (childTree.value) { - f(childName, childTree.value); - } - }); - }; - ImmutableTree.Empty = new ImmutableTree(null); - return ImmutableTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @constructor - * @implements {Operation} - */ -var ListenComplete = /** @class */ (function () { - function ListenComplete(source, path) { - this.source = source; - this.path = path; - /** @inheritDoc */ - this.type = OperationType.LISTEN_COMPLETE; - } - ListenComplete.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - return new ListenComplete(this.source, Path.Empty); - } - else { - return new ListenComplete(this.source, this.path.popFront()); - } - }; - return ListenComplete; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!Node} snap - * @constructor - * @implements {Operation} - */ -var Overwrite = /** @class */ (function () { - function Overwrite(source, path, snap) { - this.source = source; - this.path = path; - this.snap = snap; - /** @inheritDoc */ - this.type = OperationType.OVERWRITE; - } - Overwrite.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - return new Overwrite(this.source, Path.Empty, this.snap.getImmediateChild(childName)); - } - else { - return new Overwrite(this.source, this.path.popFront(), this.snap); - } - }; - return Overwrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!ImmutableTree.} children - * @constructor - * @implements {Operation} - */ -var Merge = /** @class */ (function () { - function Merge( - /**@inheritDoc */ source, - /**@inheritDoc */ path, - /**@inheritDoc */ children) { - this.source = source; - this.path = path; - this.children = children; - /** @inheritDoc */ - this.type = OperationType.MERGE; - } - /** - * @inheritDoc - */ - Merge.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - var childTree = this.children.subtree(new Path(childName)); - if (childTree.isEmpty()) { - // This child is unaffected - return null; - } - else if (childTree.value) { - // We have a snapshot for the child in question. This becomes an overwrite of the child. - return new Overwrite(this.source, Path.Empty, childTree.value); - } - else { - // This is a merge at a deeper level - return new Merge(this.source, Path.Empty, childTree); - } - } - else { - assert(this.path.getFront() === childName, "Can't get a merge for a child not on the path of the operation"); - return new Merge(this.source, this.path.popFront(), this.children); - } - }; - /** - * @inheritDoc - */ - Merge.prototype.toString = function () { - return ('Operation(' + - this.path + - ': ' + - this.source.toString() + - ' merge: ' + - this.children.toString() + - ')'); - }; - return Merge; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully - * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. - * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks - * whether a node potentially had children removed due to a filter. - */ -var CacheNode = /** @class */ (function () { - /** - * @param {!Node} node_ - * @param {boolean} fullyInitialized_ - * @param {boolean} filtered_ - */ - function CacheNode(node_, fullyInitialized_, filtered_) { - this.node_ = node_; - this.fullyInitialized_ = fullyInitialized_; - this.filtered_ = filtered_; - } - /** - * Returns whether this node was fully initialized with either server data or a complete overwrite by the client - * @return {boolean} - */ - CacheNode.prototype.isFullyInitialized = function () { - return this.fullyInitialized_; - }; - /** - * Returns whether this node is potentially missing children due to a filter applied to the node - * @return {boolean} - */ - CacheNode.prototype.isFiltered = function () { - return this.filtered_; - }; - /** - * @param {!Path} path - * @return {boolean} - */ - CacheNode.prototype.isCompleteForPath = function (path) { - if (path.isEmpty()) { - return this.isFullyInitialized() && !this.filtered_; - } - var childKey = path.getFront(); - return this.isCompleteForChild(childKey); - }; - /** - * @param {!string} key - * @return {boolean} - */ - CacheNode.prototype.isCompleteForChild = function (key) { - return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); - }; - /** - * @return {!Node} - */ - CacheNode.prototype.getNode = function () { - return this.node_; - }; - return CacheNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Stores the data we have cached for a view. - * - * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). - * - * @constructor - */ -var ViewCache = /** @class */ (function () { - /** - * - * @param {!CacheNode} eventCache_ - * @param {!CacheNode} serverCache_ - */ - function ViewCache(eventCache_, serverCache_) { - this.eventCache_ = eventCache_; - this.serverCache_ = serverCache_; - } - /** - * @param {!Node} eventSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) { - return new ViewCache(new CacheNode(eventSnap, complete, filtered), this.serverCache_); - }; - /** - * @param {!Node} serverSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) { - return new ViewCache(this.eventCache_, new CacheNode(serverSnap, complete, filtered)); - }; - /** - * @return {!CacheNode} - */ - ViewCache.prototype.getEventCache = function () { - return this.eventCache_; - }; - /** - * @return {?Node} - */ - ViewCache.prototype.getCompleteEventSnap = function () { - return this.eventCache_.isFullyInitialized() - ? this.eventCache_.getNode() - : null; - }; - /** - * @return {!CacheNode} - */ - ViewCache.prototype.getServerCache = function () { - return this.serverCache_; - }; - /** - * @return {?Node} - */ - ViewCache.prototype.getCompleteServerSnap = function () { - return this.serverCache_.isFullyInitialized() - ? this.serverCache_.getNode() - : null; - }; - /** - * @const - * @type {ViewCache} - */ - ViewCache.Empty = new ViewCache(new CacheNode(ChildrenNode.EMPTY_NODE, - /*fullyInitialized=*/ false, - /*filtered=*/ false), new CacheNode(ChildrenNode.EMPTY_NODE, - /*fullyInitialized=*/ false, - /*filtered=*/ false)); - return ViewCache; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @struct - * @param {!string} type The event type - * @param {!Node} snapshotNode The data - * @param {string=} childName The name for this child, if it's a child event - * @param {Node=} oldSnap Used for intermediate processing of child changed events - * @param {string=} prevName The name for the previous child, if applicable - */ -var Change = /** @class */ (function () { - function Change(type, snapshotNode, childName, oldSnap, prevName) { - this.type = type; - this.snapshotNode = snapshotNode; - this.childName = childName; - this.oldSnap = oldSnap; - this.prevName = prevName; - } - /** - * @param {!Node} snapshot - * @return {!Change} - */ - Change.valueChange = function (snapshot) { - return new Change(Change.VALUE, snapshot); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childAddedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_ADDED, snapshot, childKey); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childRemovedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_REMOVED, snapshot, childKey); - }; - /** - * @param {string} childKey - * @param {!Node} newSnapshot - * @param {!Node} oldSnapshot - * @return {!Change} - */ - Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) { - return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childMovedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_MOVED, snapshot, childKey); - }; - //event types - /** Event type for a child added */ - Change.CHILD_ADDED = 'child_added'; - /** Event type for a child removed */ - Change.CHILD_REMOVED = 'child_removed'; - /** Event type for a child changed */ - Change.CHILD_CHANGED = 'child_changed'; - /** Event type for a child moved */ - Change.CHILD_MOVED = 'child_moved'; - /** Event type for a value change */ - Change.VALUE = 'value'; - return Change; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Doesn't really filter nodes but applies an index to the node and keeps track of any changes - * - * @constructor - * @implements {NodeFilter} - * @param {!Index} index - */ -var IndexedFilter = /** @class */ (function () { - function IndexedFilter(index_) { - this.index_ = index_; - } - IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); - var oldChild = snap.getImmediateChild(key); - // Check if anything actually changed. - if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { - // There's an edge case where a child can enter or leave the view because affectedPath was set to null. - // In this case, affectedPath will appear null in both the old and new snapshots. So we need - // to avoid treating these cases as "nothing changed." - if (oldChild.isEmpty() == newChild.isEmpty()) { - // Nothing changed. - // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. - //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); - return snap; - } - } - if (optChangeAccumulator != null) { - if (newChild.isEmpty()) { - if (snap.hasChild(key)) { - optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, oldChild)); - } - else { - assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); - } - } - else if (oldChild.isEmpty()) { - optChangeAccumulator.trackChildChange(Change.childAddedChange(key, newChild)); - } - else { - optChangeAccumulator.trackChildChange(Change.childChangedChange(key, newChild, oldChild)); - } - } - if (snap.isLeafNode() && newChild.isEmpty()) { - return snap; - } - else { - // Make sure the node is indexed - return snap.updateImmediateChild(key, newChild).withIndex(this.index_); - } - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - if (optChangeAccumulator != null) { - if (!oldSnap.isLeafNode()) { - oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (!newSnap.hasChild(key)) { - optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, childNode)); - } - }); - } - if (!newSnap.isLeafNode()) { - newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (oldSnap.hasChild(key)) { - var oldChild = oldSnap.getImmediateChild(key); - if (!oldChild.equals(childNode)) { - optChangeAccumulator.trackChildChange(Change.childChangedChange(key, childNode, oldChild)); - } - } - else { - optChangeAccumulator.trackChildChange(Change.childAddedChange(key, childNode)); - } - }); - } - } - return newSnap.withIndex(this.index_); - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - if (oldSnap.isEmpty()) { - return ChildrenNode.EMPTY_NODE; - } - else { - return oldSnap.updatePriority(newPriority); - } - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.filtersNodes = function () { - return false; - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.getIndexedFilter = function () { - return this; - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.getIndex = function () { - return this.index_; - }; - return IndexedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - */ -var ChildChangeAccumulator = /** @class */ (function () { - function ChildChangeAccumulator() { - this.changeMap_ = {}; - } - /** - * @param {!Change} change - */ - ChildChangeAccumulator.prototype.trackChildChange = function (change) { - var type = change.type; - var childKey /** @type {!string} */ = change.childName; - assert(type == Change.CHILD_ADDED || - type == Change.CHILD_CHANGED || - type == Change.CHILD_REMOVED, 'Only child changes supported for tracking'); - assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); - var oldChange = safeGet(this.changeMap_, childKey); - if (oldChange) { - var oldType = oldChange.type; - if (type == Change.CHILD_ADDED && oldType == Change.CHILD_REMOVED) { - this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode); - } - else if (type == Change.CHILD_REMOVED && - oldType == Change.CHILD_ADDED) { - delete this.changeMap_[childKey]; - } - else if (type == Change.CHILD_REMOVED && - oldType == Change.CHILD_CHANGED) { - this.changeMap_[childKey] = Change.childRemovedChange(childKey, oldChange.oldSnap); - } - else if (type == Change.CHILD_CHANGED && - oldType == Change.CHILD_ADDED) { - this.changeMap_[childKey] = Change.childAddedChange(childKey, change.snapshotNode); - } - else if (type == Change.CHILD_CHANGED && - oldType == Change.CHILD_CHANGED) { - this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap); - } - else { - throw assertionError('Illegal combination of changes: ' + - change + - ' occurred after ' + - oldChange); - } - } - else { - this.changeMap_[childKey] = change; - } - }; - /** - * @return {!Array.} - */ - ChildChangeAccumulator.prototype.getChanges = function () { - return getValues(this.changeMap_); - }; - return ChildChangeAccumulator; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An implementation of CompleteChildSource that never returns any additional children - * - * @private - * @constructor - * @implements CompleteChildSource - */ -var NoCompleteChildSource_ = /** @class */ (function () { - function NoCompleteChildSource_() { - } - /** - * @inheritDoc - */ - NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) { - return null; - }; - /** - * @inheritDoc - */ - NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) { - return null; - }; - return NoCompleteChildSource_; -}()); -/** - * Singleton instance. - * @const - * @type {!CompleteChildSource} - */ -var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); -/** - * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or - * old event caches available to calculate complete children. - * - * - * @implements CompleteChildSource - */ -var WriteTreeCompleteChildSource = /** @class */ (function () { - /** - * @param {!WriteTreeRef} writes_ - * @param {!ViewCache} viewCache_ - * @param {?Node} optCompleteServerCache_ - */ - function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) { - if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; } - this.writes_ = writes_; - this.viewCache_ = viewCache_; - this.optCompleteServerCache_ = optCompleteServerCache_; - } - /** - * @inheritDoc - */ - WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) { - var node = this.viewCache_.getEventCache(); - if (node.isCompleteForChild(childKey)) { - return node.getNode().getImmediateChild(childKey); - } - else { - var serverNode = this.optCompleteServerCache_ != null - ? new CacheNode(this.optCompleteServerCache_, true, false) - : this.viewCache_.getServerCache(); - return this.writes_.calcCompleteChild(childKey, serverNode); - } - }; - /** - * @inheritDoc - */ - WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) { - var completeServerData = this.optCompleteServerCache_ != null - ? this.optCompleteServerCache_ - : this.viewCache_.getCompleteServerSnap(); - var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index); - if (nodes.length === 0) { - return null; - } - else { - return nodes[0]; - } - }; - return WriteTreeCompleteChildSource; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @struct - */ -var ProcessorResult = /** @class */ (function () { - /** - * @param {!ViewCache} viewCache - * @param {!Array.} changes - */ - function ProcessorResult(viewCache, changes) { - this.viewCache = viewCache; - this.changes = changes; - } - return ProcessorResult; -}()); -/** - * @constructor - */ -var ViewProcessor = /** @class */ (function () { - /** - * @param {!NodeFilter} filter_ - */ - function ViewProcessor(filter_) { - this.filter_ = filter_; - } - /** - * @param {!ViewCache} viewCache - */ - ViewProcessor.prototype.assertIndexed = function (viewCache) { - assert(viewCache - .getEventCache() - .getNode() - .isIndexed(this.filter_.getIndex()), 'Event snap not indexed'); - assert(viewCache - .getServerCache() - .getNode() - .isIndexed(this.filter_.getIndex()), 'Server snap not indexed'); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @return {!ProcessorResult} - */ - ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) { - var accumulator = new ChildChangeAccumulator(); - var newViewCache, filterServerNode; - if (operation.type === OperationType.OVERWRITE) { - var overwrite = operation; - if (overwrite.source.fromUser) { - newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); - } - else { - assert(overwrite.source.fromServer, 'Unknown source.'); - // We filter the node if it's a tagged update or the node has been previously filtered and the - // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered - // again - filterServerNode = - overwrite.source.tagged || - (oldViewCache.getServerCache().isFiltered() && - !overwrite.path.isEmpty()); - newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); - } - } - else if (operation.type === OperationType.MERGE) { - var merge = operation; - if (merge.source.fromUser) { - newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); - } - else { - assert(merge.source.fromServer, 'Unknown source.'); - // We filter the node if it's a tagged update or the node has been previously filtered - filterServerNode = - merge.source.tagged || oldViewCache.getServerCache().isFiltered(); - newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); - } - } - else if (operation.type === OperationType.ACK_USER_WRITE) { - var ackUserWrite = operation; - if (!ackUserWrite.revert) { - newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); - } - else { - newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); - } - } - else if (operation.type === OperationType.LISTEN_COMPLETE) { - newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator); - } - else { - throw assertionError('Unknown operation type: ' + operation.type); - } - var changes = accumulator.getChanges(); - ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes); - return new ProcessorResult(newViewCache, changes); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!ViewCache} newViewCache - * @param {!Array.} accumulator - * @private - */ - ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) { - var eventSnap = newViewCache.getEventCache(); - if (eventSnap.isFullyInitialized()) { - var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); - var oldCompleteSnap = oldViewCache.getCompleteEventSnap(); - if (accumulator.length > 0 || - !oldViewCache.getEventCache().isFullyInitialized() || - (isLeafOrEmpty && - !eventSnap - .getNode() - .equals(/** @type {!Node} */ (oldCompleteSnap))) || - !eventSnap - .getNode() - .getPriority() - .equals(oldCompleteSnap.getPriority())) { - accumulator.push(Change.valueChange( - /** @type {!Node} */ newViewCache.getCompleteEventSnap())); - } - } - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} changePath - * @param {!WriteTreeRef} writesCache - * @param {!CompleteChildSource} source - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) { - var oldEventSnap = viewCache.getEventCache(); - if (writesCache.shadowingWrite(changePath) != null) { - // we have a shadowing write, ignore changes - return viewCache; - } - else { - var newEventCache = void 0, serverNode = void 0; - if (changePath.isEmpty()) { - // TODO: figure out how this plays with "sliding ack windows" - assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data'); - if (viewCache.getServerCache().isFiltered()) { - // We need to special case this, because we need to only apply writes to complete children, or - // we might end up raising events for incomplete children. If the server data is filtered deep - // writes cannot be guaranteed to be complete - var serverCache = viewCache.getCompleteServerSnap(); - var completeChildren = serverCache instanceof ChildrenNode - ? serverCache - : ChildrenNode.EMPTY_NODE; - var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren); - newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator); - } - else { - var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator); - } - } - else { - var childKey = changePath.getFront(); - if (childKey == '.priority') { - assert(changePath.getLength() == 1, "Can't have a priority with additional path components"); - var oldEventNode = oldEventSnap.getNode(); - serverNode = viewCache.getServerCache().getNode(); - // we might have overwrites for this priority - var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode); - if (updatedPriority != null) { - newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority); - } - else { - // priority didn't change, keep old node - newEventCache = oldEventSnap.getNode(); - } - } - else { - var childChangePath = changePath.popFront(); - // update child - var newEventChild = void 0; - if (oldEventSnap.isCompleteForChild(childKey)) { - serverNode = viewCache.getServerCache().getNode(); - var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode); - if (eventChildUpdate != null) { - newEventChild = oldEventSnap - .getNode() - .getImmediateChild(childKey) - .updateChild(childChangePath, eventChildUpdate); - } - else { - // Nothing changed, just keep the old child - newEventChild = oldEventSnap - .getNode() - .getImmediateChild(childKey); - } - } - else { - newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache()); - } - if (newEventChild != null) { - newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); - } - else { - // no complete child available or no change - newEventCache = oldEventSnap.getNode(); - } - } - } - return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes()); - } - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { - var oldServerSnap = oldViewCache.getServerCache(); - var newServerCache; - var serverFilter = filterServerNode - ? this.filter_ - : this.filter_.getIndexedFilter(); - if (changePath.isEmpty()) { - newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); - } - else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { - // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update - var newServerNode = oldServerSnap - .getNode() - .updateChild(changePath, changedSnap); - newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); - } - else { - var childKey = changePath.getFront(); - if (!oldServerSnap.isCompleteForPath(changePath) && - changePath.getLength() > 1) { - // We don't update incomplete nodes with updates intended for other listeners - return oldViewCache; - } - var childChangePath = changePath.popFront(); - var childNode = oldServerSnap.getNode().getImmediateChild(childKey); - var newChildNode = childNode.updateChild(childChangePath, changedSnap); - if (childKey == '.priority') { - newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); - } - else { - newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); - } - } - var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes()); - var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); - return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { - var oldEventSnap = oldViewCache.getEventCache(); - var newViewCache, newEventCache; - var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); - if (changePath.isEmpty()) { - newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator); - newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes()); - } - else { - var childKey = changePath.getFront(); - if (childKey === '.priority') { - newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap); - newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); - } - else { - var childChangePath = changePath.popFront(); - var oldChild = oldEventSnap.getNode().getImmediateChild(childKey); - var newChild = void 0; - if (childChangePath.isEmpty()) { - // Child overwrite, we can replace the child - newChild = changedSnap; - } - else { - var childNode = source.getCompleteChild(childKey); - if (childNode != null) { - if (childChangePath.getBack() === '.priority' && - childNode.getChild(childChangePath.parent()).isEmpty()) { - // This is a priority update on an empty node. If this node exists on the server, the - // server will send down the priority in the update, so ignore for now - newChild = childNode; - } - else { - newChild = childNode.updateChild(childChangePath, changedSnap); - } - } - else { - // There is no complete child node available - newChild = ChildrenNode.EMPTY_NODE; - } - } - if (!oldChild.equals(newChild)) { - var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); - newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes()); - } - else { - newViewCache = oldViewCache; - } - } - } - return newViewCache; - }; - /** - * @param {!ViewCache} viewCache - * @param {string} childKey - * @return {boolean} - * @private - */ - ViewProcessor.cacheHasChild_ = function (viewCache, childKey) { - return viewCache.getEventCache().isCompleteForChild(childKey); - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) { - var _this = this; - // HACK: In the case of a limit query, there may be some changes that bump things out of the - // window leaving room for new items. It's important we process these changes first, so we - // iterate the changes twice, first processing any that affect items currently in view. - // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server - // and event snap. I'm not sure if this will result in edge cases when a child is in one but - // not the other. - var curViewCache = viewCache; - changedChildren.foreach(function (relativePath, childNode) { - var writePath = path.child(relativePath); - if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) { - curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator); - } - }); - changedChildren.foreach(function (relativePath, childNode) { - var writePath = path.child(relativePath); - if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) { - curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator); - } - }); - return curViewCache; - }; - /** - * @param {!Node} node - * @param {ImmutableTree.} merge - * @return {!Node} - * @private - */ - ViewProcessor.prototype.applyMerge_ = function (node, merge) { - merge.foreach(function (relativePath, childNode) { - node = node.updateChild(relativePath, childNode); - }); - return node; - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { - var _this = this; - // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and - // wait for the complete data update coming soon. - if (viewCache - .getServerCache() - .getNode() - .isEmpty() && - !viewCache.getServerCache().isFullyInitialized()) { - return viewCache; - } - // HACK: In the case of a limit query, there may be some changes that bump things out of the - // window leaving room for new items. It's important we process these changes first, so we - // iterate the changes twice, first processing any that affect items currently in view. - // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server - // and event snap. I'm not sure if this will result in edge cases when a child is in one but - // not the other. - var curViewCache = viewCache; - var viewMergeTree; - if (path.isEmpty()) { - viewMergeTree = changedChildren; - } - else { - viewMergeTree = ImmutableTree.Empty.setTree(path, changedChildren); - } - var serverNode = viewCache.getServerCache().getNode(); - viewMergeTree.children.inorderTraversal(function (childKey, childTree) { - if (serverNode.hasChild(childKey)) { - var serverChild = viewCache - .getServerCache() - .getNode() - .getImmediateChild(childKey); - var newChild = _this.applyMerge_(serverChild, childTree); - curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); - } - }); - viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) { - var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) && - childMergeTree.value == null; - if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { - var serverChild = viewCache - .getServerCache() - .getNode() - .getImmediateChild(childKey); - var newChild = _this.applyMerge_(serverChild, childMergeTree); - curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); - } - }); - return curViewCache; - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} ackPath - * @param {!ImmutableTree} affectedTree - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { - if (writesCache.shadowingWrite(ackPath) != null) { - return viewCache; - } - // Only filter server node if it is currently filtered - var filterServerNode = viewCache.getServerCache().isFiltered(); - // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update - // now that it won't be shadowed. - var serverCache = viewCache.getServerCache(); - if (affectedTree.value != null) { - // This is an overwrite. - if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) || - serverCache.isCompleteForPath(ackPath)) { - return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); - } - else if (ackPath.isEmpty()) { - // This is a goofy edge case where we are acking data at this location but don't have full data. We - // should just re-apply whatever we have in our cache as a merge. - var changedChildren_1 = ImmutableTree.Empty; - serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) { - changedChildren_1 = changedChildren_1.set(new Path(name), node); - }); - return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator); - } - else { - return viewCache; - } - } - else { - // This is a merge. - var changedChildren_2 = ImmutableTree.Empty; - affectedTree.foreach(function (mergePath, value) { - var serverCachePath = ackPath.child(mergePath); - if (serverCache.isCompleteForPath(serverCachePath)) { - changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath)); - } - }); - return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator); - } - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) { - var oldServerNode = viewCache.getServerCache(); - var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered()); - return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) { - var complete; - if (writesCache.shadowingWrite(path) != null) { - return viewCache; - } - else { - var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); - var oldEventCache = viewCache.getEventCache().getNode(); - var newEventCache = void 0; - if (path.isEmpty() || path.getFront() === '.priority') { - var newNode = void 0; - if (viewCache.getServerCache().isFullyInitialized()) { - newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - } - else { - var serverChildren = viewCache.getServerCache().getNode(); - assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); - newNode = writesCache.calcCompleteEventChildren(serverChildren); - } - newNode = newNode; - newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator); - } - else { - var childKey = path.getFront(); - var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache()); - if (newChild == null && - viewCache.getServerCache().isCompleteForChild(childKey)) { - newChild = oldEventCache.getImmediateChild(childKey); - } - if (newChild != null) { - newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator); - } - else if (viewCache - .getEventCache() - .getNode() - .hasChild(childKey)) { - // No complete child available, delete the existing one, if any - newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator); - } - else { - newEventCache = oldEventCache; - } - if (newEventCache.isEmpty() && - viewCache.getServerCache().isFullyInitialized()) { - // We might have reverted all child writes. Maybe the old event was a leaf node - complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - if (complete.isLeafNode()) { - newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator); - } - } - } - complete = - viewCache.getServerCache().isFullyInitialized() || - writesCache.shadowingWrite(Path.Empty) != null; - return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes()); - } - }; - return ViewProcessor; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An EventGenerator is used to convert "raw" changes (Change) as computed by the - * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() - * for details. - * - * @constructor - */ -var EventGenerator = /** @class */ (function () { - /** - * - * @param {!Query} query_ - */ - function EventGenerator(query_) { - this.query_ = query_; - /** - * @private - * @type {!Index} - */ - this.index_ = this.query_.getQueryParams().getIndex(); - } - /** - * Given a set of raw changes (no moved events and prevName not specified yet), and a set of - * EventRegistrations that should be notified of these changes, generate the actual events to be raised. - * - * Notes: - * - child_moved events will be synthesized at this time for any child_changed events that affect - * our index. - * - prevName will be calculated based on the index ordering. - * - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {!Array.} eventRegistrations - * @return {!Array.} - */ - EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) { - var _this = this; - var events = []; - var moves = []; - changes.forEach(function (change) { - if (change.type === Change.CHILD_CHANGED && - _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { - moves.push(Change.childMovedChange(change.childName, change.snapshotNode)); - } - }); - this.generateEventsForType_(events, Change.CHILD_REMOVED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_ADDED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_MOVED, moves, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_CHANGED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.VALUE, changes, eventRegistrations, eventCache); - return events; - }; - /** - * Given changes of a single change type, generate the corresponding events. - * - * @param {!Array.} events - * @param {!string} eventType - * @param {!Array.} changes - * @param {!Array.} registrations - * @param {!Node} eventCache - * @private - */ - EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) { - var _this = this; - var filteredChanges = changes.filter(function (change) { return change.type === eventType; }); - filteredChanges.sort(this.compareChanges_.bind(this)); - filteredChanges.forEach(function (change) { - var materializedChange = _this.materializeSingleChange_(change, eventCache); - registrations.forEach(function (registration) { - if (registration.respondsTo(change.type)) { - events.push(registration.createEvent(materializedChange, _this.query_)); - } - }); - }); - }; - /** - * @param {!Change} change - * @param {!Node} eventCache - * @return {!Change} - * @private - */ - EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) { - if (change.type === 'value' || change.type === 'child_removed') { - return change; - } - else { - change.prevName = eventCache.getPredecessorChildName( - /** @type {!string} */ - change.childName, change.snapshotNode, this.index_); - return change; - } - }; - /** - * @param {!Change} a - * @param {!Change} b - * @return {number} - * @private - */ - EventGenerator.prototype.compareChanges_ = function (a, b) { - if (a.childName == null || b.childName == null) { - throw assertionError('Should only compare child_ events.'); - } - var aWrapped = new NamedNode(a.childName, a.snapshotNode); - var bWrapped = new NamedNode(b.childName, b.snapshotNode); - return this.index_.compare(aWrapped, bWrapped); - }; - return EventGenerator; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A view represents a specific location and query that has 1 or more event registrations. - * - * It does several things: - * - Maintains the list of event registrations for this location/query. - * - Maintains a cache of the data visible for this location/query. - * - Applies new operations (via applyOperation), updates the cache, and based on the event - * registrations returns the set of events to be raised. - * @constructor - */ -var View = /** @class */ (function () { - /** - * - * @param {!Query} query_ - * @param {!ViewCache} initialViewCache - */ - function View(query_, initialViewCache) { - this.query_ = query_; - this.eventRegistrations_ = []; - var params = this.query_.getQueryParams(); - var indexFilter = new IndexedFilter(params.getIndex()); - var filter = params.getNodeFilter(); - /** - * @type {ViewProcessor} - * @private - */ - this.processor_ = new ViewProcessor(filter); - var initialServerCache = initialViewCache.getServerCache(); - var initialEventCache = initialViewCache.getEventCache(); - // Don't filter server node with other filter than index, wait for tagged listen - var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); - var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); - var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); - var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); - /** - * @type {!ViewCache} - * @private - */ - this.viewCache_ = new ViewCache(newEventCache, newServerCache); - /** - * @type {!EventGenerator} - * @private - */ - this.eventGenerator_ = new EventGenerator(this.query_); - } - /** - * @return {!Query} - */ - View.prototype.getQuery = function () { - return this.query_; - }; - /** - * @return {?Node} - */ - View.prototype.getServerCache = function () { - return this.viewCache_.getServerCache().getNode(); - }; - /** - * @param {!Path} path - * @return {?Node} - */ - View.prototype.getCompleteServerCache = function (path) { - var cache = this.viewCache_.getCompleteServerSnap(); - if (cache) { - // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and - // we need to see if it contains the child we're interested in. - if (this.query_.getQueryParams().loadsAllData() || - (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) { - return cache.getChild(path); - } - } - return null; - }; - /** - * @return {boolean} - */ - View.prototype.isEmpty = function () { - return this.eventRegistrations_.length === 0; - }; - /** - * @param {!EventRegistration} eventRegistration - */ - View.prototype.addEventRegistration = function (eventRegistration) { - this.eventRegistrations_.push(eventRegistration); - }; - /** - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - View.prototype.removeEventRegistration = function (eventRegistration, cancelError) { - var cancelEvents = []; - if (cancelError) { - assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); - var path_1 = this.query_.path; - this.eventRegistrations_.forEach(function (registration) { - cancelError /** @type {!Error} */ = cancelError; - var maybeEvent = registration.createCancelEvent(cancelError, path_1); - if (maybeEvent) { - cancelEvents.push(maybeEvent); - } - }); - } - if (eventRegistration) { - var remaining = []; - for (var i = 0; i < this.eventRegistrations_.length; ++i) { - var existing = this.eventRegistrations_[i]; - if (!existing.matches(eventRegistration)) { - remaining.push(existing); - } - else if (eventRegistration.hasAnyCallback()) { - // We're removing just this one - remaining = remaining.concat(this.eventRegistrations_.slice(i + 1)); - break; - } - } - this.eventRegistrations_ = remaining; - } - else { - this.eventRegistrations_ = []; - } - return cancelEvents; - }; - /** - * Applies the given Operation, updates our cache, and returns the appropriate events. - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @return {!Array.} - */ - View.prototype.applyOperation = function (operation, writesCache, completeServerCache) { - if (operation.type === OperationType.MERGE && - operation.source.queryId !== null) { - assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges'); - assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache'); - } - var oldViewCache = this.viewCache_; - var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache); - this.processor_.assertIndexed(result.viewCache); - assert(result.viewCache.getServerCache().isFullyInitialized() || - !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back'); - this.viewCache_ = result.viewCache; - return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null); - }; - /** - * @param {!EventRegistration} registration - * @return {!Array.} - */ - View.prototype.getInitialEvents = function (registration) { - var eventSnap = this.viewCache_.getEventCache(); - var initialChanges = []; - if (!eventSnap.getNode().isLeafNode()) { - var eventNode = eventSnap.getNode(); - eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) { - initialChanges.push(Change.childAddedChange(key, childNode)); - }); - } - if (eventSnap.isFullyInitialized()) { - initialChanges.push(Change.valueChange(eventSnap.getNode())); - } - return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration); - }; - /** - * @private - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {EventRegistration=} eventRegistration - * @return {!Array.} - */ - View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) { - var registrations = eventRegistration - ? [eventRegistration] - : this.eventRegistrations_; - return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations); - }; - return View; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __referenceConstructor$1; -/** - * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to - * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes - * and user writes (set, transaction, update). - * - * It's responsible for: - * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). - * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, - * applyUserOverwrite, etc.) - */ -var SyncPoint = /** @class */ (function () { - function SyncPoint() { - /** - * The Views being tracked at this location in the tree, stored as a map where the key is a - * queryId and the value is the View for that query. - * - * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). - * - * @type {!Object.} - * @private - */ - this.views_ = {}; - } - Object.defineProperty(SyncPoint, "__referenceConstructor", { - get: function () { - assert(__referenceConstructor$1, 'Reference.ts has not been loaded'); - return __referenceConstructor$1; - }, - set: function (val) { - assert(!__referenceConstructor$1, '__referenceConstructor has already been defined'); - __referenceConstructor$1 = val; - }, - enumerable: true, - configurable: true - }); - /** - * @return {boolean} - */ - SyncPoint.prototype.isEmpty = function () { - return isEmpty(this.views_); - }; - /** - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} optCompleteServerCache - * @return {!Array.} - */ - SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) { - var queryId = operation.source.queryId; - if (queryId !== null) { - var view = safeGet(this.views_, queryId); - assert(view != null, 'SyncTree gave us an op for an invalid query.'); - return view.applyOperation(operation, writesCache, optCompleteServerCache); - } - else { - var events_1 = []; - forEach(this.views_, function (key, view) { - events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache)); - }); - return events_1; - } - }; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache Complete server cache, if we have it. - * @param {boolean} serverCacheComplete - * @return {!Array.} Events to raise. - */ - SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) { - var queryId = query.queryIdentifier(); - var view = safeGet(this.views_, queryId); - if (!view) { - // TODO: make writesCache take flag for complete server node - var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null); - var eventCacheComplete = false; - if (eventCache) { - eventCacheComplete = true; - } - else if (serverCache instanceof ChildrenNode) { - eventCache = writesCache.calcCompleteEventChildren(serverCache); - eventCacheComplete = false; - } - else { - eventCache = ChildrenNode.EMPTY_NODE; - eventCacheComplete = false; - } - var viewCache = new ViewCache(new CacheNode( - /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode( - /** @type {!Node} */ (serverCache), serverCacheComplete, false)); - view = new View(query, viewCache); - this.views_[queryId] = view; - } - // This is guaranteed to exist now, we just created anything that was missing - view.addEventRegistration(eventRegistration); - return view.getInitialEvents(eventRegistration); - }; - /** - * Remove event callback(s). Return cancelEvents if a cancelError is specified. - * - * If query is the default query, we'll check all views for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified view(s). - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events - */ - SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) { - var queryId = query.queryIdentifier(); - var removed = []; - var cancelEvents = []; - var hadCompleteView = this.hasCompleteView(); - if (queryId === 'default') { - // When you do ref.off(...), we search all views for the registration to remove. - var self_1 = this; - forEach(this.views_, function (viewQueryId, view) { - cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError)); - if (view.isEmpty()) { - delete self_1.views_[viewQueryId]; - // We'll deal with complete views later. - if (!view - .getQuery() - .getQueryParams() - .loadsAllData()) { - removed.push(view.getQuery()); - } - } - }); - } - else { - // remove the callback from the specific view. - var view = safeGet(this.views_, queryId); - if (view) { - cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError)); - if (view.isEmpty()) { - delete this.views_[queryId]; - // We'll deal with complete views later. - if (!view - .getQuery() - .getQueryParams() - .loadsAllData()) { - removed.push(view.getQuery()); - } - } - } - } - if (hadCompleteView && !this.hasCompleteView()) { - // We removed our last complete view. - removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path)); - } - return { removed: removed, events: cancelEvents }; - }; - /** - * @return {!Array.} - */ - SyncPoint.prototype.getQueryViews = function () { - var _this = this; - var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; }); - return values.filter(function (view) { - return !view - .getQuery() - .getQueryParams() - .loadsAllData(); - }); - }; - /** - * - * @param {!Path} path The path to the desired complete snapshot - * @return {?Node} A complete cache, if it exists - */ - SyncPoint.prototype.getCompleteServerCache = function (path) { - var serverCache = null; - forEach(this.views_, function (key, view) { - serverCache = serverCache || view.getCompleteServerCache(path); - }); - return serverCache; - }; - /** - * @param {!Query} query - * @return {?View} - */ - SyncPoint.prototype.viewForQuery = function (query) { - var params = query.getQueryParams(); - if (params.loadsAllData()) { - return this.getCompleteView(); - } - else { - var queryId = query.queryIdentifier(); - return safeGet(this.views_, queryId); - } - }; - /** - * @param {!Query} query - * @return {boolean} - */ - SyncPoint.prototype.viewExistsForQuery = function (query) { - return this.viewForQuery(query) != null; - }; - /** - * @return {boolean} - */ - SyncPoint.prototype.hasCompleteView = function () { - return this.getCompleteView() != null; - }; - /** - * @return {?View} - */ - SyncPoint.prototype.getCompleteView = function () { - var completeView = findValue(this.views_, function (view) { - return view - .getQuery() - .getQueryParams() - .loadsAllData(); - }); - return completeView || null; - }; - return SyncPoint; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with - * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write - * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write - * to reflect the write added. - * - * @constructor - * @param {!ImmutableTree.} writeTree - */ -var CompoundWrite = /** @class */ (function () { - function CompoundWrite(writeTree_) { - this.writeTree_ = writeTree_; - } - /** - * @param {!Path} path - * @param {!Node} node - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.addWrite = function (path, node) { - if (path.isEmpty()) { - return new CompoundWrite(new ImmutableTree(node)); - } - else { - var rootmost = this.writeTree_.findRootMostValueAndPath(path); - if (rootmost != null) { - var rootMostPath = rootmost.path; - var value = rootmost.value; - var relativePath = Path.relativePath(rootMostPath, path); - value = value.updateChild(relativePath, node); - return new CompoundWrite(this.writeTree_.set(rootMostPath, value)); - } - else { - var subtree = new ImmutableTree(node); - var newWriteTree = this.writeTree_.setTree(path, subtree); - return new CompoundWrite(newWriteTree); - } - } - }; - /** - * @param {!Path} path - * @param {!Object.} updates - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.addWrites = function (path, updates) { - var newWrite = this; - forEach(updates, function (childKey, node) { - newWrite = newWrite.addWrite(path.child(childKey), node); - }); - return newWrite; - }; - /** - * Will remove a write at the given path and deeper paths. This will not modify a write at a higher - * location, which must be removed by calling this method with that path. - * - * @param {!Path} path The path at which a write and all deeper writes should be removed - * @return {!CompoundWrite} The new CompoundWrite with the removed path - */ - CompoundWrite.prototype.removeWrite = function (path) { - if (path.isEmpty()) { - return CompoundWrite.Empty; - } - else { - var newWriteTree = this.writeTree_.setTree(path, ImmutableTree.Empty); - return new CompoundWrite(newWriteTree); - } - }; - /** - * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be - * considered "complete". - * - * @param {!Path} path The path to check for - * @return {boolean} Whether there is a complete write at that path - */ - CompoundWrite.prototype.hasCompleteWrite = function (path) { - return this.getCompleteNode(path) != null; - }; - /** - * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate - * writes from deeper paths, but will return child nodes from a more shallow path. - * - * @param {!Path} path The path to get a complete write - * @return {?Node} The node if complete at that path, or null otherwise. - */ - CompoundWrite.prototype.getCompleteNode = function (path) { - var rootmost = this.writeTree_.findRootMostValueAndPath(path); - if (rootmost != null) { - return this.writeTree_ - .get(rootmost.path) - .getChild(Path.relativePath(rootmost.path, path)); - } - else { - return null; - } - }; - /** - * Returns all children that are guaranteed to be a complete overwrite. - * - * @return {!Array.} A list of all complete children. - */ - CompoundWrite.prototype.getCompleteChildren = function () { - var children = []; - var node = this.writeTree_.value; - if (node != null) { - // If it's a leaf node, it has no children; so nothing to do. - if (!node.isLeafNode()) { - node.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - children.push(new NamedNode(childName, childNode)); - }); - } - } - else { - this.writeTree_.children.inorderTraversal(function (childName, childTree) { - if (childTree.value != null) { - children.push(new NamedNode(childName, childTree.value)); - } - }); - } - return children; - }; - /** - * @param {!Path} path - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.childCompoundWrite = function (path) { - if (path.isEmpty()) { - return this; - } - else { - var shadowingNode = this.getCompleteNode(path); - if (shadowingNode != null) { - return new CompoundWrite(new ImmutableTree(shadowingNode)); - } - else { - return new CompoundWrite(this.writeTree_.subtree(path)); - } - } - }; - /** - * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. - * @return {boolean} Whether this CompoundWrite is empty - */ - CompoundWrite.prototype.isEmpty = function () { - return this.writeTree_.isEmpty(); - }; - /** - * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the - * node - * @param {!Node} node The node to apply this CompoundWrite to - * @return {!Node} The node with all writes applied - */ - CompoundWrite.prototype.apply = function (node) { - return CompoundWrite.applySubtreeWrite_(Path.Empty, this.writeTree_, node); - }; - /** - * @type {!CompoundWrite} - */ - CompoundWrite.Empty = new CompoundWrite(new ImmutableTree(null)); - /** - * @param {!Path} relativePath - * @param {!ImmutableTree.} writeTree - * @param {!Node} node - * @return {!Node} - * @private - */ - CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) { - if (writeTree.value != null) { - // Since there a write is always a leaf, we're done here - return node.updateChild(relativePath, writeTree.value); - } - else { - var priorityWrite_1 = null; - writeTree.children.inorderTraversal(function (childKey, childTree) { - if (childKey === '.priority') { - // Apply priorities at the end so we don't update priorities for either empty nodes or forget - // to apply priorities to empty nodes that are later filled - assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); - priorityWrite_1 = childTree.value; - } - else { - node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node); - } - }); - // If there was a priority write, we only apply it if the node is not empty - if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) { - node = node.updateChild(relativePath.child('.priority'), priorityWrite_1); - } - return node; - } - }; - return CompoundWrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them - * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() - * and addMerge(), and removed with removeWrite(). - * - * @constructor - */ -var WriteTree = /** @class */ (function () { - function WriteTree() { - /** - * A tree tracking the result of applying all visible writes. This does not include transactions with - * applyLocally=false or writes that are completely shadowed by other writes. - * - * @type {!CompoundWrite} - * @private - */ - this.visibleWrites_ = CompoundWrite.Empty; - /** - * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary - * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also - * used by transactions). - * - * @type {!Array.} - * @private - */ - this.allWrites_ = []; - this.lastWriteId_ = -1; - } - /** - * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. - * - * @param {!Path} path - * @return {!WriteTreeRef} - */ - WriteTree.prototype.childWrites = function (path) { - return new WriteTreeRef(path, this); - }; - /** - * Record a new overwrite from user code. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} writeId - * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches - */ - WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) { - assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones'); - if (visible === undefined) { - visible = true; - } - this.allWrites_.push({ - path: path, - snap: snap, - writeId: writeId, - visible: visible - }); - if (visible) { - this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap); - } - this.lastWriteId_ = writeId; - }; - /** - * Record a new merge from user code. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - */ - WriteTree.prototype.addMerge = function (path, changedChildren, writeId) { - assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones'); - this.allWrites_.push({ - path: path, - children: changedChildren, - writeId: writeId, - visible: true - }); - this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren); - this.lastWriteId_ = writeId; - }; - /** - * @param {!number} writeId - * @return {?WriteRecord} - */ - WriteTree.prototype.getWrite = function (writeId) { - for (var i = 0; i < this.allWrites_.length; i++) { - var record = this.allWrites_[i]; - if (record.writeId === writeId) { - return record; - } - } - return null; - }; - /** - * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates - * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. - * - * @param {!number} writeId - * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise - * events as a result). - */ - WriteTree.prototype.removeWrite = function (writeId) { - // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied - // out of order. - //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; - //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); - var _this = this; - var idx = this.allWrites_.findIndex(function (s) { - return s.writeId === writeId; - }); - assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); - var writeToRemove = this.allWrites_[idx]; - this.allWrites_.splice(idx, 1); - var removedWriteWasVisible = writeToRemove.visible; - var removedWriteOverlapsWithOtherWrites = false; - var i = this.allWrites_.length - 1; - while (removedWriteWasVisible && i >= 0) { - var currentWrite = this.allWrites_[i]; - if (currentWrite.visible) { - if (i >= idx && - this.recordContainsPath_(currentWrite, writeToRemove.path)) { - // The removed write was completely shadowed by a subsequent write. - removedWriteWasVisible = false; - } - else if (writeToRemove.path.contains(currentWrite.path)) { - // Either we're covering some writes or they're covering part of us (depending on which came first). - removedWriteOverlapsWithOtherWrites = true; - } - } - i--; - } - if (!removedWriteWasVisible) { - return false; - } - else if (removedWriteOverlapsWithOtherWrites) { - // There's some shadowing going on. Just rebuild the visible writes from scratch. - this.resetTree_(); - return true; - } - else { - // There's no shadowing. We can safely just remove the write(s) from visibleWrites. - if (writeToRemove.snap) { - this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path); - } - else { - var children = writeToRemove.children; - forEach(children, function (childName) { - _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName)); - }); - } - return true; - } - }; - /** - * Return a complete snapshot for the given path if there's visible write data at that path, else null. - * No server data is considered. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTree.prototype.getCompleteWriteData = function (path) { - return this.visibleWrites_.getCompleteNode(path); - }; - /** - * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden - * writes), attempt to calculate a complete snapshot for the given path - * - * @param {!Path} treePath - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude An optional set to be excluded - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { - if (!writeIdsToExclude && !includeHiddenWrites) { - var shadowingNode = this.visibleWrites_.getCompleteNode(treePath); - if (shadowingNode != null) { - return shadowingNode; - } - else { - var subMerge = this.visibleWrites_.childCompoundWrite(treePath); - if (subMerge.isEmpty()) { - return completeServerCache; - } - else if (completeServerCache == null && - !subMerge.hasCompleteWrite(Path.Empty)) { - // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow - return null; - } - else { - var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; - return subMerge.apply(layeredCache); - } - } - } - else { - var merge = this.visibleWrites_.childCompoundWrite(treePath); - if (!includeHiddenWrites && merge.isEmpty()) { - return completeServerCache; - } - else { - // If the server cache is null, and we don't have a complete cache, we need to return null - if (!includeHiddenWrites && - completeServerCache == null && - !merge.hasCompleteWrite(Path.Empty)) { - return null; - } - else { - var filter = function (write) { - return ((write.visible || includeHiddenWrites) && - (!writeIdsToExclude || - !~writeIdsToExclude.indexOf(write.writeId)) && - (write.path.contains(treePath) || treePath.contains(write.path))); - }; - var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath); - var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; - return mergeAtPath.apply(layeredCache); - } - } - } - }; - /** - * With optional, underlying server data, attempt to return a children node of children that we have complete data for. - * Used when creating new views, to pre-fill their complete event children snapshot. - * - * @param {!Path} treePath - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) { - var completeChildren = ChildrenNode.EMPTY_NODE; - var topLevelSet = this.visibleWrites_.getCompleteNode(treePath); - if (topLevelSet) { - if (!topLevelSet.isLeafNode()) { - // we're shadowing everything. Return the children. - topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) { - completeChildren = completeChildren.updateImmediateChild(childName, childSnap); - }); - } - return completeChildren; - } - else if (completeServerChildren) { - // Layer any children we have on top of this - // We know we don't have a top-level set, so just enumerate existing children - var merge_1 = this.visibleWrites_.childCompoundWrite(treePath); - completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - var node = merge_1 - .childCompoundWrite(new Path(childName)) - .apply(childNode); - completeChildren = completeChildren.updateImmediateChild(childName, node); - }); - // Add any complete children we have from the set - merge_1.getCompleteChildren().forEach(function (namedNode) { - completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); - }); - return completeChildren; - } - else { - // We don't have anything to layer on top of. Layer on any children we have - // Note that we can return an empty snap if we have a defined delete - var merge = this.visibleWrites_.childCompoundWrite(treePath); - merge.getCompleteChildren().forEach(function (namedNode) { - completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); - }); - return completeChildren; - } - }; - /** - * Given that the underlying server data has updated, determine what, if anything, needs to be - * applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events - * - * Either existingEventSnap or existingServerSnap must exist - * - * @param {!Path} treePath - * @param {!Path} childPath - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) { - assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); - var path = treePath.child(childPath); - if (this.visibleWrites_.hasCompleteWrite(path)) { - // At this point we can probably guarantee that we're in case 2, meaning no events - // May need to check visibility while doing the findRootMostValueAndPath call - return null; - } - else { - // No complete shadowing. We're either partially shadowing or not shadowing at all. - var childMerge = this.visibleWrites_.childCompoundWrite(path); - if (childMerge.isEmpty()) { - // We're not shadowing at all. Case 1 - return existingServerSnap.getChild(childPath); - } - else { - // This could be more efficient if the serverNode + updates doesn't change the eventSnap - // However this is tricky to find out, since user updates don't necessary change the server - // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server - // adds nodes, but doesn't change any existing writes. It is therefore not enough to - // only check if the updates change the serverNode. - // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? - return childMerge.apply(existingServerSnap.getChild(childPath)); - } - } - }; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!Path} treePath - * @param {!string} childKey - * @param {!CacheNode} existingServerSnap - * @return {?Node} - */ - WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) { - var path = treePath.child(childKey); - var shadowingNode = this.visibleWrites_.getCompleteNode(path); - if (shadowingNode != null) { - return shadowingNode; - } - else { - if (existingServerSnap.isCompleteForChild(childKey)) { - var childMerge = this.visibleWrites_.childCompoundWrite(path); - return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey)); - } - else { - return null; - } - } - }; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTree.prototype.shadowingWrite = function (path) { - return this.visibleWrites_.getCompleteNode(path); - }; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window. - * - * @param {!Path} treePath - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) { - var toIterate; - var merge = this.visibleWrites_.childCompoundWrite(treePath); - var shadowingNode = merge.getCompleteNode(Path.Empty); - if (shadowingNode != null) { - toIterate = shadowingNode; - } - else if (completeServerData != null) { - toIterate = merge.apply(completeServerData); - } - else { - // no children to iterate on - return []; - } - toIterate = toIterate.withIndex(index); - if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { - var nodes = []; - var cmp = index.getCompare(); - var iter = reverse - ? toIterate.getReverseIteratorFrom(startPost, index) - : toIterate.getIteratorFrom(startPost, index); - var next = iter.getNext(); - while (next && nodes.length < count) { - if (cmp(next, startPost) !== 0) { - nodes.push(next); - } - next = iter.getNext(); - } - return nodes; - } - else { - return []; - } - }; - /** - * @param {!WriteRecord} writeRecord - * @param {!Path} path - * @return {boolean} - * @private - */ - WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) { - if (writeRecord.snap) { - return writeRecord.path.contains(path); - } - else { - // findKey can return undefined, so use !! to coerce to boolean - return !!findKey(writeRecord.children, function (childSnap, childName) { - return writeRecord.path.child(childName).contains(path); - }); - } - }; - /** - * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots - * @private - */ - WriteTree.prototype.resetTree_ = function () { - this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path.Empty); - if (this.allWrites_.length > 0) { - this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId; - } - else { - this.lastWriteId_ = -1; - } - }; - /** - * The default filter used when constructing the tree. Keep everything that's visible. - * - * @param {!WriteRecord} write - * @return {boolean} - * @private - */ - WriteTree.DefaultFilter_ = function (write) { - return write.visible; - }; - /** - * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of - * event data at that path. - * - * @param {!Array.} writes - * @param {!function(!WriteRecord):boolean} filter - * @param {!Path} treeRoot - * @return {!CompoundWrite} - * @private - */ - WriteTree.layerTree_ = function (writes, filter, treeRoot) { - var compoundWrite = CompoundWrite.Empty; - for (var i = 0; i < writes.length; ++i) { - var write = writes[i]; - // Theory, a later set will either: - // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction - // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction - if (filter(write)) { - var writePath = write.path; - var relativePath = void 0; - if (write.snap) { - if (treeRoot.contains(writePath)) { - relativePath = Path.relativePath(treeRoot, writePath); - compoundWrite = compoundWrite.addWrite(relativePath, write.snap); - } - else if (writePath.contains(treeRoot)) { - relativePath = Path.relativePath(writePath, treeRoot); - compoundWrite = compoundWrite.addWrite(Path.Empty, write.snap.getChild(relativePath)); - } - else { - // There is no overlap between root path and write path, ignore write - } - } - else if (write.children) { - if (treeRoot.contains(writePath)) { - relativePath = Path.relativePath(treeRoot, writePath); - compoundWrite = compoundWrite.addWrites(relativePath, write.children); - } - else if (writePath.contains(treeRoot)) { - relativePath = Path.relativePath(writePath, treeRoot); - if (relativePath.isEmpty()) { - compoundWrite = compoundWrite.addWrites(Path.Empty, write.children); - } - else { - var child = safeGet(write.children, relativePath.getFront()); - if (child) { - // There exists a child in this node that matches the root path - var deepNode = child.getChild(relativePath.popFront()); - compoundWrite = compoundWrite.addWrite(Path.Empty, deepNode); - } - } - } - else { - // There is no overlap between root path and write path, ignore write - } - } - else { - throw assertionError('WriteRecord should have .snap or .children'); - } - } - } - return compoundWrite; - }; - return WriteTree; -}()); -/** - * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods - * just proxy to the underlying WriteTree. - * - * @constructor - */ -var WriteTreeRef = /** @class */ (function () { - /** - * @param {!Path} path - * @param {!WriteTree} writeTree - */ - function WriteTreeRef(path, writeTree) { - this.treePath_ = path; - this.writeTree_ = writeTree; - } - /** - * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used - * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node - * can lead to a more expensive calculation. - * - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude Optional writes to exclude. - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) { - return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites); - }; - /** - * If possible, returns a children node containing all of the complete children we have data for. The returned data is a - * mix of the given server data and write data. - * - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) { - return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren); - }; - /** - * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, - * if anything, needs to be applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events should be raised - * - * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert - * - * @param {!Path} path - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) { - return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap); - }; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTreeRef.prototype.shadowingWrite = function (path) { - return this.writeTree_.shadowingWrite(this.treePath_.child(path)); - }; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window - * - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) { - return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index); - }; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!string} childKey - * @param {!CacheNode} existingServerCache - * @return {?Node} - */ - WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) { - return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache); - }; - /** - * Return a WriteTreeRef for a child. - * - * @param {string} childName - * @return {!WriteTreeRef} - */ - WriteTreeRef.prototype.child = function (childName) { - return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_); - }; - return WriteTreeRef; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SyncTree is the central class for managing event callback registration, data caching, views - * (query processing), and event generation. There are typically two SyncTree instances for - * each Repo, one for the normal Firebase data, and one for the .info data. - * - * It has a number of responsibilities, including: - * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). - * - Applying and caching data changes for user set(), transaction(), and update() calls - * (applyUserOverwrite(), applyUserMerge()). - * - Applying and caching data changes for server data changes (applyServerOverwrite(), - * applyServerMerge()). - * - Generating user-facing events for server and user changes (all of the apply* methods - * return the set of events that need to be raised as a result). - * - Maintaining the appropriate set of server listens to ensure we are always subscribed - * to the correct set of paths and queries to satisfy the current set of user event - * callbacks (listens are started/stopped using the provided listenProvider). - * - * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual - * events are returned to the caller rather than raised synchronously. - * - * @constructor - */ -var SyncTree = /** @class */ (function () { - /** - * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening - * to server data. - */ - function SyncTree(listenProvider_) { - this.listenProvider_ = listenProvider_; - /** - * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. - * @type {!ImmutableTree.} - * @private - */ - this.syncPointTree_ = ImmutableTree.Empty; - /** - * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). - * @type {!WriteTree} - * @private - */ - this.pendingWriteTree_ = new WriteTree(); - this.tagToQueryMap_ = {}; - this.queryToTagMap_ = {}; - } - /** - * Apply the data changes for a user-generated set() or transaction() call. - * - * @param {!Path} path - * @param {!Node} newData - * @param {number} writeId - * @param {boolean=} visible - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) { - // Record pending write. - this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible); - if (!visible) { - return []; - } - else { - return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.User, path, newData)); - } - }; - /** - * Apply the data from a user-generated update() call - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) { - // Record pending merge. - this.pendingWriteTree_.addMerge(path, changedChildren, writeId); - var changeTree = ImmutableTree.fromObject(changedChildren); - return this.applyOperationToSyncPoints_(new Merge(OperationSource.User, path, changeTree)); - }; - /** - * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). - * - * @param {!number} writeId - * @param {boolean=} revert True if the given write failed and needs to be reverted - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.ackUserWrite = function (writeId, revert) { - if (revert === void 0) { revert = false; } - var write = this.pendingWriteTree_.getWrite(writeId); - var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId); - if (!needToReevaluate) { - return []; - } - else { - var affectedTree_1 = ImmutableTree.Empty; - if (write.snap != null) { - // overwrite - affectedTree_1 = affectedTree_1.set(Path.Empty, true); - } - else { - forEach(write.children, function (pathString, node) { - affectedTree_1 = affectedTree_1.set(new Path(pathString), node); - }); - } - return this.applyOperationToSyncPoints_(new AckUserWrite(write.path, affectedTree_1, revert)); - } - }; - /** - * Apply new server data for the specified path.. - * - * @param {!Path} path - * @param {!Node} newData - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyServerOverwrite = function (path, newData) { - return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.Server, path, newData)); - }; - /** - * Apply new server data to be merged in at the specified path. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyServerMerge = function (path, changedChildren) { - var changeTree = ImmutableTree.fromObject(changedChildren); - return this.applyOperationToSyncPoints_(new Merge(OperationSource.Server, path, changeTree)); - }; - /** - * Apply a listen complete for a query - * - * @param {!Path} path - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyListenComplete = function (path) { - return this.applyOperationToSyncPoints_(new ListenComplete(OperationSource.Server, path)); - }; - /** - * Apply new server data for the specified tagged query. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey != null) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var op = new Overwrite(OperationSource.forServerTaggedQuery(queryId), relativePath, snap); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // Query must have been removed already - return []; - } - }; - /** - * Apply server data to be merged in for the specified tagged query. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var changeTree = ImmutableTree.fromObject(changedChildren); - var op = new Merge(OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // We've already removed the query. No big deal, ignore the update - return []; - } - }; - /** - * Apply a listen complete for a tagged query - * - * @param {!Path} path - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedListenComplete = function (path, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var op = new ListenComplete(OperationSource.forServerTaggedQuery(queryId), relativePath); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // We've already removed the query. No big deal, ignore the update - return []; - } - }; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.addEventRegistration = function (query, eventRegistration) { - var path = query.path; - var serverCache = null; - var foundAncestorDefaultView = false; - // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. - // Consider optimizing this once there's a better understanding of what actual behavior will be. - this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) { - var relativePath = Path.relativePath(pathToSyncPoint, path); - serverCache = serverCache || sp.getCompleteServerCache(relativePath); - foundAncestorDefaultView = - foundAncestorDefaultView || sp.hasCompleteView(); - }); - var syncPoint = this.syncPointTree_.get(path); - if (!syncPoint) { - syncPoint = new SyncPoint(); - this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint); - } - else { - foundAncestorDefaultView = - foundAncestorDefaultView || syncPoint.hasCompleteView(); - serverCache = serverCache || syncPoint.getCompleteServerCache(Path.Empty); - } - var serverCacheComplete; - if (serverCache != null) { - serverCacheComplete = true; - } - else { - serverCacheComplete = false; - serverCache = ChildrenNode.EMPTY_NODE; - var subtree = this.syncPointTree_.subtree(path); - subtree.foreachChild(function (childName, childSyncPoint) { - var completeCache = childSyncPoint.getCompleteServerCache(Path.Empty); - if (completeCache) { - serverCache = serverCache.updateImmediateChild(childName, completeCache); - } - }); - } - var viewAlreadyExists = syncPoint.viewExistsForQuery(query); - if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) { - // We need to track a tag for this query - var queryKey = SyncTree.makeQueryKey_(query); - assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag'); - var tag = SyncTree.getNextQueryTag_(); - this.queryToTagMap_[queryKey] = tag; - // Coerce to string to avoid sparse arrays. - this.tagToQueryMap_['_' + tag] = queryKey; - } - var writesCache = this.pendingWriteTree_.childWrites(path); - var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete); - if (!viewAlreadyExists && !foundAncestorDefaultView) { - var view /** @type !View */ = syncPoint.viewForQuery(query); - events = events.concat(this.setupListener_(query, view)); - } - return events; - }; - /** - * Remove event callback(s). - * - * If query is the default query, we'll check all queries for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, all callbacks are removed. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) { - var _this = this; - // Find the syncPoint first. Then deal with whether or not it has matching listeners - var path = query.path; - var maybeSyncPoint = this.syncPointTree_.get(path); - var cancelEvents = []; - // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without - // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and - // not loadsAllData(). - if (maybeSyncPoint && - (query.queryIdentifier() === 'default' || - maybeSyncPoint.viewExistsForQuery(query))) { - /** - * @type {{removed: !Array., events: !Array.}} - */ - var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError); - if (maybeSyncPoint.isEmpty()) { - this.syncPointTree_ = this.syncPointTree_.remove(path); - } - var removed = removedAndEvents.removed; - cancelEvents = removedAndEvents.events; - // We may have just removed one of many listeners and can short-circuit this whole process - // We may also not have removed a default listener, in which case all of the descendant listeners should already be - // properly set up. - // - // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of - // queryId === 'default' - var removingDefault = -1 !== - removed.findIndex(function (query) { - return query.getQueryParams().loadsAllData(); - }); - var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) { - return parentSyncPoint.hasCompleteView(); - }); - if (removingDefault && !covered) { - var subtree = this.syncPointTree_.subtree(path); - // There are potentially child listeners. Determine what if any listens we need to send before executing the - // removal - if (!subtree.isEmpty()) { - // We need to fold over our subtree and collect the listeners to send - var newViews = this.collectDistinctViewsForSubTree_(subtree); - // Ok, we've collected all the listens we need. Set them up. - for (var i = 0; i < newViews.length; ++i) { - var view = newViews[i], newQuery = view.getQuery(); - var listener = this.createListenerForView_(view); - this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete); - } - } - else { - // There's nothing below us, so nothing we need to start listening on - } - } - // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query - // The above block has us covered in terms of making sure we're set up on listens lower in the tree. - // Also, note that if we have a cancelError, it's already been removed at the provider level. - if (!covered && removed.length > 0 && !cancelError) { - // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one - // default. Otherwise, we need to iterate through and cancel each individual query - if (removingDefault) { - // We don't tag default listeners - var defaultTag = null; - this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag); - } - else { - removed.forEach(function (queryToRemove) { - var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)]; - _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove); - }); - } - } - // Now, clear all of the tags we're tracking for the removed listens - this.removeTags_(removed); - } - else { - // No-op, this listener must've been already removed - } - return cancelEvents; - }; - /** - * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above - * it, but as this is only used by transaction code, that should always be the case anyways. - * - * Note: this method will *include* hidden writes from transaction with applyLocally set to false. - * @param {!Path} path The path to the data we want - * @param {Array.=} writeIdsToExclude A specific set to be excluded - * @return {?Node} - */ - SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) { - var includeHiddenSets = true; - var writeTree = this.pendingWriteTree_; - var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) { - var relativePath = Path.relativePath(pathSoFar, path); - var serverCache = syncPoint.getCompleteServerCache(relativePath); - if (serverCache) { - return serverCache; - } - }); - return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets); - }; - /** - * This collapses multiple unfiltered views into a single view, since we only need a single - * listener for them. - * - * @param {!ImmutableTree.} subtree - * @return {!Array.} - * @private - */ - SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) { - return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) { - if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) { - var completeView = maybeChildSyncPoint.getCompleteView(); - return [completeView]; - } - else { - // No complete view here, flatten any deeper listens into an array - var views_1 = []; - if (maybeChildSyncPoint) { - views_1 = maybeChildSyncPoint.getQueryViews(); - } - forEach(childMap, function (key, childViews) { - views_1 = views_1.concat(childViews); - }); - return views_1; - } - }); - }; - /** - * @param {!Array.} queries - * @private - */ - SyncTree.prototype.removeTags_ = function (queries) { - for (var j = 0; j < queries.length; ++j) { - var removedQuery = queries[j]; - if (!removedQuery.getQueryParams().loadsAllData()) { - // We should have a tag for this - var removedQueryKey = SyncTree.makeQueryKey_(removedQuery); - var removedQueryTag = this.queryToTagMap_[removedQueryKey]; - delete this.queryToTagMap_[removedQueryKey]; - delete this.tagToQueryMap_['_' + removedQueryTag]; - } - } - }; - /** - * Normalizes a query to a query we send the server for listening - * @param {!Query} query - * @return {!Query} The normalized query - * @private - */ - SyncTree.queryForListening_ = function (query) { - if (query.getQueryParams().loadsAllData() && - !query.getQueryParams().isDefault()) { - // We treat queries that load all data as default queries - // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits - // from Query - return /** @type {!Query} */ query.getRef(); - } - else { - return query; - } - }; - /** - * For a given new listen, manage the de-duplication of outstanding subscriptions. - * - * @param {!Query} query - * @param {!View} view - * @return {!Array.} This method can return events to support synchronous data sources - * @private - */ - SyncTree.prototype.setupListener_ = function (query, view) { - var path = query.path; - var tag = this.tagForQuery_(query); - var listener = this.createListenerForView_(view); - var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete); - var subtree = this.syncPointTree_.subtree(path); - // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we - // may need to shadow other listens as well. - if (tag) { - assert(!subtree.value.hasCompleteView(), "If we're adding a query, it shouldn't be shadowed"); - } - else { - // Shadow everything at or below this location, this is a default listener. - var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) { - if (!relativePath.isEmpty() && - maybeChildSyncPoint && - maybeChildSyncPoint.hasCompleteView()) { - return [maybeChildSyncPoint.getCompleteView().getQuery()]; - } - else { - // No default listener here, flatten any deeper queries into an array - var queries_1 = []; - if (maybeChildSyncPoint) { - queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); })); - } - forEach(childMap, function (key, childQueries) { - queries_1 = queries_1.concat(childQueries); - }); - return queries_1; - } - }); - for (var i = 0; i < queriesToStop.length; ++i) { - var queryToStop = queriesToStop[i]; - this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop)); - } - } - return events; - }; - /** - * - * @param {!View} view - * @return {{hashFn: function(), onComplete: function(!string, *)}} - * @private - */ - SyncTree.prototype.createListenerForView_ = function (view) { - var _this = this; - var query = view.getQuery(); - var tag = this.tagForQuery_(query); - return { - hashFn: function () { - var cache = view.getServerCache() || ChildrenNode.EMPTY_NODE; - return cache.hash(); - }, - onComplete: function (status) { - if (status === 'ok') { - if (tag) { - return _this.applyTaggedListenComplete(query.path, tag); - } - else { - return _this.applyListenComplete(query.path); - } - } - else { - // If a listen failed, kill all of the listeners here, not just the one that triggered the error. - // Note that this may need to be scoped to just this listener if we change permissions on filtered children - var error$$1 = errorForServerCode(status, query); - return _this.removeEventRegistration(query, - /*eventRegistration*/ null, error$$1); - } - } - }; - }; - /** - * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. - * @private - * @param {!Query} query - * @return {string} - */ - SyncTree.makeQueryKey_ = function (query) { - return query.path.toString() + '$' + query.queryIdentifier(); - }; - /** - * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. - * @private - * @param {!string} queryKey - * @return {{queryId: !string, path: !Path}} - */ - SyncTree.parseQueryKey_ = function (queryKey) { - var splitIndex = queryKey.indexOf('$'); - assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); - return { - queryId: queryKey.substr(splitIndex + 1), - path: new Path(queryKey.substr(0, splitIndex)) - }; - }; - /** - * Return the query associated with the given tag, if we have one - * @param {!number} tag - * @return {?string} - * @private - */ - SyncTree.prototype.queryKeyForTag_ = function (tag) { - return this.tagToQueryMap_['_' + tag]; - }; - /** - * Return the tag associated with the given query. - * @param {!Query} query - * @return {?number} - * @private - */ - SyncTree.prototype.tagForQuery_ = function (query) { - var queryKey = SyncTree.makeQueryKey_(query); - return safeGet(this.queryToTagMap_, queryKey); - }; - /** - * Static accessor for query tags. - * @return {number} - * @private - */ - SyncTree.getNextQueryTag_ = function () { - return SyncTree.nextQueryTag_++; - }; - /** - * A helper method to apply tagged operations - * - * @param {!Path} queryPath - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) { - var syncPoint = this.syncPointTree_.get(queryPath); - assert(syncPoint, "Missing sync point for query tag that we're tracking"); - var writesCache = this.pendingWriteTree_.childWrites(queryPath); - return syncPoint.applyOperation(operation, writesCache, - /*serverCache=*/ null); - }; - /** - * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. - * - * NOTES: - * - Descendant SyncPoints will be visited first (since we raise events depth-first). - - * - We call applyOperation() on each SyncPoint passing three things: - * 1. A version of the Operation that has been made relative to the SyncPoint location. - * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. - * 3. A snapshot Node with cached server data, if we have it. - - * - We concatenate all of the events returned by each SyncPoint and return the result. - * - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) { - return this.applyOperationHelper_(operation, this.syncPointTree_, - /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path.Empty)); - }; - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) { - if (operation.path.isEmpty()) { - return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); - } - else { - var syncPoint = syncPointTree.get(Path.Empty); - // If we don't have cached server data, see if we can get it from this SyncPoint. - if (serverCache == null && syncPoint != null) { - serverCache = syncPoint.getCompleteServerCache(Path.Empty); - } - var events = []; - var childName = operation.path.getFront(); - var childOperation = operation.operationForChild(childName); - var childTree = syncPointTree.children.get(childName); - if (childTree && childOperation) { - var childServerCache = serverCache - ? serverCache.getImmediateChild(childName) - : null; - var childWritesCache = writesCache.child(childName); - events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); - } - if (syncPoint) { - events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache)); - } - return events; - } - }; - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) { - var _this = this; - var syncPoint = syncPointTree.get(Path.Empty); - // If we don't have cached server data, see if we can get it from this SyncPoint. - if (serverCache == null && syncPoint != null) { - serverCache = syncPoint.getCompleteServerCache(Path.Empty); - } - var events = []; - syncPointTree.children.inorderTraversal(function (childName, childTree) { - var childServerCache = serverCache - ? serverCache.getImmediateChild(childName) - : null; - var childWritesCache = writesCache.child(childName); - var childOperation = operation.operationForChild(childName); - if (childOperation) { - events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); - } - }); - if (syncPoint) { - events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache)); - } - return events; - }; - /** - * Static tracker for next query tag. - * @type {number} - * @private - */ - SyncTree.nextQueryTag_ = 1; - return SyncTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Mutable object which basically just stores a reference to the "latest" immutable snapshot. - * - * @constructor - */ -var SnapshotHolder = /** @class */ (function () { - function SnapshotHolder() { - this.rootNode_ = ChildrenNode.EMPTY_NODE; - } - SnapshotHolder.prototype.getNode = function (path) { - return this.rootNode_.getChild(path); - }; - SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) { - this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); - }; - return SnapshotHolder; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Abstraction around FirebaseApp's token fetching capabilities. - */ -var AuthTokenProvider = /** @class */ (function () { - /** - * @param {!FirebaseApp} app_ - */ - function AuthTokenProvider(app_) { - this.app_ = app_; - } - /** - * @param {boolean} forceRefresh - * @return {!Promise} - */ - AuthTokenProvider.prototype.getToken = function (forceRefresh) { - return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, - // .catch - function (error$$1) { - // TODO: Need to figure out all the cases this is raised and whether - // this makes sense. - if (error$$1 && error$$1.code === 'auth/token-not-initialized') { - log('Got auth/token-not-initialized error. Treating as null token.'); - return null; - } - else { - return Promise.reject(error$$1); - } - }); - }; - AuthTokenProvider.prototype.addTokenChangeListener = function (listener) { - // TODO: We might want to wrap the listener and call it with no args to - // avoid a leaky abstraction, but that makes removing the listener harder. - this.app_['INTERNAL']['addAuthTokenListener'](listener); - }; - AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) { - this.app_['INTERNAL']['removeAuthTokenListener'](listener); - }; - AuthTokenProvider.prototype.notifyForInvalidToken = function () { - var errorMessage = 'Provided authentication credentials for the app named "' + - this.app_.name + - '" are invalid. This usually indicates your app was not ' + - 'initialized correctly. '; - if ('credential' in this.app_.options) { - errorMessage += - 'Make sure the "credential" property provided to initializeApp() ' + - 'is authorized to access the specified "databaseURL" and is from the correct ' + - 'project.'; - } - else if ('serviceAccount' in this.app_.options) { - errorMessage += - 'Make sure the "serviceAccount" property provided to initializeApp() ' + - 'is authorized to access the specified "databaseURL" and is from the correct ' + - 'project.'; - } - else { - errorMessage += - 'Make sure the "apiKey" and "databaseURL" properties provided to ' + - 'initializeApp() match the values provided for your app at ' + - 'https://console.firebase.google.com/.'; - } - warn(errorMessage); - }; - return AuthTokenProvider; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Tracks a collection of stats. - * - * @constructor - */ -var StatsCollection = /** @class */ (function () { - function StatsCollection() { - this.counters_ = {}; - } - StatsCollection.prototype.incrementCounter = function (name, amount) { - if (amount === void 0) { amount = 1; } - if (!contains(this.counters_, name)) - this.counters_[name] = 0; - this.counters_[name] += amount; - }; - StatsCollection.prototype.get = function () { - return deepCopy(this.counters_); - }; - return StatsCollection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var StatsManager = /** @class */ (function () { - function StatsManager() { - } - StatsManager.getCollection = function (repoInfo) { - var hashString = repoInfo.toString(); - if (!this.collections_[hashString]) { - this.collections_[hashString] = new StatsCollection(); - } - return this.collections_[hashString]; - }; - StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) { - var hashString = repoInfo.toString(); - if (!this.reporters_[hashString]) { - this.reporters_[hashString] = creatorFunction(); - } - return this.reporters_[hashString]; - }; - StatsManager.collections_ = {}; - StatsManager.reporters_ = {}; - return StatsManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns the delta from the previous call to get stats. - * - * @param collection_ The collection to "listen" to. - * @constructor - */ -var StatsListener = /** @class */ (function () { - function StatsListener(collection_) { - this.collection_ = collection_; - this.last_ = null; - } - StatsListener.prototype.get = function () { - var newStats = this.collection_.get(); - var delta = clone(newStats); - if (this.last_) { - forEach(this.last_, function (stat, value) { - delta[stat] = delta[stat] - value; - }); - } - this.last_ = newStats; - return delta; - }; - return StatsListener; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably -// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 -// seconds to try to ensure the Firebase connection is established / settled. -var FIRST_STATS_MIN_TIME = 10 * 1000; -var FIRST_STATS_MAX_TIME = 30 * 1000; -// We'll continue to report stats on average every 5 minutes. -var REPORT_STATS_INTERVAL = 5 * 60 * 1000; -/** - * @constructor - */ -var StatsReporter = /** @class */ (function () { - /** - * @param collection - * @param server_ - */ - function StatsReporter(collection, server_) { - this.server_ = server_; - this.statsToReport_ = {}; - this.statsListener_ = new StatsListener(collection); - var timeout = FIRST_STATS_MIN_TIME + - (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); - setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); - } - StatsReporter.prototype.includeStat = function (stat) { - this.statsToReport_[stat] = true; - }; - StatsReporter.prototype.reportStats_ = function () { - var _this = this; - var stats = this.statsListener_.get(); - var reportedStats = {}; - var haveStatsToReport = false; - forEach(stats, function (stat, value) { - if (value > 0 && contains(_this.statsToReport_, stat)) { - reportedStats[stat] = value; - haveStatsToReport = true; - } - }); - if (haveStatsToReport) { - this.server_.reportStats(reportedStats); - } - // queue our next run. - setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); - }; - return StatsReporter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * The event queue serves a few purposes: - * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more - * events being queued. - * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, - * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call - * left off, ensuring that the events are still raised synchronously and in order. - * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued - * events are raised synchronously. - * - * NOTE: This can all go away if/when we move to async events. - * - * @constructor - */ -var EventQueue = /** @class */ (function () { - function EventQueue() { - /** - * @private - * @type {!Array.} - */ - this.eventLists_ = []; - /** - * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. - * @private - * @type {!number} - */ - this.recursionDepth_ = 0; - } - /** - * @param {!Array.} eventDataList The new events to queue. - */ - EventQueue.prototype.queueEvents = function (eventDataList) { - // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. - var currList = null; - for (var i = 0; i < eventDataList.length; i++) { - var eventData = eventDataList[i]; - var eventPath = eventData.getPath(); - if (currList !== null && !eventPath.equals(currList.getPath())) { - this.eventLists_.push(currList); - currList = null; - } - if (currList === null) { - currList = new EventList(eventPath); - } - currList.add(eventData); - } - if (currList) { - this.eventLists_.push(currList); - } - }; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) - * for the specified path. - * - * It is assumed that the new events are all for the specified path. - * - * @param {!Path} path The path to raise events for. - * @param {!Array.} eventDataList The new events to raise. - */ - EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) { - this.queueEvents(eventDataList); - this.raiseQueuedEventsMatchingPredicate_(function (eventPath) { - return eventPath.equals(path); - }); - }; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) for - * locations related to the specified change path (i.e. all ancestors and descendants). - * - * It is assumed that the new events are all related (ancestor or descendant) to the specified path. - * - * @param {!Path} changedPath The path to raise events for. - * @param {!Array.} eventDataList The events to raise - */ - EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) { - this.queueEvents(eventDataList); - this.raiseQueuedEventsMatchingPredicate_(function (eventPath) { - return eventPath.contains(changedPath) || changedPath.contains(eventPath); - }); - }; - /** - * @param {!function(!Path):boolean} predicate - * @private - */ - EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) { - this.recursionDepth_++; - var sentAll = true; - for (var i = 0; i < this.eventLists_.length; i++) { - var eventList = this.eventLists_[i]; - if (eventList) { - var eventPath = eventList.getPath(); - if (predicate(eventPath)) { - this.eventLists_[i].raise(); - this.eventLists_[i] = null; - } - else { - sentAll = false; - } - } - } - if (sentAll) { - this.eventLists_ = []; - } - this.recursionDepth_--; - }; - return EventQueue; -}()); -/** - * @param {!Path} path - * @constructor - */ -var EventList = /** @class */ (function () { - function EventList(path_) { - this.path_ = path_; - /** - * @type {!Array.} - * @private - */ - this.events_ = []; - } - /** - * @param {!Event} eventData - */ - EventList.prototype.add = function (eventData) { - this.events_.push(eventData); - }; - /** - * Iterates through the list and raises each event - */ - EventList.prototype.raise = function () { - for (var i = 0; i < this.events_.length; i++) { - var eventData = this.events_[i]; - if (eventData !== null) { - this.events_[i] = null; - var eventFn = eventData.getEventRunner(); - if (logger) { - log('event: ' + eventData.toString()); - } - exceptionGuard(eventFn); - } - } - }; - /** - * @return {!Path} - */ - EventList.prototype.getPath = function () { - return this.path_; - }; - return EventList; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Base class to be used if you want to emit events. Call the constructor with - * the set of allowed event names. - */ -var EventEmitter = /** @class */ (function () { - /** - * @param {!Array.} allowedEvents_ - */ - function EventEmitter(allowedEvents_) { - this.allowedEvents_ = allowedEvents_; - this.listeners_ = {}; - assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); - } - /** - * To be called by derived classes to trigger events. - * @param {!string} eventType - * @param {...*} var_args - */ - EventEmitter.prototype.trigger = function (eventType) { - var var_args = []; - for (var _i = 1; _i < arguments.length; _i++) { - var_args[_i - 1] = arguments[_i]; - } - if (Array.isArray(this.listeners_[eventType])) { - // Clone the list, since callbacks could add/remove listeners. - var listeners = this.listeners_[eventType].slice(); - for (var i = 0; i < listeners.length; i++) { - listeners[i].callback.apply(listeners[i].context, var_args); - } - } - }; - EventEmitter.prototype.on = function (eventType, callback, context) { - this.validateEventType_(eventType); - this.listeners_[eventType] = this.listeners_[eventType] || []; - this.listeners_[eventType].push({ callback: callback, context: context }); - var eventData = this.getInitialEvent(eventType); - if (eventData) { - callback.apply(context, eventData); - } - }; - EventEmitter.prototype.off = function (eventType, callback, context) { - this.validateEventType_(eventType); - var listeners = this.listeners_[eventType] || []; - for (var i = 0; i < listeners.length; i++) { - if (listeners[i].callback === callback && - (!context || context === listeners[i].context)) { - listeners.splice(i, 1); - return; - } - } - }; - EventEmitter.prototype.validateEventType_ = function (eventType) { - assert(this.allowedEvents_.find(function (et) { - return et === eventType; - }), 'Unknown event: ' + eventType); - }; - return EventEmitter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @extends {EventEmitter} - */ -var VisibilityMonitor = /** @class */ (function (_super) { - __extends(VisibilityMonitor, _super); - function VisibilityMonitor() { - var _this = _super.call(this, ['visible']) || this; - var hidden; - var visibilityChange; - if (typeof document !== 'undefined' && - typeof document.addEventListener !== 'undefined') { - if (typeof document['hidden'] !== 'undefined') { - // Opera 12.10 and Firefox 18 and later support - visibilityChange = 'visibilitychange'; - hidden = 'hidden'; - } - else if (typeof document['mozHidden'] !== 'undefined') { - visibilityChange = 'mozvisibilitychange'; - hidden = 'mozHidden'; - } - else if (typeof document['msHidden'] !== 'undefined') { - visibilityChange = 'msvisibilitychange'; - hidden = 'msHidden'; - } - else if (typeof document['webkitHidden'] !== 'undefined') { - visibilityChange = 'webkitvisibilitychange'; - hidden = 'webkitHidden'; - } - } - // Initially, we always assume we are visible. This ensures that in browsers - // without page visibility support or in cases where we are never visible - // (e.g. chrome extension), we act as if we are visible, i.e. don't delay - // reconnects - _this.visible_ = true; - if (visibilityChange) { - document.addEventListener(visibilityChange, function () { - var visible = !document[hidden]; - if (visible !== _this.visible_) { - _this.visible_ = visible; - _this.trigger('visible', visible); - } - }, false); - } - return _this; - } - VisibilityMonitor.getInstance = function () { - return new VisibilityMonitor(); - }; - /** - * @param {!string} eventType - * @return {Array.} - */ - VisibilityMonitor.prototype.getInitialEvent = function (eventType) { - assert(eventType === 'visible', 'Unknown event type: ' + eventType); - return [this.visible_]; - }; - return VisibilityMonitor; -}(EventEmitter)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Monitors online state (as reported by window.online/offline events). - * - * The expectation is that this could have many false positives (thinks we are online - * when we're not), but no false negatives. So we can safely use it to determine when - * we definitely cannot reach the internet. - * - * @extends {EventEmitter} - */ -var OnlineMonitor = /** @class */ (function (_super) { - __extends(OnlineMonitor, _super); - function OnlineMonitor() { - var _this = _super.call(this, ['online']) || this; - _this.online_ = true; - // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. - // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 - // It would seem that the 'online' event does not always fire consistently. So we disable it - // for Cordova. - if (typeof window !== 'undefined' && - typeof window.addEventListener !== 'undefined' && - !isMobileCordova()) { - window.addEventListener('online', function () { - if (!_this.online_) { - _this.online_ = true; - _this.trigger('online', true); - } - }, false); - window.addEventListener('offline', function () { - if (_this.online_) { - _this.online_ = false; - _this.trigger('online', false); - } - }, false); - } - return _this; - } - OnlineMonitor.getInstance = function () { - return new OnlineMonitor(); - }; - /** - * @param {!string} eventType - * @return {Array.} - */ - OnlineMonitor.prototype.getInitialEvent = function (eventType) { - assert(eventType === 'online', 'Unknown event type: ' + eventType); - return [this.online_]; - }; - /** - * @return {boolean} - */ - OnlineMonitor.prototype.currentlyOnline = function () { - return this.online_; - }; - return OnlineMonitor; -}(EventEmitter)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class ensures the packets from the server arrive in order - * This class takes data from the server and ensures it gets passed into the callbacks in order. - * @constructor - */ -var PacketReceiver = /** @class */ (function () { - /** - * @param onMessage_ - */ - function PacketReceiver(onMessage_) { - this.onMessage_ = onMessage_; - this.pendingResponses = []; - this.currentResponseNum = 0; - this.closeAfterResponse = -1; - this.onClose = null; - } - PacketReceiver.prototype.closeAfter = function (responseNum, callback) { - this.closeAfterResponse = responseNum; - this.onClose = callback; - if (this.closeAfterResponse < this.currentResponseNum) { - this.onClose(); - this.onClose = null; - } - }; - /** - * Each message from the server comes with a response number, and an array of data. The responseNumber - * allows us to ensure that we process them in the right order, since we can't be guaranteed that all - * browsers will respond in the same order as the requests we sent - * @param {number} requestNum - * @param {Array} data - */ - PacketReceiver.prototype.handleResponse = function (requestNum, data) { - var _this = this; - this.pendingResponses[requestNum] = data; - var _loop_1 = function () { - var toProcess = this_1.pendingResponses[this_1.currentResponseNum]; - delete this_1.pendingResponses[this_1.currentResponseNum]; - var _loop_2 = function (i) { - if (toProcess[i]) { - exceptionGuard(function () { - _this.onMessage_(toProcess[i]); - }); - } - }; - for (var i = 0; i < toProcess.length; ++i) { - _loop_2(i); - } - if (this_1.currentResponseNum === this_1.closeAfterResponse) { - if (this_1.onClose) { - this_1.onClose(); - this_1.onClose = null; - } - return "break"; - } - this_1.currentResponseNum++; - }; - var this_1 = this; - while (this.pendingResponses[this.currentResponseNum]) { - var state_1 = _loop_1(); - if (state_1 === "break") - break; - } - }; - return PacketReceiver; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// URL query parameters associated with longpolling -var FIREBASE_LONGPOLL_START_PARAM = 'start'; -var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; -var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; -var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; -var FIREBASE_LONGPOLL_ID_PARAM = 'id'; -var FIREBASE_LONGPOLL_PW_PARAM = 'pw'; -var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; -var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; -var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; -var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; -var FIREBASE_LONGPOLL_DATA_PARAM = 'd'; -var FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn'; -var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; -//Data size constants. -//TODO: Perf: the maximum length actually differs from browser to browser. -// We should check what browser we're on and set accordingly. -var MAX_URL_DATA_SIZE = 1870; -var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= -var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; -/** - * Keepalive period - * send a fresh request at minimum every 25 seconds. Opera has a maximum request - * length of 30 seconds that we can't exceed. - * @const - * @type {number} - */ -var KEEPALIVE_REQUEST_INTERVAL = 25000; -/** - * How long to wait before aborting a long-polling connection attempt. - * @const - * @type {number} - */ -var LP_CONNECT_TIMEOUT = 30000; -/** - * This class manages a single long-polling connection. - * - * @constructor - * @implements {Transport} - */ -var BrowserPollConnection = /** @class */ (function () { - /** - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing - * transport session - * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a - * connection previously - */ - function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) { - this.connId = connId; - this.repoInfo = repoInfo; - this.transportSessionId = transportSessionId; - this.lastSessionId = lastSessionId; - this.bytesSent = 0; - this.bytesReceived = 0; - this.everConnected_ = false; - this.log_ = logWrapper(connId); - this.stats_ = StatsManager.getCollection(repoInfo); - this.urlFn = function (params) { - return repoInfo.connectionURL(LONG_POLLING, params); - }; - } - /** - * - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) { - var _this = this; - this.curSegmentNum = 0; - this.onDisconnect_ = onDisconnect; - this.myPacketOrderer = new PacketReceiver(onMessage); - this.isClosed_ = false; - this.connectTimeoutTimer_ = setTimeout(function () { - _this.log_('Timed out trying to connect.'); - // Make sure we clear the host cache - _this.onClosed_(); - _this.connectTimeoutTimer_ = null; - }, Math.floor(LP_CONNECT_TIMEOUT)); - // Ensure we delay the creation of the iframe until the DOM is loaded. - executeWhenDOMReady(function () { - if (_this.isClosed_) - return; - //Set up a callback that gets triggered once a connection is set up. - _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var command = args[0], arg1 = args[1], arg2 = args[2]; - _this.incrementIncomingBytes_(args); - if (!_this.scriptTagHolder) - return; // we closed the connection. - if (_this.connectTimeoutTimer_) { - clearTimeout(_this.connectTimeoutTimer_); - _this.connectTimeoutTimer_ = null; - } - _this.everConnected_ = true; - if (command == FIREBASE_LONGPOLL_START_PARAM) { - _this.id = arg1; - _this.password = arg2; - } - else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { - // Don't clear the host cache. We got a response from the server, so we know it's reachable - if (arg1) { - // We aren't expecting any more data (other than what the server's already in the process of sending us - // through our already open polls), so don't send any more. - _this.scriptTagHolder.sendNewPolls = false; - // arg1 in this case is the last response number sent by the server. We should try to receive - // all of the responses up to this one before closing - _this.myPacketOrderer.closeAfter(arg1, function () { - _this.onClosed_(); - }); - } - else { - _this.onClosed_(); - } - } - else { - throw new Error('Unrecognized command received: ' + command); - } - }, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var pN = args[0], data = args[1]; - _this.incrementIncomingBytes_(args); - _this.myPacketOrderer.handleResponse(pN, data); - }, function () { - _this.onClosed_(); - }, _this.urlFn); - //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results - //from cache. - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); - if (_this.scriptTagHolder.uniqueCallbackIdentifier) - urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier; - urlParams[VERSION_PARAM] = PROTOCOL_VERSION; - if (_this.transportSessionId) { - urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId; - } - if (_this.lastSessionId) { - urlParams[LAST_SESSION_PARAM] = _this.lastSessionId; - } - if (!isNodeSdk() && - typeof location !== 'undefined' && - location.href && - location.href.indexOf(FORGE_DOMAIN) !== -1) { - urlParams[REFERER_PARAM] = FORGE_REF; - } - var connectURL = _this.urlFn(urlParams); - _this.log_('Connecting via long-poll to ' + connectURL); - _this.scriptTagHolder.addTag(connectURL, function () { - /* do nothing */ - }); - }); - }; - /** - * Call this when a handshake has completed successfully and we want to consider the connection established - */ - BrowserPollConnection.prototype.start = function () { - this.scriptTagHolder.startLongPoll(this.id, this.password); - this.addDisconnectPingFrame(this.id, this.password); - }; - /** - * Forces long polling to be considered as a potential transport - */ - BrowserPollConnection.forceAllow = function () { - BrowserPollConnection.forceAllow_ = true; - }; - /** - * Forces longpolling to not be considered as a potential transport - */ - BrowserPollConnection.forceDisallow = function () { - BrowserPollConnection.forceDisallow_ = true; - }; - // Static method, use string literal so it can be accessed in a generic way - BrowserPollConnection.isAvailable = function () { - // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in - // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). - return (BrowserPollConnection.forceAllow_ || - (!BrowserPollConnection.forceDisallow_ && - typeof document !== 'undefined' && - document.createElement != null && - !isChromeExtensionContentScript() && - !isWindowsStoreApp() && - !isNodeSdk())); - }; - /** - * No-op for polling - */ - BrowserPollConnection.prototype.markConnectionHealthy = function () { }; - /** - * Stops polling and cleans up the iframe - * @private - */ - BrowserPollConnection.prototype.shutdown_ = function () { - this.isClosed_ = true; - if (this.scriptTagHolder) { - this.scriptTagHolder.close(); - this.scriptTagHolder = null; - } - //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. - if (this.myDisconnFrame) { - document.body.removeChild(this.myDisconnFrame); - this.myDisconnFrame = null; - } - if (this.connectTimeoutTimer_) { - clearTimeout(this.connectTimeoutTimer_); - this.connectTimeoutTimer_ = null; - } - }; - /** - * Triggered when this transport is closed - * @private - */ - BrowserPollConnection.prototype.onClosed_ = function () { - if (!this.isClosed_) { - this.log_('Longpoll is closing itself'); - this.shutdown_(); - if (this.onDisconnect_) { - this.onDisconnect_(this.everConnected_); - this.onDisconnect_ = null; - } - } - }; - /** - * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server - * that we've left. - */ - BrowserPollConnection.prototype.close = function () { - if (!this.isClosed_) { - this.log_('Longpoll is being closed.'); - this.shutdown_(); - } - }; - /** - * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then - * broken into chunks (since URLs have a small maximum length). - * @param {!Object} data The JSON data to transmit. - */ - BrowserPollConnection.prototype.send = function (data) { - var dataStr = stringify(data); - this.bytesSent += dataStr.length; - this.stats_.incrementCounter('bytes_sent', dataStr.length); - //first, lets get the base64-encoded data - var base64data = base64Encode(dataStr); - //We can only fit a certain amount in each URL, so we need to split this request - //up into multiple pieces if it doesn't fit in one request. - var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); - //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number - //of segments so that we can reassemble the packet on the server. - for (var i = 0; i < dataSegs.length; i++) { - this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); - this.curSegmentNum++; - } - }; - /** - * This is how we notify the server that we're leaving. - * We aren't able to send requests with DHTML on a window close event, but we can - * trigger XHR requests in some browsers (everything but Opera basically). - * @param {!string} id - * @param {!string} pw - */ - BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) { - if (isNodeSdk()) - return; - this.myDisconnFrame = document.createElement('iframe'); - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; - this.myDisconnFrame.src = this.urlFn(urlParams); - this.myDisconnFrame.style.display = 'none'; - document.body.appendChild(this.myDisconnFrame); - }; - /** - * Used to track the bytes received by this client - * @param {*} args - * @private - */ - BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) { - // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. - var bytesReceived = stringify(args).length; - this.bytesReceived += bytesReceived; - this.stats_.incrementCounter('bytes_received', bytesReceived); - }; - return BrowserPollConnection; -}()); -/********************************************************************************************* - * A wrapper around an iframe that is used as a long-polling script holder. - * @constructor - *********************************************************************************************/ -var FirebaseIFrameScriptHolder = /** @class */ (function () { - /** - * @param commandCB - The callback to be called when control commands are recevied from the server. - * @param onMessageCB - The callback to be triggered when responses arrive from the server. - * @param onDisconnect - The callback to be triggered when this tag holder is closed - * @param urlFn - A function that provides the URL of the endpoint to send data to. - */ - function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) { - this.onDisconnect = onDisconnect; - this.urlFn = urlFn; - //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause - //problems in some browsers. - /** - * @type {CountedSet.} - */ - this.outstandingRequests = new CountedSet(); - //A queue of the pending segments waiting for transmission to the server. - this.pendingSegs = []; - //A serial number. We use this for two things: - // 1) A way to ensure the browser doesn't cache responses to polls - // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The - // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute - // JSONP code in the order it was added to the iframe. - this.currentSerial = Math.floor(Math.random() * 100000000); - // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still - // incoming data from the server that we're waiting for). - this.sendNewPolls = true; - if (!isNodeSdk()) { - //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the - //iframes where we put the long-polling script tags. We have two callbacks: - // 1) Command Callback - Triggered for control issues, like starting a connection. - // 2) Message Callback - Triggered when new data arrives. - this.uniqueCallbackIdentifier = LUIDGenerator(); - window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; - window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB; - //Create an iframe for us to add script tags to. - this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); - // Set the iframe's contents. - var script = ''; - // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient - // for ie9, but ie8 needs to do it again in the document itself. - if (this.myIFrame.src && - this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { - var currentDomain = document.domain; - script = ''; - } - var iframeContents = '' + script + ''; - try { - this.myIFrame.doc.open(); - this.myIFrame.doc.write(iframeContents); - this.myIFrame.doc.close(); - } - catch (e) { - log('frame writing exception'); - if (e.stack) { - log(e.stack); - } - log(e); - } - } - else { - this.commandCB = commandCB; - this.onMessageCB = onMessageCB; - } - } - /** - * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can - * actually use. - * @private - * @return {Element} - */ - FirebaseIFrameScriptHolder.createIFrame_ = function () { - var iframe = document.createElement('iframe'); - iframe.style.display = 'none'; - // This is necessary in order to initialize the document inside the iframe - if (document.body) { - document.body.appendChild(iframe); - try { - // If document.domain has been modified in IE, this will throw an error, and we need to set the - // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute - // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. - var a = iframe.contentWindow.document; - if (!a) { - // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. - log('No IE domain setting required'); - } - } - catch (e) { - var domain = document.domain; - iframe.src = - "javascript:void((function(){document.open();document.domain='" + - domain + - "';document.close();})())"; - } - } - else { - // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this - // never gets hit. - throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; - } - // Get the document of the iframe in a browser-specific way. - if (iframe.contentDocument) { - iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari - } - else if (iframe.contentWindow) { - iframe.doc = iframe.contentWindow.document; // Internet Explorer - } - else if (iframe.document) { - iframe.doc = iframe.document; //others? - } - return iframe; - }; - /** - * Cancel all outstanding queries and remove the frame. - */ - FirebaseIFrameScriptHolder.prototype.close = function () { - var _this = this; - //Mark this iframe as dead, so no new requests are sent. - this.alive = false; - if (this.myIFrame) { - //We have to actually remove all of the html inside this iframe before removing it from the - //window, or IE will continue loading and executing the script tags we've already added, which - //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this. - this.myIFrame.doc.body.innerHTML = ''; - setTimeout(function () { - if (_this.myIFrame !== null) { - document.body.removeChild(_this.myIFrame); - _this.myIFrame = null; - } - }, Math.floor(0)); - } - if (isNodeSdk() && this.myID) { - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; - var theURL = this.urlFn(urlParams); - FirebaseIFrameScriptHolder.nodeRestRequest(theURL); - } - // Protect from being called recursively. - var onDisconnect = this.onDisconnect; - if (onDisconnect) { - this.onDisconnect = null; - onDisconnect(); - } - }; - /** - * Actually start the long-polling session by adding the first script tag(s) to the iframe. - * @param {!string} id - The ID of this connection - * @param {!string} pw - The password for this connection - */ - FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) { - this.myID = id; - this.myPW = pw; - this.alive = true; - //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. - while (this.newRequest_()) { } - }; - /** - * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't - * too many outstanding requests and we are still alive. - * - * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if - * needed. - */ - FirebaseIFrameScriptHolder.prototype.newRequest_ = function () { - // We keep one outstanding request open all the time to receive data, but if we need to send data - // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically - // close the old request. - if (this.alive && - this.sendNewPolls && - this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) { - //construct our url - this.currentSerial++; - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; - urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; - var theURL = this.urlFn(urlParams); - //Now add as much data as we can. - var curDataString = ''; - var i = 0; - while (this.pendingSegs.length > 0) { - //first, lets see if the next segment will fit. - var nextSeg = this.pendingSegs[0]; - if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <= - MAX_URL_DATA_SIZE) { - //great, the segment will fit. Lets append it. - var theSeg = this.pendingSegs.shift(); - curDataString = - curDataString + - '&' + - FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + - i + - '=' + - theSeg.seg + - '&' + - FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + - i + - '=' + - theSeg.ts + - '&' + - FIREBASE_LONGPOLL_DATA_PARAM + - i + - '=' + - theSeg.d; - i++; - } - else { - break; - } - } - theURL = theURL + curDataString; - this.addLongPollTag_(theURL, this.currentSerial); - return true; - } - else { - return false; - } - }; - /** - * Queue a packet for transmission to the server. - * @param segnum - A sequential id for this packet segment used for reassembly - * @param totalsegs - The total number of segments in this packet - * @param data - The data for this segment. - */ - FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) { - //add this to the queue of segments to send. - this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); - //send the data immediately if there isn't already data being transmitted, unless - //startLongPoll hasn't been called yet. - if (this.alive) { - this.newRequest_(); - } - }; - /** - * Add a script tag for a regular long-poll request. - * @param {!string} url - The URL of the script tag. - * @param {!number} serial - The serial number of the request. - * @private - */ - FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) { - var _this = this; - //remember that we sent this request. - this.outstandingRequests.add(serial, 1); - var doNewRequest = function () { - _this.outstandingRequests.remove(serial); - _this.newRequest_(); - }; - // If this request doesn't return on its own accord (by the server sending us some data), we'll - // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. - var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); - var readyStateCB = function () { - // Request completed. Cancel the keepalive. - clearTimeout(keepaliveTimeout); - // Trigger a new request so we can continue receiving data. - doNewRequest(); - }; - this.addTag(url, readyStateCB); - }; - /** - * Add an arbitrary script tag to the iframe. - * @param {!string} url - The URL for the script tag source. - * @param {!function()} loadCB - A callback to be triggered once the script has loaded. - */ - FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) { - var _this = this; - if (isNodeSdk()) { - this.doNodeLongPoll(url, loadCB); - } - else { - setTimeout(function () { - try { - // if we're already closed, don't add this poll - if (!_this.sendNewPolls) - return; - var newScript_1 = _this.myIFrame.doc.createElement('script'); - newScript_1.type = 'text/javascript'; - newScript_1.async = true; - newScript_1.src = url; - newScript_1.onload = newScript_1.onreadystatechange = function () { - var rstate = newScript_1.readyState; - if (!rstate || rstate === 'loaded' || rstate === 'complete') { - newScript_1.onload = newScript_1.onreadystatechange = null; - if (newScript_1.parentNode) { - newScript_1.parentNode.removeChild(newScript_1); - } - loadCB(); - } - }; - newScript_1.onerror = function () { - log('Long-poll script failed to load: ' + url); - _this.sendNewPolls = false; - _this.close(); - }; - _this.myIFrame.doc.body.appendChild(newScript_1); - } - catch (e) { - // TODO: we should make this error visible somehow - } - }, Math.floor(1)); - } - }; - return FirebaseIFrameScriptHolder; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var WEBSOCKET_MAX_FRAME_SIZE = 16384; -var WEBSOCKET_KEEPALIVE_INTERVAL = 45000; -var WebSocketImpl = null; -if (typeof MozWebSocket !== 'undefined') { - WebSocketImpl = MozWebSocket; -} -else if (typeof WebSocket !== 'undefined') { - WebSocketImpl = WebSocket; -} -/** - * Create a new websocket connection with the given callbacks. - * @constructor - * @implements {Transport} - */ -var WebSocketConnection = /** @class */ (function () { - /** - * @param {string} connId identifier for this transport - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - */ - function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) { - this.connId = connId; - this.keepaliveTimer = null; - this.frames = null; - this.totalFrames = 0; - this.bytesSent = 0; - this.bytesReceived = 0; - this.log_ = logWrapper(this.connId); - this.stats_ = StatsManager.getCollection(repoInfo); - this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId); - } - /** - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @return {string} connection url - * @private - */ - WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) { - var urlParams = {}; - urlParams[VERSION_PARAM] = PROTOCOL_VERSION; - if (!isNodeSdk() && - typeof location !== 'undefined' && - location.href && - location.href.indexOf(FORGE_DOMAIN) !== -1) { - urlParams[REFERER_PARAM] = FORGE_REF; - } - if (transportSessionId) { - urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; - } - if (lastSessionId) { - urlParams[LAST_SESSION_PARAM] = lastSessionId; - } - return repoInfo.connectionURL(WEBSOCKET, urlParams); - }; - /** - * - * @param onMessage Callback when messages arrive - * @param onDisconnect Callback with connection lost. - */ - WebSocketConnection.prototype.open = function (onMessage, onDisconnect) { - var _this = this; - this.onDisconnect = onDisconnect; - this.onMessage = onMessage; - this.log_('Websocket connecting to ' + this.connURL); - this.everConnected_ = false; - // Assume failure until proven otherwise. - PersistentStorage.set('previous_websocket_failure', true); - try { - if (isNodeSdk()) { - var device = CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node'; - // UA Format: Firebase//// - var options = { - headers: { - 'User-Agent': "Firebase/" + PROTOCOL_VERSION + "/" + firebase.SDK_VERSION + "/" + process.platform + "/" + device - } - }; - // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. - var env = process['env']; - var proxy = this.connURL.indexOf('wss://') == 0 - ? env['HTTPS_PROXY'] || env['https_proxy'] - : env['HTTP_PROXY'] || env['http_proxy']; - if (proxy) { - options['proxy'] = { origin: proxy }; - } - this.mySock = new WebSocketImpl(this.connURL, [], options); - } - else { - this.mySock = new WebSocketImpl(this.connURL); - } - } - catch (e) { - this.log_('Error instantiating WebSocket.'); - var error$$1 = e.message || e.data; - if (error$$1) { - this.log_(error$$1); - } - this.onClosed_(); - return; - } - this.mySock.onopen = function () { - _this.log_('Websocket connected.'); - _this.everConnected_ = true; - }; - this.mySock.onclose = function () { - _this.log_('Websocket connection was disconnected.'); - _this.mySock = null; - _this.onClosed_(); - }; - this.mySock.onmessage = function (m) { - _this.handleIncomingFrame(m); - }; - this.mySock.onerror = function (e) { - _this.log_('WebSocket error. Closing connection.'); - var error$$1 = e.message || e.data; - if (error$$1) { - _this.log_(error$$1); - } - _this.onClosed_(); - }; - }; - /** - * No-op for websockets, we don't need to do anything once the connection is confirmed as open - */ - WebSocketConnection.prototype.start = function () { }; - WebSocketConnection.forceDisallow = function () { - WebSocketConnection.forceDisallow_ = true; - }; - WebSocketConnection.isAvailable = function () { - var isOldAndroid = false; - if (typeof navigator !== 'undefined' && navigator.userAgent) { - var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; - var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); - if (oldAndroidMatch && oldAndroidMatch.length > 1) { - if (parseFloat(oldAndroidMatch[1]) < 4.4) { - isOldAndroid = true; - } - } - } - return (!isOldAndroid && - WebSocketImpl !== null && - !WebSocketConnection.forceDisallow_); - }; - /** - * Returns true if we previously failed to connect with this transport. - * @return {boolean} - */ - WebSocketConnection.previouslyFailed = function () { - // If our persistent storage is actually only in-memory storage, - // we default to assuming that it previously failed to be safe. - return (PersistentStorage.isInMemoryStorage || - PersistentStorage.get('previous_websocket_failure') === true); - }; - WebSocketConnection.prototype.markConnectionHealthy = function () { - PersistentStorage.remove('previous_websocket_failure'); - }; - WebSocketConnection.prototype.appendFrame_ = function (data) { - this.frames.push(data); - if (this.frames.length == this.totalFrames) { - var fullMess = this.frames.join(''); - this.frames = null; - var jsonMess = jsonEval(fullMess); - //handle the message - this.onMessage(jsonMess); - } - }; - /** - * @param {number} frameCount The number of frames we are expecting from the server - * @private - */ - WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) { - this.totalFrames = frameCount; - this.frames = []; - }; - /** - * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 - * @param {!String} data - * @return {?String} Any remaining data to be process, or null if there is none - * @private - */ - WebSocketConnection.prototype.extractFrameCount_ = function (data) { - assert(this.frames === null, 'We already have a frame buffer'); - // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced - // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 - if (data.length <= 6) { - var frameCount = Number(data); - if (!isNaN(frameCount)) { - this.handleNewFrameCount_(frameCount); - return null; - } - } - this.handleNewFrameCount_(1); - return data; - }; - /** - * Process a websocket frame that has arrived from the server. - * @param mess The frame data - */ - WebSocketConnection.prototype.handleIncomingFrame = function (mess) { - if (this.mySock === null) - return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. - var data = mess['data']; - this.bytesReceived += data.length; - this.stats_.incrementCounter('bytes_received', data.length); - this.resetKeepAlive(); - if (this.frames !== null) { - // we're buffering - this.appendFrame_(data); - } - else { - // try to parse out a frame count, otherwise, assume 1 and process it - var remainingData = this.extractFrameCount_(data); - if (remainingData !== null) { - this.appendFrame_(remainingData); - } - } - }; - /** - * Send a message to the server - * @param {Object} data The JSON object to transmit - */ - WebSocketConnection.prototype.send = function (data) { - this.resetKeepAlive(); - var dataStr = stringify(data); - this.bytesSent += dataStr.length; - this.stats_.incrementCounter('bytes_sent', dataStr.length); - //We can only fit a certain amount in each websocket frame, so we need to split this request - //up into multiple pieces if it doesn't fit in one request. - var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); - //Send the length header - if (dataSegs.length > 1) { - this.sendString_(String(dataSegs.length)); - } - //Send the actual data in segments. - for (var i = 0; i < dataSegs.length; i++) { - this.sendString_(dataSegs[i]); - } - }; - WebSocketConnection.prototype.shutdown_ = function () { - this.isClosed_ = true; - if (this.keepaliveTimer) { - clearInterval(this.keepaliveTimer); - this.keepaliveTimer = null; - } - if (this.mySock) { - this.mySock.close(); - this.mySock = null; - } - }; - WebSocketConnection.prototype.onClosed_ = function () { - if (!this.isClosed_) { - this.log_('WebSocket is closing itself'); - this.shutdown_(); - // since this is an internal close, trigger the close listener - if (this.onDisconnect) { - this.onDisconnect(this.everConnected_); - this.onDisconnect = null; - } - } - }; - /** - * External-facing close handler. - * Close the websocket and kill the connection. - */ - WebSocketConnection.prototype.close = function () { - if (!this.isClosed_) { - this.log_('WebSocket is being closed'); - this.shutdown_(); - } - }; - /** - * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after - * the last activity. - */ - WebSocketConnection.prototype.resetKeepAlive = function () { - var _this = this; - clearInterval(this.keepaliveTimer); - this.keepaliveTimer = setInterval(function () { - //If there has been no websocket activity for a while, send a no-op - if (_this.mySock) { - _this.sendString_('0'); - } - _this.resetKeepAlive(); - }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); - }; - /** - * Send a string over the websocket. - * - * @param {string} str String to send. - * @private - */ - WebSocketConnection.prototype.sendString_ = function (str) { - // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() - // calls for some unknown reason. We treat these as an error and disconnect. - // See https://app.asana.com/0/58926111402292/68021340250410 - try { - this.mySock.send(str); - } - catch (e) { - this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); - setTimeout(this.onClosed_.bind(this), 0); - } - }; - /** - * Number of response before we consider the connection "healthy." - * @type {number} - */ - WebSocketConnection.responsesRequiredToBeHealthy = 2; - /** - * Time to wait for the connection te become healthy before giving up. - * @type {number} - */ - WebSocketConnection.healthyTimeout = 30000; - return WebSocketConnection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Currently simplistic, this class manages what transport a Connection should use at various stages of its - * lifecycle. - * - * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if - * they are available. - * @constructor - */ -var TransportManager = /** @class */ (function () { - /** - * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to - */ - function TransportManager(repoInfo) { - this.initTransports_(repoInfo); - } - Object.defineProperty(TransportManager, "ALL_TRANSPORTS", { - /** - * @const - * @type {!Array.} - */ - get: function () { - return [BrowserPollConnection, WebSocketConnection]; - }, - enumerable: true, - configurable: true - }); - /** - * @param {!RepoInfo} repoInfo - * @private - */ - TransportManager.prototype.initTransports_ = function (repoInfo) { - var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); - var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); - if (repoInfo.webSocketOnly) { - if (!isWebSocketsAvailable) - warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); - isSkipPollConnection = true; - } - if (isSkipPollConnection) { - this.transports_ = [WebSocketConnection]; - } - else { - var transports_1 = (this.transports_ = []); - each(TransportManager.ALL_TRANSPORTS, function (i, transport) { - if (transport && transport['isAvailable']()) { - transports_1.push(transport); - } - }); - } - }; - /** - * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the - * initial transport to use - */ - TransportManager.prototype.initialTransport = function () { - if (this.transports_.length > 0) { - return this.transports_[0]; - } - else { - throw new Error('No transports available'); - } - }; - /** - * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next - * transport, or null - */ - TransportManager.prototype.upgradeTransport = function () { - if (this.transports_.length > 1) { - return this.transports_[1]; - } - else { - return null; - } - }; - return TransportManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Abort upgrade attempt if it takes longer than 60s. -var UPGRADE_TIMEOUT = 60000; -// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. -// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. -var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; -// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) -// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout -// but we've sent/received enough bytes, we don't cancel the connection. -var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; -var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; -var MESSAGE_TYPE = 't'; -var MESSAGE_DATA = 'd'; -var CONTROL_SHUTDOWN = 's'; -var CONTROL_RESET = 'r'; -var CONTROL_ERROR = 'e'; -var CONTROL_PONG = 'o'; -var SWITCH_ACK = 'a'; -var END_TRANSMISSION = 'n'; -var PING = 'p'; -var SERVER_HELLO = 'h'; -/** - * Creates a new real-time connection to the server using whichever method works - * best in the current browser. - * - * @constructor - */ -var Connection = /** @class */ (function () { - /** - * @param {!string} id - an id for this connection - * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to - * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives - * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages. - * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost - * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down. - * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server - */ - function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { - this.id = id; - this.repoInfo_ = repoInfo_; - this.onMessage_ = onMessage_; - this.onReady_ = onReady_; - this.onDisconnect_ = onDisconnect_; - this.onKill_ = onKill_; - this.lastSessionId = lastSessionId; - this.connectionCount = 0; - this.pendingDataMessages = []; - this.state_ = 0 /* CONNECTING */; - this.log_ = logWrapper('c:' + this.id + ':'); - this.transportManager_ = new TransportManager(repoInfo_); - this.log_('Connection created'); - this.start_(); - } - /** - * Starts a connection attempt - * @private - */ - Connection.prototype.start_ = function () { - var _this = this; - var conn = this.transportManager_.initialTransport(); - this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId); - // For certain transports (WebSockets), we need to send and receive several messages back and forth before we - // can consider the transport healthy. - this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; - var onMessageReceived = this.connReceiver_(this.conn_); - var onConnectionLost = this.disconnReceiver_(this.conn_); - this.tx_ = this.conn_; - this.rx_ = this.conn_; - this.secondaryConn_ = null; - this.isHealthy_ = false; - /* - * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. - * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. - * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should - * still have the context of your originating frame. - */ - setTimeout(function () { - // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it - _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost); - }, Math.floor(0)); - var healthyTimeout_ms = conn['healthyTimeout'] || 0; - if (healthyTimeout_ms > 0) { - this.healthyTimeout_ = setTimeoutNonBlocking(function () { - _this.healthyTimeout_ = null; - if (!_this.isHealthy_) { - if (_this.conn_ && - _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { - _this.log_('Connection exceeded healthy timeout but has received ' + - _this.conn_.bytesReceived + - ' bytes. Marking connection healthy.'); - _this.isHealthy_ = true; - _this.conn_.markConnectionHealthy(); - } - else if (_this.conn_ && - _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { - _this.log_('Connection exceeded healthy timeout but has sent ' + - _this.conn_.bytesSent + - ' bytes. Leaving connection alive.'); - // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to - // the server. - } - else { - _this.log_('Closing unhealthy connection after timeout.'); - _this.close(); - } - } - }, Math.floor(healthyTimeout_ms)); - } - }; - /** - * @return {!string} - * @private - */ - Connection.prototype.nextTransportId_ = function () { - return 'c:' + this.id + ':' + this.connectionCount++; - }; - Connection.prototype.disconnReceiver_ = function (conn) { - var _this = this; - return function (everConnected) { - if (conn === _this.conn_) { - _this.onConnectionLost_(everConnected); - } - else if (conn === _this.secondaryConn_) { - _this.log_('Secondary connection lost.'); - _this.onSecondaryConnectionLost_(); - } - else { - _this.log_('closing an old connection'); - } - }; - }; - Connection.prototype.connReceiver_ = function (conn) { - var _this = this; - return function (message) { - if (_this.state_ != 2 /* DISCONNECTED */) { - if (conn === _this.rx_) { - _this.onPrimaryMessageReceived_(message); - } - else if (conn === _this.secondaryConn_) { - _this.onSecondaryMessageReceived_(message); - } - else { - _this.log_('message on old connection'); - } - } - }; - }; - /** - * - * @param {Object} dataMsg An arbitrary data message to be sent to the server - */ - Connection.prototype.sendRequest = function (dataMsg) { - // wrap in a data message envelope and send it on - var msg = { t: 'd', d: dataMsg }; - this.sendData_(msg); - }; - Connection.prototype.tryCleanupConnection = function () { - if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { - this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); - this.conn_ = this.secondaryConn_; - this.secondaryConn_ = null; - // the server will shutdown the old connection - } - }; - Connection.prototype.onSecondaryControl_ = function (controlData) { - if (MESSAGE_TYPE in controlData) { - var cmd = controlData[MESSAGE_TYPE]; - if (cmd === SWITCH_ACK) { - this.upgradeIfSecondaryHealthy_(); - } - else if (cmd === CONTROL_RESET) { - // Most likely the session wasn't valid. Abandon the switch attempt - this.log_('Got a reset on secondary, closing it'); - this.secondaryConn_.close(); - // If we were already using this connection for something, than we need to fully close - if (this.tx_ === this.secondaryConn_ || - this.rx_ === this.secondaryConn_) { - this.close(); - } - } - else if (cmd === CONTROL_PONG) { - this.log_('got pong on secondary.'); - this.secondaryResponsesRequired_--; - this.upgradeIfSecondaryHealthy_(); - } - } - }; - Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) { - var layer = requireKey('t', parsedData); - var data = requireKey('d', parsedData); - if (layer == 'c') { - this.onSecondaryControl_(data); - } - else if (layer == 'd') { - // got a data message, but we're still second connection. Need to buffer it up - this.pendingDataMessages.push(data); - } - else { - throw new Error('Unknown protocol layer: ' + layer); - } - }; - Connection.prototype.upgradeIfSecondaryHealthy_ = function () { - if (this.secondaryResponsesRequired_ <= 0) { - this.log_('Secondary connection is healthy.'); - this.isHealthy_ = true; - this.secondaryConn_.markConnectionHealthy(); - this.proceedWithUpgrade_(); - } - else { - // Send a ping to make sure the connection is healthy. - this.log_('sending ping on secondary.'); - this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); - } - }; - Connection.prototype.proceedWithUpgrade_ = function () { - // tell this connection to consider itself open - this.secondaryConn_.start(); - // send ack - this.log_('sending client ack on secondary'); - this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); - // send end packet on primary transport, switch to sending on this one - // can receive on this one, buffer responses until end received on primary transport - this.log_('Ending transmission on primary'); - this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); - this.tx_ = this.secondaryConn_; - this.tryCleanupConnection(); - }; - Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) { - // Must refer to parsedData properties in quotes, so closure doesn't touch them. - var layer = requireKey('t', parsedData); - var data = requireKey('d', parsedData); - if (layer == 'c') { - this.onControl_(data); - } - else if (layer == 'd') { - this.onDataMessage_(data); - } - }; - Connection.prototype.onDataMessage_ = function (message) { - this.onPrimaryResponse_(); - // We don't do anything with data messages, just kick them up a level - this.onMessage_(message); - }; - Connection.prototype.onPrimaryResponse_ = function () { - if (!this.isHealthy_) { - this.primaryResponsesRequired_--; - if (this.primaryResponsesRequired_ <= 0) { - this.log_('Primary connection is healthy.'); - this.isHealthy_ = true; - this.conn_.markConnectionHealthy(); - } - } - }; - Connection.prototype.onControl_ = function (controlData) { - var cmd = requireKey(MESSAGE_TYPE, controlData); - if (MESSAGE_DATA in controlData) { - var payload = controlData[MESSAGE_DATA]; - if (cmd === SERVER_HELLO) { - this.onHandshake_(payload); - } - else if (cmd === END_TRANSMISSION) { - this.log_('recvd end transmission on primary'); - this.rx_ = this.secondaryConn_; - for (var i = 0; i < this.pendingDataMessages.length; ++i) { - this.onDataMessage_(this.pendingDataMessages[i]); - } - this.pendingDataMessages = []; - this.tryCleanupConnection(); - } - else if (cmd === CONTROL_SHUTDOWN) { - // This was previously the 'onKill' callback passed to the lower-level connection - // payload in this case is the reason for the shutdown. Generally a human-readable error - this.onConnectionShutdown_(payload); - } - else if (cmd === CONTROL_RESET) { - // payload in this case is the host we should contact - this.onReset_(payload); - } - else if (cmd === CONTROL_ERROR) { - error('Server Error: ' + payload); - } - else if (cmd === CONTROL_PONG) { - this.log_('got pong on primary.'); - this.onPrimaryResponse_(); - this.sendPingOnPrimaryIfNecessary_(); - } - else { - error('Unknown control packet command: ' + cmd); - } - } - }; - /** - * - * @param {Object} handshake The handshake data returned from the server - * @private - */ - Connection.prototype.onHandshake_ = function (handshake) { - var timestamp = handshake.ts; - var version = handshake.v; - var host = handshake.h; - this.sessionId = handshake.s; - this.repoInfo_.updateHost(host); - // if we've already closed the connection, then don't bother trying to progress further - if (this.state_ == 0 /* CONNECTING */) { - this.conn_.start(); - this.onConnectionEstablished_(this.conn_, timestamp); - if (PROTOCOL_VERSION !== version) { - warn('Protocol version mismatch detected'); - } - // TODO: do we want to upgrade? when? maybe a delay? - this.tryStartUpgrade_(); - } - }; - Connection.prototype.tryStartUpgrade_ = function () { - var conn = this.transportManager_.upgradeTransport(); - if (conn) { - this.startUpgrade_(conn); - } - }; - Connection.prototype.startUpgrade_ = function (conn) { - var _this = this; - this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId); - // For certain transports (WebSockets), we need to send and receive several messages back and forth before we - // can consider the transport healthy. - this.secondaryResponsesRequired_ = - conn['responsesRequiredToBeHealthy'] || 0; - var onMessage = this.connReceiver_(this.secondaryConn_); - var onDisconnect = this.disconnReceiver_(this.secondaryConn_); - this.secondaryConn_.open(onMessage, onDisconnect); - // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. - setTimeoutNonBlocking(function () { - if (_this.secondaryConn_) { - _this.log_('Timed out trying to upgrade.'); - _this.secondaryConn_.close(); - } - }, Math.floor(UPGRADE_TIMEOUT)); - }; - Connection.prototype.onReset_ = function (host) { - this.log_('Reset packet received. New host: ' + host); - this.repoInfo_.updateHost(host); - // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. - // We don't currently support resets after the connection has already been established - if (this.state_ === 1 /* CONNECTED */) { - this.close(); - } - else { - // Close whatever connections we have open and start again. - this.closeConnections_(); - this.start_(); - } - }; - Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) { - var _this = this; - this.log_('Realtime connection established.'); - this.conn_ = conn; - this.state_ = 1 /* CONNECTED */; - if (this.onReady_) { - this.onReady_(timestamp, this.sessionId); - this.onReady_ = null; - } - // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, - // send some pings. - if (this.primaryResponsesRequired_ === 0) { - this.log_('Primary connection is healthy.'); - this.isHealthy_ = true; - } - else { - setTimeoutNonBlocking(function () { - _this.sendPingOnPrimaryIfNecessary_(); - }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); - } - }; - Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () { - // If the connection isn't considered healthy yet, we'll send a noop ping packet request. - if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) { - this.log_('sending ping on primary.'); - this.sendData_({ t: 'c', d: { t: PING, d: {} } }); - } - }; - Connection.prototype.onSecondaryConnectionLost_ = function () { - var conn = this.secondaryConn_; - this.secondaryConn_ = null; - if (this.tx_ === conn || this.rx_ === conn) { - // we are relying on this connection already in some capacity. Therefore, a failure is real - this.close(); - } - }; - /** - * - * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if - * we should flush the host cache - * @private - */ - Connection.prototype.onConnectionLost_ = function (everConnected) { - this.conn_ = null; - // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting - // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. - if (!everConnected && this.state_ === 0 /* CONNECTING */) { - this.log_('Realtime connection failed.'); - // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away - if (this.repoInfo_.isCacheableHost()) { - PersistentStorage.remove('host:' + this.repoInfo_.host); - // reset the internal host to what we would show the user, i.e. .firebaseio.com - this.repoInfo_.internalHost = this.repoInfo_.host; - } - } - else if (this.state_ === 1 /* CONNECTED */) { - this.log_('Realtime connection lost.'); - } - this.close(); - }; - /** - * - * @param {string} reason - * @private - */ - Connection.prototype.onConnectionShutdown_ = function (reason) { - this.log_('Connection shutdown command received. Shutting down...'); - if (this.onKill_) { - this.onKill_(reason); - this.onKill_ = null; - } - // We intentionally don't want to fire onDisconnect (kill is a different case), - // so clear the callback. - this.onDisconnect_ = null; - this.close(); - }; - Connection.prototype.sendData_ = function (data) { - if (this.state_ !== 1 /* CONNECTED */) { - throw 'Connection is not connected'; - } - else { - this.tx_.send(data); - } - }; - /** - * Cleans up this connection, calling the appropriate callbacks - */ - Connection.prototype.close = function () { - if (this.state_ !== 2 /* DISCONNECTED */) { - this.log_('Closing realtime connection.'); - this.state_ = 2 /* DISCONNECTED */; - this.closeConnections_(); - if (this.onDisconnect_) { - this.onDisconnect_(); - this.onDisconnect_ = null; - } - } - }; - /** - * - * @private - */ - Connection.prototype.closeConnections_ = function () { - this.log_('Shutting down all connections'); - if (this.conn_) { - this.conn_.close(); - this.conn_ = null; - } - if (this.secondaryConn_) { - this.secondaryConn_.close(); - this.secondaryConn_ = null; - } - if (this.healthyTimeout_) { - clearTimeout(this.healthyTimeout_); - this.healthyTimeout_ = null; - } - }; - return Connection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Interface defining the set of actions that can be performed against the Firebase server - * (basically corresponds to our wire protocol). - * - * @interface - */ -var ServerActions = /** @class */ (function () { - function ServerActions() { - } - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - * @param {string=} hash - */ - ServerActions.prototype.put = function (pathString, data, onComplete, hash) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, ?string)} onComplete - * @param {string=} hash - */ - ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { }; - /** - * Refreshes the auth token for the current connection. - * @param {string} token The authentication token - */ - ServerActions.prototype.refreshAuthToken = function (token) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { }; - /** - * @param {string} pathString - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { }; - /** - * @param {Object.} stats - */ - ServerActions.prototype.reportStats = function (stats) { }; - return ServerActions; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var RECONNECT_MIN_DELAY = 1000; -var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) -var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) -var RECONNECT_DELAY_MULTIPLIER = 1.3; -var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. -var SERVER_KILL_INTERRUPT_REASON = 'server_kill'; -// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. -var INVALID_AUTH_TOKEN_THRESHOLD = 3; -/** - * Firebase connection. Abstracts wire protocol and handles reconnecting. - * - * NOTE: All JSON objects sent to the realtime connection must have property names enclosed - * in quotes to make sure the closure compiler does not minify them. - */ -var PersistentConnection = /** @class */ (function (_super) { - __extends(PersistentConnection, _super); - /** - * @implements {ServerActions} - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param onConnectStatus_ - * @param onServerInfoUpdate_ - * @param authTokenProvider_ - * @param authOverride_ - */ - function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) { - var _this = _super.call(this) || this; - _this.repoInfo_ = repoInfo_; - _this.onDataUpdate_ = onDataUpdate_; - _this.onConnectStatus_ = onConnectStatus_; - _this.onServerInfoUpdate_ = onServerInfoUpdate_; - _this.authTokenProvider_ = authTokenProvider_; - _this.authOverride_ = authOverride_; - // Used for diagnostic logging. - _this.id = PersistentConnection.nextPersistentConnectionId_++; - _this.log_ = logWrapper('p:' + _this.id + ':'); - /** @private {Object} */ - _this.interruptReasons_ = {}; - _this.listens_ = {}; - _this.outstandingPuts_ = []; - _this.outstandingPutCount_ = 0; - _this.onDisconnectRequestQueue_ = []; - _this.connected_ = false; - _this.reconnectDelay_ = RECONNECT_MIN_DELAY; - _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; - _this.securityDebugCallback_ = null; - _this.lastSessionId = null; - /** @private {number|null} */ - _this.establishConnectionTimer_ = null; - /** @private {boolean} */ - _this.visible_ = false; - // Before we get connected, we keep a queue of pending messages to send. - _this.requestCBHash_ = {}; - _this.requestNumber_ = 0; - /** @private {?{ - * sendRequest(Object), - * close() - * }} */ - _this.realtime_ = null; - /** @private {string|null} */ - _this.authToken_ = null; - _this.forceTokenRefresh_ = false; - _this.invalidAuthTokenCount_ = 0; - _this.firstConnection_ = true; - _this.lastConnectionAttemptTime_ = null; - _this.lastConnectionEstablishedTime_ = null; - if (authOverride_ && !isNodeSdk()) { - throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); - } - _this.scheduleConnect_(0); - VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this); - if (repoInfo_.host.indexOf('fblocal') === -1) { - OnlineMonitor.getInstance().on('online', _this.onOnline_, _this); - } - return _this; - } - /** - * @param {!string} action - * @param {*} body - * @param {function(*)=} onResponse - * @protected - */ - PersistentConnection.prototype.sendRequest = function (action, body, onResponse) { - var curReqNum = ++this.requestNumber_; - var msg = { r: curReqNum, a: action, b: body }; - this.log_(stringify(msg)); - assert(this.connected_, "sendRequest call when we're not connected not allowed."); - this.realtime_.sendRequest(msg); - if (onResponse) { - this.requestCBHash_[curReqNum] = onResponse; - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) { - var queryId = query.queryIdentifier(); - var pathString = query.path.toString(); - this.log_('Listen called for ' + pathString + ' ' + queryId); - this.listens_[pathString] = this.listens_[pathString] || {}; - assert(query.getQueryParams().isDefault() || - !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query'); - assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.'); - var listenSpec = { - onComplete: onComplete, - hashFn: currentHashFn, - query: query, - tag: tag - }; - this.listens_[pathString][queryId] = listenSpec; - if (this.connected_) { - this.sendListen_(listenSpec); - } - }; - /** - * @param {!{onComplete(), - * hashFn():!string, - * query: !Query, - * tag: ?number}} listenSpec - * @private - */ - PersistentConnection.prototype.sendListen_ = function (listenSpec) { - var _this = this; - var query = listenSpec.query; - var pathString = query.path.toString(); - var queryId = query.queryIdentifier(); - this.log_('Listen on ' + pathString + ' for ' + queryId); - var req = { /*path*/ p: pathString }; - var action = 'q'; - // Only bother to send query if it's non-default. - if (listenSpec.tag) { - req['q'] = query.queryObject(); - req['t'] = listenSpec.tag; - } - req[ /*hash*/'h'] = listenSpec.hashFn(); - this.sendRequest(action, req, function (message) { - var payload = message[ /*data*/'d']; - var status = message[ /*status*/'s']; - // print warnings in any case... - PersistentConnection.warnOnListenWarnings_(payload, query); - var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId]; - // only trigger actions if the listen hasn't been removed and readded - if (currentListenSpec === listenSpec) { - _this.log_('listen response', message); - if (status !== 'ok') { - _this.removeListen_(pathString, queryId); - } - if (listenSpec.onComplete) { - listenSpec.onComplete(status, payload); - } - } - }); - }; - /** - * @param {*} payload - * @param {!Query} query - * @private - */ - PersistentConnection.warnOnListenWarnings_ = function (payload, query) { - if (payload && typeof payload === 'object' && contains(payload, 'w')) { - var warnings = safeGet(payload, 'w'); - if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { - var indexSpec = '".indexOn": "' + - query - .getQueryParams() - .getIndex() - .toString() + - '"'; - var indexPath = query.path.toString(); - warn("Using an unspecified index. Your data will be downloaded and " + - ("filtered on the client. Consider adding " + indexSpec + " at ") + - (indexPath + " to your security rules for better performance.")); - } - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.refreshAuthToken = function (token) { - this.authToken_ = token; - this.log_('Auth token refreshed'); - if (this.authToken_) { - this.tryAuth(); - } - else { - //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete - //the credential so we dont become authenticated next time we connect. - if (this.connected_) { - this.sendRequest('unauth', {}, function () { }); - } - } - this.reduceReconnectDelayIfAdminCredential_(token); - }; - /** - * @param {!string} credential - * @private - */ - PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) { - // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). - // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. - var isFirebaseSecret = credential && credential.length === 40; - if (isFirebaseSecret || isAdmin(credential)) { - this.log_('Admin auth credential detected. Reducing max reconnect time.'); - this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; - } - }; - /** - * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like - * a auth revoked (the connection is closed). - */ - PersistentConnection.prototype.tryAuth = function () { - var _this = this; - if (this.connected_ && this.authToken_) { - var token_1 = this.authToken_; - var authMethod = isValidFormat(token_1) ? 'auth' : 'gauth'; - var requestData = { cred: token_1 }; - if (this.authOverride_ === null) { - requestData['noauth'] = true; - } - else if (typeof this.authOverride_ === 'object') { - requestData['authvar'] = this.authOverride_; - } - this.sendRequest(authMethod, requestData, function (res) { - var status = res[ /*status*/'s']; - var data = res[ /*data*/'d'] || 'error'; - if (_this.authToken_ === token_1) { - if (status === 'ok') { - _this.invalidAuthTokenCount_ = 0; - } - else { - // Triggers reconnect and force refresh for auth token - _this.onAuthRevoked_(status, data); - } - } - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.unlisten = function (query, tag) { - var pathString = query.path.toString(); - var queryId = query.queryIdentifier(); - this.log_('Unlisten called for ' + pathString + ' ' + queryId); - assert(query.getQueryParams().isDefault() || - !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query'); - var listen = this.removeListen_(pathString, queryId); - if (listen && this.connected_) { - this.sendUnlisten_(pathString, queryId, query.queryObject(), tag); - } - }; - PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) { - this.log_('Unlisten on ' + pathString + ' for ' + queryId); - var req = { /*path*/ p: pathString }; - var action = 'n'; - // Only bother sending queryId if it's non-default. - if (tag) { - req['q'] = queryObj; - req['t'] = tag; - } - this.sendRequest(action, req); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('o', pathString, data, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'o', - data: data, - onComplete: onComplete - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('om', pathString, data, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'om', - data: data, - onComplete: onComplete - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('oc', pathString, null, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'oc', - data: null, - onComplete: onComplete - }); - } - }; - PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) { - var request = { /*path*/ p: pathString, /*data*/ d: data }; - this.log_('onDisconnect ' + action, request); - this.sendRequest(action, request, function (response) { - if (onComplete) { - setTimeout(function () { - onComplete(response[ /*status*/'s'], response[ /* data */'d']); - }, Math.floor(0)); - } - }); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { - this.putInternal('p', pathString, data, onComplete, hash); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) { - this.putInternal('m', pathString, data, onComplete, hash); - }; - PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) { - var request = { - /*path*/ p: pathString, - /*data*/ d: data - }; - if (hash !== undefined) - request[ /*hash*/'h'] = hash; - // TODO: Only keep track of the most recent put for a given path? - this.outstandingPuts_.push({ - action: action, - request: request, - onComplete: onComplete - }); - this.outstandingPutCount_++; - var index = this.outstandingPuts_.length - 1; - if (this.connected_) { - this.sendPut_(index); - } - else { - this.log_('Buffering put: ' + pathString); - } - }; - PersistentConnection.prototype.sendPut_ = function (index) { - var _this = this; - var action = this.outstandingPuts_[index].action; - var request = this.outstandingPuts_[index].request; - var onComplete = this.outstandingPuts_[index].onComplete; - this.outstandingPuts_[index].queued = this.connected_; - this.sendRequest(action, request, function (message) { - _this.log_(action + ' response', message); - delete _this.outstandingPuts_[index]; - _this.outstandingPutCount_--; - // Clean up array occasionally. - if (_this.outstandingPutCount_ === 0) { - _this.outstandingPuts_ = []; - } - if (onComplete) - onComplete(message[ /*status*/'s'], message[ /* data */'d']); - }); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.reportStats = function (stats) { - var _this = this; - // If we're not connected, we just drop the stats. - if (this.connected_) { - var request = { /*counters*/ c: stats }; - this.log_('reportStats', request); - this.sendRequest(/*stats*/ 's', request, function (result) { - var status = result[ /*status*/'s']; - if (status !== 'ok') { - var errorReason = result[ /* data */'d']; - _this.log_('reportStats', 'Error sending stats: ' + errorReason); - } - }); - } - }; - /** - * @param {*} message - * @private - */ - PersistentConnection.prototype.onDataMessage_ = function (message) { - if ('r' in message) { - // this is a response - this.log_('from server: ' + stringify(message)); - var reqNum = message['r']; - var onResponse = this.requestCBHash_[reqNum]; - if (onResponse) { - delete this.requestCBHash_[reqNum]; - onResponse(message[ /*body*/'b']); - } - } - else if ('error' in message) { - throw 'A server-side error has occurred: ' + message['error']; - } - else if ('a' in message) { - // a and b are action and body, respectively - this.onDataPush_(message['a'], message['b']); - } - }; - PersistentConnection.prototype.onDataPush_ = function (action, body) { - this.log_('handleServerMessage', action, body); - if (action === 'd') - this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], - /*isMerge*/ false, body['t']); - else if (action === 'm') - this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], - /*isMerge=*/ true, body['t']); - else if (action === 'c') - this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); - else if (action === 'ac') - this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); - else if (action === 'sd') - this.onSecurityDebugPacket_(body); - else - error('Unrecognized action received from server: ' + - stringify(action) + - '\nAre you using the latest client?'); - }; - PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) { - this.log_('connection ready'); - this.connected_ = true; - this.lastConnectionEstablishedTime_ = new Date().getTime(); - this.handleTimestamp_(timestamp); - this.lastSessionId = sessionId; - if (this.firstConnection_) { - this.sendConnectStats_(); - } - this.restoreState_(); - this.firstConnection_ = false; - this.onConnectStatus_(true); - }; - PersistentConnection.prototype.scheduleConnect_ = function (timeout) { - var _this = this; - assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); - if (this.establishConnectionTimer_) { - clearTimeout(this.establishConnectionTimer_); - } - // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in - // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). - this.establishConnectionTimer_ = setTimeout(function () { - _this.establishConnectionTimer_ = null; - _this.establishConnection_(); - }, Math.floor(timeout)); - }; - /** - * @param {boolean} visible - * @private - */ - PersistentConnection.prototype.onVisible_ = function (visible) { - // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. - if (visible && - !this.visible_ && - this.reconnectDelay_ === this.maxReconnectDelay_) { - this.log_('Window became visible. Reducing delay.'); - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - this.visible_ = visible; - }; - PersistentConnection.prototype.onOnline_ = function (online) { - if (online) { - this.log_('Browser went online.'); - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - else { - this.log_('Browser went offline. Killing connection.'); - if (this.realtime_) { - this.realtime_.close(); - } - } - }; - PersistentConnection.prototype.onRealtimeDisconnect_ = function () { - this.log_('data client disconnected'); - this.connected_ = false; - this.realtime_ = null; - // Since we don't know if our sent transactions succeeded or not, we need to cancel them. - this.cancelSentTransactions_(); - // Clear out the pending requests. - this.requestCBHash_ = {}; - if (this.shouldReconnect_()) { - if (!this.visible_) { - this.log_("Window isn't visible. Delaying reconnect."); - this.reconnectDelay_ = this.maxReconnectDelay_; - this.lastConnectionAttemptTime_ = new Date().getTime(); - } - else if (this.lastConnectionEstablishedTime_) { - // If we've been connected long enough, reset reconnect delay to minimum. - var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; - if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - this.lastConnectionEstablishedTime_ = null; - } - var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_; - var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); - reconnectDelay = Math.random() * reconnectDelay; - this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); - this.scheduleConnect_(reconnectDelay); - // Adjust reconnect delay for next time. - this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); - } - this.onConnectStatus_(false); - }; - PersistentConnection.prototype.establishConnection_ = function () { - if (this.shouldReconnect_()) { - this.log_('Making a connection attempt'); - this.lastConnectionAttemptTime_ = new Date().getTime(); - this.lastConnectionEstablishedTime_ = null; - var onDataMessage_1 = this.onDataMessage_.bind(this); - var onReady_1 = this.onReady_.bind(this); - var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this); - var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++; - var self_1 = this; - var lastSessionId_1 = this.lastSessionId; - var canceled_1 = false; - var connection_1 = null; - var closeFn_1 = function () { - if (connection_1) { - connection_1.close(); - } - else { - canceled_1 = true; - onDisconnect_1(); - } - }; - var sendRequestFn = function (msg) { - assert(connection_1, "sendRequest call when we're not connected not allowed."); - connection_1.sendRequest(msg); - }; - this.realtime_ = { - close: closeFn_1, - sendRequest: sendRequestFn - }; - var forceRefresh = this.forceTokenRefresh_; - this.forceTokenRefresh_ = false; - // First fetch auth token, and establish connection after fetching the token was successful - this.authTokenProvider_ - .getToken(forceRefresh) - .then(function (result) { - if (!canceled_1) { - log('getToken() completed. Creating connection.'); - self_1.authToken_ = result && result.accessToken; - connection_1 = new Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, - /* onKill= */ function (reason) { - warn(reason + ' (' + self_1.repoInfo_.toString() + ')'); - self_1.interrupt(SERVER_KILL_INTERRUPT_REASON); - }, lastSessionId_1); - } - else { - log('getToken() completed but was canceled'); - } - }) - .then(null, function (error$$1) { - self_1.log_('Failed to get token: ' + error$$1); - if (!canceled_1) { - if (CONSTANTS.NODE_ADMIN) { - // This may be a critical error for the Admin Node.js SDK, so log a warning. - // But getToken() may also just have temporarily failed, so we still want to - // continue retrying. - warn(error$$1); - } - closeFn_1(); - } - }); - } - }; - /** - * @param {string} reason - */ - PersistentConnection.prototype.interrupt = function (reason) { - log('Interrupting connection for reason: ' + reason); - this.interruptReasons_[reason] = true; - if (this.realtime_) { - this.realtime_.close(); - } - else { - if (this.establishConnectionTimer_) { - clearTimeout(this.establishConnectionTimer_); - this.establishConnectionTimer_ = null; - } - if (this.connected_) { - this.onRealtimeDisconnect_(); - } - } - }; - /** - * @param {string} reason - */ - PersistentConnection.prototype.resume = function (reason) { - log('Resuming connection for reason: ' + reason); - delete this.interruptReasons_[reason]; - if (isEmpty(this.interruptReasons_)) { - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - }; - PersistentConnection.prototype.handleTimestamp_ = function (timestamp) { - var delta = timestamp - new Date().getTime(); - this.onServerInfoUpdate_({ serverTimeOffset: delta }); - }; - PersistentConnection.prototype.cancelSentTransactions_ = function () { - for (var i = 0; i < this.outstandingPuts_.length; i++) { - var put = this.outstandingPuts_[i]; - if (put && /*hash*/ 'h' in put.request && put.queued) { - if (put.onComplete) - put.onComplete('disconnect'); - delete this.outstandingPuts_[i]; - this.outstandingPutCount_--; - } - } - // Clean up array occasionally. - if (this.outstandingPutCount_ === 0) - this.outstandingPuts_ = []; - }; - /** - * @param {!string} pathString - * @param {Array.<*>=} query - * @private - */ - PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) { - // Remove the listen and manufacture a "permission_denied" error for the failed listen. - var queryId; - if (!query) { - queryId = 'default'; - } - else { - queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$'); - } - var listen = this.removeListen_(pathString, queryId); - if (listen && listen.onComplete) - listen.onComplete('permission_denied'); - }; - /** - * @param {!string} pathString - * @param {!string} queryId - * @return {{queries:Array., onComplete:function(string)}} - * @private - */ - PersistentConnection.prototype.removeListen_ = function (pathString, queryId) { - var normalizedPathString = new Path(pathString).toString(); // normalize path. - var listen; - if (this.listens_[normalizedPathString] !== undefined) { - listen = this.listens_[normalizedPathString][queryId]; - delete this.listens_[normalizedPathString][queryId]; - if (getCount(this.listens_[normalizedPathString]) === 0) { - delete this.listens_[normalizedPathString]; - } - } - else { - // all listens for this path has already been removed - listen = undefined; - } - return listen; - }; - PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) { - log('Auth token revoked: ' + statusCode + '/' + explanation); - this.authToken_ = null; - this.forceTokenRefresh_ = true; - this.realtime_.close(); - if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { - // We'll wait a couple times before logging the warning / increasing the - // retry period since oauth tokens will report as "invalid" if they're - // just expired. Plus there may be transient issues that resolve themselves. - this.invalidAuthTokenCount_++; - if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) { - // Set a long reconnect delay because recovery is unlikely - this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; - // Notify the auth token provider that the token is invalid, which will log - // a warning - this.authTokenProvider_.notifyForInvalidToken(); - } - } - }; - PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) { - if (this.securityDebugCallback_) { - this.securityDebugCallback_(body); - } - else { - if ('msg' in body) { - console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); - } - } - }; - PersistentConnection.prototype.restoreState_ = function () { - var _this = this; - //Re-authenticate ourselves if we have a credential stored. - this.tryAuth(); - // Puts depend on having received the corresponding data update from the server before they complete, so we must - // make sure to send listens before puts. - forEach(this.listens_, function (pathString, queries) { - forEach(queries, function (key, listenSpec) { - _this.sendListen_(listenSpec); - }); - }); - for (var i = 0; i < this.outstandingPuts_.length; i++) { - if (this.outstandingPuts_[i]) - this.sendPut_(i); - } - while (this.onDisconnectRequestQueue_.length) { - var request = this.onDisconnectRequestQueue_.shift(); - this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); - } - }; - /** - * Sends client stats for first connection - * @private - */ - PersistentConnection.prototype.sendConnectStats_ = function () { - var stats = {}; - var clientName = 'js'; - if (CONSTANTS.NODE_ADMIN) { - clientName = 'admin_node'; - } - else if (CONSTANTS.NODE_CLIENT) { - clientName = 'node'; - } - stats['sdk.' + clientName + '.' + firebase.SDK_VERSION.replace(/\./g, '-')] = 1; - if (isMobileCordova()) { - stats['framework.cordova'] = 1; - } - else if (isReactNative()) { - stats['framework.reactnative'] = 1; - } - this.reportStats(stats); - }; - /** - * @return {boolean} - * @private - */ - PersistentConnection.prototype.shouldReconnect_ = function () { - var online = OnlineMonitor.getInstance().currentlyOnline(); - return isEmpty(this.interruptReasons_) && online; - }; - /** - * @private - */ - PersistentConnection.nextPersistentConnectionId_ = 0; - /** - * Counter for number of connections created. Mainly used for tagging in the logs - * @type {number} - * @private - */ - PersistentConnection.nextConnectionId_ = 0; - return PersistentConnection; -}(ServerActions)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An implementation of ServerActions that communicates with the server via REST requests. - * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full - * persistent connection (using WebSockets or long-polling) - */ -var ReadonlyRestClient = /** @class */ (function (_super) { - __extends(ReadonlyRestClient, _super); - /** - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param {AuthTokenProvider} authTokenProvider_ - * @implements {ServerActions} - */ - function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) { - var _this = _super.call(this) || this; - _this.repoInfo_ = repoInfo_; - _this.onDataUpdate_ = onDataUpdate_; - _this.authTokenProvider_ = authTokenProvider_; - /** @private {function(...[*])} */ - _this.log_ = logWrapper('p:rest:'); - /** - * We don't actually need to track listens, except to prevent us calling an onComplete for a listen - * that's been removed. :-/ - * - * @private {!Object.} - */ - _this.listens_ = {}; - return _this; - } - ReadonlyRestClient.prototype.reportStats = function (stats) { - throw new Error('Method not implemented.'); - }; - /** - * @param {!Query} query - * @param {?number=} tag - * @return {string} - * @private - */ - ReadonlyRestClient.getListenId_ = function (query, tag) { - if (tag !== undefined) { - return 'tag$' + tag; - } - else { - assert(query.getQueryParams().isDefault(), "should have a tag if it's not a default query."); - return query.path.toString(); - } - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) { - var _this = this; - var pathString = query.path.toString(); - this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier()); - // Mark this listener so we can tell if it's removed. - var listenId = ReadonlyRestClient.getListenId_(query, tag); - var thisListen = {}; - this.listens_[listenId] = thisListen; - var queryStringParameters = query - .getQueryParams() - .toRestQueryStringParameters(); - this.restRequest_(pathString + '.json', queryStringParameters, function (error$$1, result) { - var data = result; - if (error$$1 === 404) { - data = null; - error$$1 = null; - } - if (error$$1 === null) { - _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); - } - if (safeGet(_this.listens_, listenId) === thisListen) { - var status_1; - if (!error$$1) { - status_1 = 'ok'; - } - else if (error$$1 == 401) { - status_1 = 'permission_denied'; - } - else { - status_1 = 'rest_error:' + error$$1; - } - onComplete(status_1, null); - } - }); - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.unlisten = function (query, tag) { - var listenId = ReadonlyRestClient.getListenId_(query, tag); - delete this.listens_[listenId]; - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.refreshAuthToken = function (token) { - // no-op since we just always call getToken. - }; - /** - * Performs a REST request to the given path, with the provided query string parameters, - * and any auth credentials we have. - * - * @param {!string} pathString - * @param {!Object.} queryStringParameters - * @param {?function(?number, *=)} callback - * @private - */ - ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) { - var _this = this; - if (queryStringParameters === void 0) { queryStringParameters = {}; } - queryStringParameters['format'] = 'export'; - this.authTokenProvider_ - .getToken(/*forceRefresh=*/ false) - .then(function (authTokenData) { - var authToken = authTokenData && authTokenData.accessToken; - if (authToken) { - queryStringParameters['auth'] = authToken; - } - var url = (_this.repoInfo_.secure ? 'https://' : 'http://') + - _this.repoInfo_.host + - pathString + - '?' + - 'ns=' + - _this.repoInfo_.namespace + - querystring(queryStringParameters); - _this.log_('Sending REST request for ' + url); - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function () { - if (callback && xhr.readyState === 4) { - _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); - var res = null; - if (xhr.status >= 200 && xhr.status < 300) { - try { - res = jsonEval(xhr.responseText); - } - catch (e) { - warn('Failed to parse JSON response for ' + - url + - ': ' + - xhr.responseText); - } - callback(null, res); - } - else { - // 401 and 404 are expected. - if (xhr.status !== 401 && xhr.status !== 404) { - warn('Got unsuccessful REST response for ' + - url + - ' Status: ' + - xhr.status); - } - callback(xhr.status); - } - callback = null; - } - }; - xhr.open('GET', url, /*asynchronous=*/ true); - xhr.send(); - }); - }; - return ReadonlyRestClient; -}(ServerActions)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var INTERRUPT_REASON = 'repo_interrupt'; -/** - * A connection to a single data repository. - */ -var Repo = /** @class */ (function () { - /** - * @param {!RepoInfo} repoInfo_ - * @param {boolean} forceRestClient - * @param {!FirebaseApp} app - */ - function Repo(repoInfo_, forceRestClient, app) { - var _this = this; - this.repoInfo_ = repoInfo_; - this.app = app; - this.dataUpdateCount = 0; - this.statsListener_ = null; - this.eventQueue_ = new EventQueue(); - this.nextWriteId_ = 1; - this.interceptServerDataCallback_ = null; - // A list of data pieces and paths to be set when this client disconnects. - this.onDisconnect_ = new SparseSnapshotTree(); - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @type {?PersistentConnection} - */ - this.persistentConnection_ = null; - /** @type {!AuthTokenProvider} */ - var authTokenProvider = new AuthTokenProvider(app); - this.stats_ = StatsManager.getCollection(repoInfo_); - if (forceRestClient || beingCrawled()) { - this.server_ = new ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider); - // Minor hack: Fire onConnect immediately, since there's no actual connection. - setTimeout(this.onConnectStatus_.bind(this, true), 0); - } - else { - var authOverride = app.options['databaseAuthVariableOverride']; - // Validate authOverride - if (typeof authOverride !== 'undefined' && authOverride !== null) { - if (typeof authOverride !== 'object') { - throw new Error('Only objects are supported for option databaseAuthVariableOverride'); - } - try { - stringify(authOverride); - } - catch (e) { - throw new Error('Invalid authOverride provided: ' + e); - } - } - this.persistentConnection_ = new PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride); - this.server_ = this.persistentConnection_; - } - authTokenProvider.addTokenChangeListener(function (token) { - _this.server_.refreshAuthToken(token); - }); - // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), - // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. - this.statsReporter_ = StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter(_this.stats_, _this.server_); }); - this.transactions_init_(); - // Used for .info. - this.infoData_ = new SnapshotHolder(); - this.infoSyncTree_ = new SyncTree({ - startListening: function (query, tag, currentHashFn, onComplete) { - var infoEvents = []; - var node = _this.infoData_.getNode(query.path); - // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events - // on initial data... - if (!node.isEmpty()) { - infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node); - setTimeout(function () { - onComplete('ok'); - }, 0); - } - return infoEvents; - }, - stopListening: function () { } - }); - this.updateInfo_('connected', false); - this.serverSyncTree_ = new SyncTree({ - startListening: function (query, tag, currentHashFn, onComplete) { - _this.server_.listen(query, currentHashFn, tag, function (status, data) { - var events = onComplete(status, data); - _this.eventQueue_.raiseEventsForChangedPath(query.path, events); - }); - // No synchronous events for network-backed sync trees - return []; - }, - stopListening: function (query, tag) { - _this.server_.unlisten(query, tag); - } - }); - } - /** - * @return {string} The URL corresponding to the root of this Firebase. - */ - Repo.prototype.toString = function () { - return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); - }; - /** - * @return {!string} The namespace represented by the repo. - */ - Repo.prototype.name = function () { - return this.repoInfo_.namespace; - }; - /** - * @return {!number} The time in milliseconds, taking the server offset into account if we have one. - */ - Repo.prototype.serverTime = function () { - var offsetNode = this.infoData_.getNode(new Path('.info/serverTimeOffset')); - var offset = offsetNode.val() || 0; - return new Date().getTime() + offset; - }; - /** - * Generate ServerValues using some variables from the repo object. - * @return {!Object} - */ - Repo.prototype.generateServerValues = function () { - return generateWithValues({ - timestamp: this.serverTime() - }); - }; - /** - * Called by realtime when we get new messages from the server. - * - * @private - * @param {string} pathString - * @param {*} data - * @param {boolean} isMerge - * @param {?number} tag - */ - Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) { - // For testing. - this.dataUpdateCount++; - var path = new Path(pathString); - data = this.interceptServerDataCallback_ - ? this.interceptServerDataCallback_(pathString, data) - : data; - var events = []; - if (tag) { - if (isMerge) { - var taggedChildren = map(data, function (raw) { - return nodeFromJSON$1(raw); - }); - events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag); - } - else { - var taggedSnap = nodeFromJSON$1(data); - events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag); - } - } - else if (isMerge) { - var changedChildren = map(data, function (raw) { - return nodeFromJSON$1(raw); - }); - events = this.serverSyncTree_.applyServerMerge(path, changedChildren); - } - else { - var snap = nodeFromJSON$1(data); - events = this.serverSyncTree_.applyServerOverwrite(path, snap); - } - var affectedPath = path; - if (events.length > 0) { - // Since we have a listener outstanding for each transaction, receiving any events - // is a proxy for some change having occurred. - affectedPath = this.rerunTransactions_(path); - } - this.eventQueue_.raiseEventsForChangedPath(affectedPath, events); - }; - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @param {?function(!string, *):*} callback - * @private - */ - Repo.prototype.interceptServerData_ = function (callback) { - this.interceptServerDataCallback_ = callback; - }; - /** - * @param {!boolean} connectStatus - * @private - */ - Repo.prototype.onConnectStatus_ = function (connectStatus) { - this.updateInfo_('connected', connectStatus); - if (connectStatus === false) { - this.runOnDisconnectEvents_(); - } - }; - /** - * @param {!Object} updates - * @private - */ - Repo.prototype.onServerInfoUpdate_ = function (updates) { - var _this = this; - each(updates, function (value, key) { - _this.updateInfo_(key, value); - }); - }; - /** - * - * @param {!string} pathString - * @param {*} value - * @private - */ - Repo.prototype.updateInfo_ = function (pathString, value) { - var path = new Path('/.info/' + pathString); - var newNode = nodeFromJSON$1(value); - this.infoData_.updateSnapshot(path, newNode); - var events = this.infoSyncTree_.applyServerOverwrite(path, newNode); - this.eventQueue_.raiseEventsForChangedPath(path, events); - }; - /** - * @return {!number} - * @private - */ - Repo.prototype.getNextWriteId_ = function () { - return this.nextWriteId_++; - }; - /** - * @param {!Path} path - * @param {*} newVal - * @param {number|string|null} newPriority - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) { - var _this = this; - this.log_('set', { - path: path.toString(), - value: newVal, - priority: newPriority - }); - // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or - // (b) store unresolved paths on JSON parse - var serverValues = this.generateServerValues(); - var newNodeUnresolved = nodeFromJSON$1(newVal, newPriority); - var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - var writeId = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true); - this.eventQueue_.queueEvents(events); - this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) { - var success = status === 'ok'; - if (!success) { - warn('set at ' + path + ' failed: ' + status); - } - var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success); - _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents); - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - var affectedPath = this.abortTransactions_(path); - this.rerunTransactions_(affectedPath); - // We queued the events above, so just flush the queue here - this.eventQueue_.raiseEventsForChangedPath(affectedPath, []); - }; - /** - * @param {!Path} path - * @param {!Object} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.update = function (path, childrenToMerge, onComplete) { - var _this = this; - this.log_('update', { path: path.toString(), value: childrenToMerge }); - // Start with our existing data and merge each child into it. - var empty = true; - var serverValues = this.generateServerValues(); - var changedChildren = {}; - forEach(childrenToMerge, function (changedKey, changedValue) { - empty = false; - var newNodeUnresolved = nodeFromJSON$1(changedValue); - changedChildren[changedKey] = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - }); - if (!empty) { - var writeId_1 = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1); - this.eventQueue_.queueEvents(events); - this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) { - var success = status === 'ok'; - if (!success) { - warn('update at ' + path + ' failed: ' + status); - } - var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success); - var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path; - _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents); - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - forEach(childrenToMerge, function (changedPath) { - var affectedPath = _this.abortTransactions_(path.child(changedPath)); - _this.rerunTransactions_(affectedPath); - }); - // We queued the events above, so just flush the queue here - this.eventQueue_.raiseEventsForChangedPath(path, []); - } - else { - log("update() called with empty data. Don't do anything."); - this.callOnCompleteCallback(onComplete, 'ok'); - } - }; - /** - * Applies all of the changes stored up in the onDisconnect_ tree. - * @private - */ - Repo.prototype.runOnDisconnectEvents_ = function () { - var _this = this; - this.log_('onDisconnectEvents'); - var serverValues = this.generateServerValues(); - var resolvedOnDisconnectTree = resolveDeferredValueTree(this.onDisconnect_, serverValues); - var events = []; - resolvedOnDisconnectTree.forEachTree(Path.Empty, function (path, snap) { - events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap)); - var affectedPath = _this.abortTransactions_(path); - _this.rerunTransactions_(affectedPath); - }); - this.onDisconnect_ = new SparseSnapshotTree(); - this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events); - }; - /** - * @param {!Path} path - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectCancel = function (path, onComplete) { - var _this = this; - this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.forget(path); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} value - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectSet = function (path, value, onComplete) { - var _this = this; - var newNode = nodeFromJSON$1(value); - this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.remember(path, newNode); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} value - * @param {*} priority - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) { - var _this = this; - var newNode = nodeFromJSON$1(value, priority); - this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.remember(path, newNode); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) { - var _this = this; - if (isEmpty(childrenToMerge)) { - log("onDisconnect().update() called with empty data. Don't do anything."); - this.callOnCompleteCallback(onComplete, 'ok'); - return; - } - this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) { - if (status === 'ok') { - forEach(childrenToMerge, function (childName, childNode) { - var newChildNode = nodeFromJSON$1(childNode); - _this.onDisconnect_.remember(path.child(childName), newChildNode); - }); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - */ - Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) { - var events; - if (query.path.getFront() === '.info') { - events = this.infoSyncTree_.addEventRegistration(query, eventRegistration); - } - else { - events = this.serverSyncTree_.addEventRegistration(query, eventRegistration); - } - this.eventQueue_.raiseEventsAtPath(query.path, events); - }; - /** - * @param {!Query} query - * @param {?EventRegistration} eventRegistration - */ - Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) { - // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof - // a little bit by handling the return values anyways. - var events; - if (query.path.getFront() === '.info') { - events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration); - } - else { - events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration); - } - this.eventQueue_.raiseEventsAtPath(query.path, events); - }; - Repo.prototype.interrupt = function () { - if (this.persistentConnection_) { - this.persistentConnection_.interrupt(INTERRUPT_REASON); - } - }; - Repo.prototype.resume = function () { - if (this.persistentConnection_) { - this.persistentConnection_.resume(INTERRUPT_REASON); - } - }; - Repo.prototype.stats = function (showDelta) { - if (showDelta === void 0) { showDelta = false; } - if (typeof console === 'undefined') - return; - var stats; - if (showDelta) { - if (!this.statsListener_) - this.statsListener_ = new StatsListener(this.stats_); - stats = this.statsListener_.get(); - } - else { - stats = this.stats_.get(); - } - var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) { - return Math.max(currentValue.length, previousValue); - }, 0); - forEach(stats, function (stat, value) { - // pad stat names to be the same length (plus 2 extra spaces). - for (var i = stat.length; i < longestName + 2; i++) - stat += ' '; - console.log(stat + value); - }); - }; - Repo.prototype.statsIncrementCounter = function (metric) { - this.stats_.incrementCounter(metric); - this.statsReporter_.includeStat(metric); - }; - /** - * @param {...*} var_args - * @private - */ - Repo.prototype.log_ = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var prefix = ''; - if (this.persistentConnection_) { - prefix = this.persistentConnection_.id + ':'; - } - log.apply(void 0, [prefix].concat(var_args)); - }; - /** - * @param {?function(?Error, *=)} callback - * @param {!string} status - * @param {?string=} errorReason - */ - Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) { - if (callback) { - exceptionGuard(function () { - if (status == 'ok') { - callback(null); - } - else { - var code = (status || 'error').toUpperCase(); - var message = code; - if (errorReason) - message += ': ' + errorReason; - var error$$1 = new Error(message); - error$$1.code = code; - callback(error$$1); - } - }); - } - }; - Object.defineProperty(Repo.prototype, "database", { - get: function () { - return this.__database || (this.__database = new Database(this)); - }, - enumerable: true, - configurable: true - }); - return Repo; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node - * - * @constructor - * @implements {NodeFilter} - */ -var RangedFilter = /** @class */ (function () { - /** - * @param {!QueryParams} params - */ - function RangedFilter(params) { - this.indexedFilter_ = new IndexedFilter(params.getIndex()); - this.index_ = params.getIndex(); - this.startPost_ = RangedFilter.getStartPost_(params); - this.endPost_ = RangedFilter.getEndPost_(params); - } - /** - * @return {!NamedNode} - */ - RangedFilter.prototype.getStartPost = function () { - return this.startPost_; - }; - /** - * @return {!NamedNode} - */ - RangedFilter.prototype.getEndPost = function () { - return this.endPost_; - }; - /** - * @param {!NamedNode} node - * @return {boolean} - */ - RangedFilter.prototype.matches = function (node) { - return (this.index_.compare(this.getStartPost(), node) <= 0 && - this.index_.compare(node, this.getEndPost()) <= 0); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - if (!this.matches(new NamedNode(key, newChild))) { - newChild = ChildrenNode.EMPTY_NODE; - } - return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - if (newSnap.isLeafNode()) { - // Make sure we have a children node with the correct index, not a leaf node; - newSnap = ChildrenNode.EMPTY_NODE; - } - var filtered = newSnap.withIndex(this.index_); - // Don't support priorities on queries - filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); - var self = this; - newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (!self.matches(new NamedNode(key, childNode))) { - filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); - } - }); - return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - // Don't support priorities on queries - return oldSnap; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.filtersNodes = function () { - return true; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.getIndexedFilter = function () { - return this.indexedFilter_; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.getIndex = function () { - return this.index_; - }; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - RangedFilter.getStartPost_ = function (params) { - if (params.hasStart()) { - var startName = params.getIndexStartName(); - return params.getIndex().makePost(params.getIndexStartValue(), startName); - } - else { - return params.getIndex().minPost(); - } - }; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - RangedFilter.getEndPost_ = function (params) { - if (params.hasEnd()) { - var endName = params.getIndexEndName(); - return params.getIndex().makePost(params.getIndexEndValue(), endName); - } - else { - return params.getIndex().maxPost(); - } - }; - return RangedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible - * - * @constructor - * @implements {NodeFilter} - */ -var LimitedFilter = /** @class */ (function () { - /** - * @param {!QueryParams} params - */ - function LimitedFilter(params) { - this.rangedFilter_ = new RangedFilter(params); - this.index_ = params.getIndex(); - this.limit_ = params.getLimit(); - this.reverse_ = !params.isViewFromLeft(); - } - /** - * @inheritDoc - */ - LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { - newChild = ChildrenNode.EMPTY_NODE; - } - if (snap.getImmediateChild(key).equals(newChild)) { - // No change - return snap; - } - else if (snap.numChildren() < this.limit_) { - return this.rangedFilter_ - .getIndexedFilter() - .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); - } - else { - return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); - } - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - var filtered; - if (newSnap.isLeafNode() || newSnap.isEmpty()) { - // Make sure we have a children node with the correct index, not a leaf node; - filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); - } - else { - if (this.limit_ * 2 < newSnap.numChildren() && - newSnap.isIndexed(this.index_)) { - // Easier to build up a snapshot, since what we're given has more than twice the elements we want - filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); - // anchor to the startPost, endPost, or last element as appropriate - var iterator = void 0; - if (this.reverse_) { - iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); - } - else { - iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); - } - var count = 0; - while (iterator.hasNext() && count < this.limit_) { - var next = iterator.getNext(); - var inRange = void 0; - if (this.reverse_) { - inRange = - this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0; - } - else { - inRange = - this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0; - } - if (inRange) { - filtered = filtered.updateImmediateChild(next.name, next.node); - count++; - } - else { - // if we have reached the end post, we cannot keep adding elemments - break; - } - } - } - else { - // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one - filtered = newSnap.withIndex(this.index_); - // Don't support priorities on queries - filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); - var startPost = void 0; - var endPost = void 0; - var cmp = void 0; - var iterator = void 0; - if (this.reverse_) { - iterator = filtered.getReverseIterator(this.index_); - startPost = this.rangedFilter_.getEndPost(); - endPost = this.rangedFilter_.getStartPost(); - var indexCompare_1 = this.index_.getCompare(); - cmp = function (a, b) { return indexCompare_1(b, a); }; - } - else { - iterator = filtered.getIterator(this.index_); - startPost = this.rangedFilter_.getStartPost(); - endPost = this.rangedFilter_.getEndPost(); - cmp = this.index_.getCompare(); - } - var count = 0; - var foundStartPost = false; - while (iterator.hasNext()) { - var next = iterator.getNext(); - if (!foundStartPost && cmp(startPost, next) <= 0) { - // start adding - foundStartPost = true; - } - var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0; - if (inRange) { - count++; - } - else { - filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); - } - } - } - } - return this.rangedFilter_ - .getIndexedFilter() - .updateFullNode(oldSnap, filtered, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - // Don't support priorities on queries - return oldSnap; - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.filtersNodes = function () { - return true; - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.getIndexedFilter = function () { - return this.rangedFilter_.getIndexedFilter(); - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.getIndex = function () { - return this.index_; - }; - /** - * @param {!Node} snap - * @param {string} childKey - * @param {!Node} childSnap - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} changeAccumulator - * @return {!Node} - * @private - */ - LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) { - // TODO: rename all cache stuff etc to general snap terminology - var cmp; - if (this.reverse_) { - var indexCmp_1 = this.index_.getCompare(); - cmp = function (a, b) { return indexCmp_1(b, a); }; - } - else { - cmp = this.index_.getCompare(); - } - var oldEventCache = snap; - assert(oldEventCache.numChildren() == this.limit_, ''); - var newChildNamedNode = new NamedNode(childKey, childSnap); - var windowBoundary = this.reverse_ - ? oldEventCache.getFirstChild(this.index_) - : oldEventCache.getLastChild(this.index_); - var inRange = this.rangedFilter_.matches(newChildNamedNode); - if (oldEventCache.hasChild(childKey)) { - var oldChildSnap = oldEventCache.getImmediateChild(childKey); - var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); - while (nextChild != null && - (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) { - // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't - // been applied to the limited filter yet. Ignore this next child which will be updated later in - // the limited filter... - nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); - } - var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); - var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; - if (remainsInWindow) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childChangedChange(childKey, childSnap, oldChildSnap)); - } - return oldEventCache.updateImmediateChild(childKey, childSnap); - } - else { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childRemovedChange(childKey, oldChildSnap)); - } - var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); - var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); - if (nextChildInRange) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childAddedChange(nextChild.name, nextChild.node)); - } - return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); - } - else { - return newEventCache; - } - } - } - else if (childSnap.isEmpty()) { - // we're deleting a node, but it was not in the window, so ignore it - return snap; - } - else if (inRange) { - if (cmp(windowBoundary, newChildNamedNode) >= 0) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childRemovedChange(windowBoundary.name, windowBoundary.node)); - changeAccumulator.trackChildChange(Change.childAddedChange(childKey, childSnap)); - } - return oldEventCache - .updateImmediateChild(childKey, childSnap) - .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); - } - else { - return snap; - } - } - else { - return snap; - } - }; - return LimitedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a - * range to be returned for a particular location. It is assumed that validation of parameters is done at the - * user-facing API level, so it is not done here. - * @constructor - */ -var QueryParams = /** @class */ (function () { - function QueryParams() { - this.limitSet_ = false; - this.startSet_ = false; - this.startNameSet_ = false; - this.endSet_ = false; - this.endNameSet_ = false; - this.limit_ = 0; - this.viewFrom_ = ''; - this.indexStartValue_ = null; - this.indexStartName_ = ''; - this.indexEndValue_ = null; - this.indexEndName_ = ''; - this.index_ = PRIORITY_INDEX; - } - /** - * @return {boolean} - */ - QueryParams.prototype.hasStart = function () { - return this.startSet_; - }; - /** - * @return {boolean} True if it would return from left. - */ - QueryParams.prototype.isViewFromLeft = function () { - if (this.viewFrom_ === '') { - // limit(), rather than limitToFirst or limitToLast was called. - // This means that only one of startSet_ and endSet_ is true. Use them - // to calculate which side of the view to anchor to. If neither is set, - // anchor to the end. - return this.startSet_; - } - else { - return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT); - } - }; - /** - * Only valid to call if hasStart() returns true - * @return {*} - */ - QueryParams.prototype.getIndexStartValue = function () { - assert(this.startSet_, 'Only valid if start has been set'); - return this.indexStartValue_; - }; - /** - * Only valid to call if hasStart() returns true. - * Returns the starting key name for the range defined by these query parameters - * @return {!string} - */ - QueryParams.prototype.getIndexStartName = function () { - assert(this.startSet_, 'Only valid if start has been set'); - if (this.startNameSet_) { - return this.indexStartName_; - } - else { - return MIN_NAME; - } - }; - /** - * @return {boolean} - */ - QueryParams.prototype.hasEnd = function () { - return this.endSet_; - }; - /** - * Only valid to call if hasEnd() returns true. - * @return {*} - */ - QueryParams.prototype.getIndexEndValue = function () { - assert(this.endSet_, 'Only valid if end has been set'); - return this.indexEndValue_; - }; - /** - * Only valid to call if hasEnd() returns true. - * Returns the end key name for the range defined by these query parameters - * @return {!string} - */ - QueryParams.prototype.getIndexEndName = function () { - assert(this.endSet_, 'Only valid if end has been set'); - if (this.endNameSet_) { - return this.indexEndName_; - } - else { - return MAX_NAME; - } - }; - /** - * @return {boolean} - */ - QueryParams.prototype.hasLimit = function () { - return this.limitSet_; - }; - /** - * @return {boolean} True if a limit has been set and it has been explicitly anchored - */ - QueryParams.prototype.hasAnchoredLimit = function () { - return this.limitSet_ && this.viewFrom_ !== ''; - }; - /** - * Only valid to call if hasLimit() returns true - * @return {!number} - */ - QueryParams.prototype.getLimit = function () { - assert(this.limitSet_, 'Only valid if limit has been set'); - return this.limit_; - }; - /** - * @return {!Index} - */ - QueryParams.prototype.getIndex = function () { - return this.index_; - }; - /** - * @return {!QueryParams} - * @private - */ - QueryParams.prototype.copy_ = function () { - var copy = new QueryParams(); - copy.limitSet_ = this.limitSet_; - copy.limit_ = this.limit_; - copy.startSet_ = this.startSet_; - copy.indexStartValue_ = this.indexStartValue_; - copy.startNameSet_ = this.startNameSet_; - copy.indexStartName_ = this.indexStartName_; - copy.endSet_ = this.endSet_; - copy.indexEndValue_ = this.indexEndValue_; - copy.endNameSet_ = this.endNameSet_; - copy.indexEndName_ = this.indexEndName_; - copy.index_ = this.index_; - copy.viewFrom_ = this.viewFrom_; - return copy; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limit = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = ''; - return newParams; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limitToFirst = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT; - return newParams; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limitToLast = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT; - return newParams; - }; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - QueryParams.prototype.startAt = function (indexValue, key) { - var newParams = this.copy_(); - newParams.startSet_ = true; - if (!(indexValue !== undefined)) { - indexValue = null; - } - newParams.indexStartValue_ = indexValue; - if (key != null) { - newParams.startNameSet_ = true; - newParams.indexStartName_ = key; - } - else { - newParams.startNameSet_ = false; - newParams.indexStartName_ = ''; - } - return newParams; - }; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - QueryParams.prototype.endAt = function (indexValue, key) { - var newParams = this.copy_(); - newParams.endSet_ = true; - if (!(indexValue !== undefined)) { - indexValue = null; - } - newParams.indexEndValue_ = indexValue; - if (key !== undefined) { - newParams.endNameSet_ = true; - newParams.indexEndName_ = key; - } - else { - newParams.endNameSet_ = false; - newParams.indexEndName_ = ''; - } - return newParams; - }; - /** - * @param {!Index} index - * @return {!QueryParams} - */ - QueryParams.prototype.orderBy = function (index) { - var newParams = this.copy_(); - newParams.index_ = index; - return newParams; - }; - /** - * @return {!Object} - */ - QueryParams.prototype.getQueryObject = function () { - var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_; - var obj = {}; - if (this.startSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_; - if (this.startNameSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_; - } - } - if (this.endSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_; - if (this.endNameSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_; - } - } - if (this.limitSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_; - var viewFrom = this.viewFrom_; - if (viewFrom === '') { - if (this.isViewFromLeft()) { - viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT; - } - else { - viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT; - } - } - obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom; - } - // For now, priority index is the default, so we only specify if it's some other index - if (this.index_ !== PRIORITY_INDEX) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString(); - } - return obj; - }; - /** - * @return {boolean} - */ - QueryParams.prototype.loadsAllData = function () { - return !(this.startSet_ || this.endSet_ || this.limitSet_); - }; - /** - * @return {boolean} - */ - QueryParams.prototype.isDefault = function () { - return this.loadsAllData() && this.index_ == PRIORITY_INDEX; - }; - /** - * @return {!NodeFilter} - */ - QueryParams.prototype.getNodeFilter = function () { - if (this.loadsAllData()) { - return new IndexedFilter(this.getIndex()); - } - else if (this.hasLimit()) { - return new LimitedFilter(this); - } - else { - return new RangedFilter(this); - } - }; - /** - * Returns a set of REST query string parameters representing this query. - * - * @return {!Object.} query string parameters - */ - QueryParams.prototype.toRestQueryStringParameters = function () { - var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_; - var qs = {}; - if (this.isDefault()) { - return qs; - } - var orderBy; - if (this.index_ === PRIORITY_INDEX) { - orderBy = REST_CONSTANTS.PRIORITY_INDEX; - } - else if (this.index_ === VALUE_INDEX) { - orderBy = REST_CONSTANTS.VALUE_INDEX; - } - else if (this.index_ === KEY_INDEX) { - orderBy = REST_CONSTANTS.KEY_INDEX; - } - else { - assert(this.index_ instanceof PathIndex, 'Unrecognized index type!'); - orderBy = this.index_.toString(); - } - qs[REST_CONSTANTS.ORDER_BY] = stringify(orderBy); - if (this.startSet_) { - qs[REST_CONSTANTS.START_AT] = stringify(this.indexStartValue_); - if (this.startNameSet_) { - qs[REST_CONSTANTS.START_AT] += ',' + stringify(this.indexStartName_); - } - } - if (this.endSet_) { - qs[REST_CONSTANTS.END_AT] = stringify(this.indexEndValue_); - if (this.endNameSet_) { - qs[REST_CONSTANTS.END_AT] += ',' + stringify(this.indexEndName_); - } - } - if (this.limitSet_) { - if (this.isViewFromLeft()) { - qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_; - } - else { - qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_; - } - } - return qs; - }; - /** - * Wire Protocol Constants - * @const - * @enum {string} - * @private - */ - QueryParams.WIRE_PROTOCOL_CONSTANTS_ = { - INDEX_START_VALUE: 'sp', - INDEX_START_NAME: 'sn', - INDEX_END_VALUE: 'ep', - INDEX_END_NAME: 'en', - LIMIT: 'l', - VIEW_FROM: 'vf', - VIEW_FROM_LEFT: 'l', - VIEW_FROM_RIGHT: 'r', - INDEX: 'i' - }; - /** - * REST Query Constants - * @const - * @enum {string} - * @private - */ - QueryParams.REST_QUERY_CONSTANTS_ = { - ORDER_BY: 'orderBy', - PRIORITY_INDEX: '$priority', - VALUE_INDEX: '$value', - KEY_INDEX: '$key', - START_AT: 'startAt', - END_AT: 'endAt', - LIMIT_TO_FIRST: 'limitToFirst', - LIMIT_TO_LAST: 'limitToLast' - }; - /** - * Default, empty query parameters - * @type {!QueryParams} - * @const - */ - QueryParams.DEFAULT = new QueryParams(); - return QueryParams; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Reference = /** @class */ (function (_super) { - __extends(Reference, _super); - /** - * Call options: - * new Reference(Repo, Path) or - * new Reference(url: string, string|RepoManager) - * - * Externally - this is the firebase.database.Reference type. - * - * @param {!Repo} repo - * @param {(!Path)} path - * @extends {Query} - */ - function Reference(repo, path) { - var _this = this; - if (!(repo instanceof Repo)) { - throw new Error('new Reference() no longer supported - use app.database().'); - } - // call Query's constructor, passing in the repo and path. - _this = _super.call(this, repo, path, QueryParams.DEFAULT, false) || this; - return _this; - } - /** @return {?string} */ - Reference.prototype.getKey = function () { - validateArgCount('Reference.key', 0, 0, arguments.length); - if (this.path.isEmpty()) - return null; - else - return this.path.getBack(); - }; - /** - * @param {!(string|Path)} pathString - * @return {!Reference} - */ - Reference.prototype.child = function (pathString) { - validateArgCount('Reference.child', 1, 1, arguments.length); - if (typeof pathString === 'number') { - pathString = String(pathString); - } - else if (!(pathString instanceof Path)) { - if (this.path.getFront() === null) - validateRootPathString('Reference.child', 1, pathString, false); - else - validatePathString('Reference.child', 1, pathString, false); - } - return new Reference(this.repo, this.path.child(pathString)); - }; - /** @return {?Reference} */ - Reference.prototype.getParent = function () { - validateArgCount('Reference.parent', 0, 0, arguments.length); - var parentPath = this.path.parent(); - return parentPath === null ? null : new Reference(this.repo, parentPath); - }; - /** @return {!Reference} */ - Reference.prototype.getRoot = function () { - validateArgCount('Reference.root', 0, 0, arguments.length); - var ref = this; - while (ref.getParent() !== null) { - ref = ref.getParent(); - } - return ref; - }; - /** @return {!Database} */ - Reference.prototype.databaseProp = function () { - return this.repo.database; - }; - /** - * @param {*} newVal - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.set = function (newVal, onComplete) { - validateArgCount('Reference.set', 1, 2, arguments.length); - validateWritablePath('Reference.set', this.path); - validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false); - validateCallback('Reference.set', 2, onComplete, true); - var deferred = new Deferred(); - this.repo.setWithPriority(this.path, newVal, - /*priority=*/ null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.update = function (objectToMerge, onComplete) { - validateArgCount('Reference.update', 1, 2, arguments.length); - validateWritablePath('Reference.update', this.path); - if (Array.isArray(objectToMerge)) { - var newObjectToMerge = {}; - for (var i = 0; i < objectToMerge.length; ++i) { - newObjectToMerge['' + i] = objectToMerge[i]; - } - objectToMerge = newObjectToMerge; - warn('Passing an Array to Firebase.update() is deprecated. ' + - 'Use set() if you want to overwrite the existing data, or ' + - 'an Object with integer keys if you really do want to ' + - 'only update some of the children.'); - } - validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false); - validateCallback('Reference.update', 2, onComplete, true); - var deferred = new Deferred(); - this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} newVal - * @param {string|number|null} newPriority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) { - validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); - validateWritablePath('Reference.setWithPriority', this.path); - validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false); - validatePriority('Reference.setWithPriority', 2, newPriority, false); - validateCallback('Reference.setWithPriority', 3, onComplete, true); - if (this.getKey() === '.length' || this.getKey() === '.keys') - throw 'Reference.setWithPriority failed: ' + - this.getKey() + - ' is a read-only object.'; - var deferred = new Deferred(); - this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.remove = function (onComplete) { - validateArgCount('Reference.remove', 0, 1, arguments.length); - validateWritablePath('Reference.remove', this.path); - validateCallback('Reference.remove', 1, onComplete, true); - return this.set(null, onComplete); - }; - /** - * @param {function(*):*} transactionUpdate - * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete - * @param {boolean=} applyLocally - * @return {!Promise} - */ - Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) { - validateArgCount('Reference.transaction', 1, 3, arguments.length); - validateWritablePath('Reference.transaction', this.path); - validateCallback('Reference.transaction', 1, transactionUpdate, false); - validateCallback('Reference.transaction', 2, onComplete, true); - // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how - // to expose it. - validateBoolean('Reference.transaction', 3, applyLocally, true); - if (this.getKey() === '.length' || this.getKey() === '.keys') - throw 'Reference.transaction failed: ' + - this.getKey() + - ' is a read-only object.'; - if (applyLocally === undefined) - applyLocally = true; - var deferred = new Deferred(); - if (typeof onComplete === 'function') { - deferred.promise.catch(function () { }); - } - var promiseComplete = function (error$$1, committed, snapshot) { - if (error$$1) { - deferred.reject(error$$1); - } - else { - deferred.resolve(new TransactionResult(committed, snapshot)); - } - if (typeof onComplete === 'function') { - onComplete(error$$1, committed, snapshot); - } - }; - this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally); - return deferred.promise; - }; - /** - * @param {string|number|null} priority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.setPriority = function (priority, onComplete) { - validateArgCount('Reference.setPriority', 1, 2, arguments.length); - validateWritablePath('Reference.setPriority', this.path); - validatePriority('Reference.setPriority', 1, priority, false); - validateCallback('Reference.setPriority', 2, onComplete, true); - var deferred = new Deferred(); - this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*=} value - * @param {function(?Error)=} onComplete - * @return {!Reference} - */ - Reference.prototype.push = function (value, onComplete) { - validateArgCount('Reference.push', 0, 2, arguments.length); - validateWritablePath('Reference.push', this.path); - validateFirebaseDataArg('Reference.push', 1, value, this.path, true); - validateCallback('Reference.push', 2, onComplete, true); - var now = this.repo.serverTime(); - var name = nextPushId(now); - // push() returns a ThennableReference whose promise is fulfilled with a regular Reference. - // We use child() to create handles to two different references. The first is turned into a - // ThennableReference below by adding then() and catch() methods and is used as the - // return value of push(). The second remains a regular Reference and is used as the fulfilled - // value of the first ThennableReference. - var thennablePushRef = this.child(name); - var pushRef = this.child(name); - var promise; - if (value != null) { - promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; }); - } - else { - promise = Promise.resolve(pushRef); - } - thennablePushRef.then = promise.then.bind(promise); - thennablePushRef.catch = promise.then.bind(promise, undefined); - if (typeof onComplete === 'function') { - promise.catch(function () { }); - } - return thennablePushRef; - }; - /** - * @return {!OnDisconnect} - */ - Reference.prototype.onDisconnect = function () { - validateWritablePath('Reference.onDisconnect', this.path); - return new OnDisconnect(this.repo, this.path); - }; - Object.defineProperty(Reference.prototype, "database", { - get: function () { - return this.databaseProp(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "key", { - get: function () { - return this.getKey(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "parent", { - get: function () { - return this.getParent(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "root", { - get: function () { - return this.getRoot(); - }, - enumerable: true, - configurable: true - }); - return Reference; -}(Query)); -/** - * Define reference constructor in various modules - * - * We are doing this here to avoid several circular - * dependency issues - */ -Query.__referenceConstructor = Reference; -SyncPoint.__referenceConstructor = Reference; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Node in a Tree. - */ -var TreeNode = /** @class */ (function () { - function TreeNode() { - // TODO: Consider making accessors that create children and value lazily or - // separate Internal / Leaf 'types'. - this.children = {}; - this.childCount = 0; - this.value = null; - } - return TreeNode; -}()); -/** - * A light-weight tree, traversable by path. Nodes can have both values and children. - * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty - * children. - */ -var Tree = /** @class */ (function () { - /** - * @template T - * @param {string=} name_ Optional name of the node. - * @param {Tree=} parent_ Optional parent node. - * @param {TreeNode=} node_ Optional node to wrap. - */ - function Tree(name_, parent_, node_) { - if (name_ === void 0) { name_ = ''; } - if (parent_ === void 0) { parent_ = null; } - if (node_ === void 0) { node_ = new TreeNode(); } - this.name_ = name_; - this.parent_ = parent_; - this.node_ = node_; - } - /** - * Returns a sub-Tree for the given path. - * - * @param {!(string|Path)} pathObj Path to look up. - * @return {!Tree.} Tree for path. - */ - Tree.prototype.subTree = function (pathObj) { - // TODO: Require pathObj to be Path? - var path = pathObj instanceof Path ? pathObj : new Path(pathObj); - var child = this, next; - while ((next = path.getFront()) !== null) { - var childNode = safeGet(child.node_.children, next) || new TreeNode(); - child = new Tree(next, child, childNode); - path = path.popFront(); - } - return child; - }; - /** - * Returns the data associated with this tree node. - * - * @return {?T} The data or null if no data exists. - */ - Tree.prototype.getValue = function () { - return this.node_.value; - }; - /** - * Sets data to this tree node. - * - * @param {!T} value Value to set. - */ - Tree.prototype.setValue = function (value) { - assert(typeof value !== 'undefined', 'Cannot set value to undefined'); - this.node_.value = value; - this.updateParents_(); - }; - /** - * Clears the contents of the tree node (its value and all children). - */ - Tree.prototype.clear = function () { - this.node_.value = null; - this.node_.children = {}; - this.node_.childCount = 0; - this.updateParents_(); - }; - /** - * @return {boolean} Whether the tree has any children. - */ - Tree.prototype.hasChildren = function () { - return this.node_.childCount > 0; - }; - /** - * @return {boolean} Whether the tree is empty (no value or children). - */ - Tree.prototype.isEmpty = function () { - return this.getValue() === null && !this.hasChildren(); - }; - /** - * Calls action for each child of this tree node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - Tree.prototype.forEachChild = function (action) { - var _this = this; - forEach(this.node_.children, function (child, childTree) { - action(new Tree(child, _this, childTree)); - }); - }; - /** - * Does a depth-first traversal of this node's descendants, calling action for each one. - * - * @param {function(!Tree.)} action Action to be called for each child. - * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to - * false. - * @param {boolean=} childrenFirst Whether to call action on children before calling it on - * parent. - */ - Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) { - if (includeSelf && !childrenFirst) - action(this); - this.forEachChild(function (child) { - child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst); - }); - if (includeSelf && childrenFirst) - action(this); - }; - /** - * Calls action on each ancestor node. - * - * @param {function(!Tree.)} action Action to be called on each parent; return - * true to abort. - * @param {boolean=} includeSelf Whether to call action on this node as well. - * @return {boolean} true if the action callback returned true. - */ - Tree.prototype.forEachAncestor = function (action, includeSelf) { - var node = includeSelf ? this : this.parent(); - while (node !== null) { - if (action(node)) { - return true; - } - node = node.parent(); - } - return false; - }; - /** - * Does a depth-first traversal of this node's descendants. When a descendant with a value - * is found, action is called on it and traversal does not continue inside the node. - * Action is *not* called on this node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - Tree.prototype.forEachImmediateDescendantWithValue = function (action) { - this.forEachChild(function (child) { - if (child.getValue() !== null) - action(child); - else - child.forEachImmediateDescendantWithValue(action); - }); - }; - /** - * @return {!Path} The path of this tree node, as a Path. - */ - Tree.prototype.path = function () { - return new Path(this.parent_ === null - ? this.name_ - : this.parent_.path() + '/' + this.name_); - }; - /** - * @return {string} The name of the tree node. - */ - Tree.prototype.name = function () { - return this.name_; - }; - /** - * @return {?Tree} The parent tree node, or null if this is the root of the tree. - */ - Tree.prototype.parent = function () { - return this.parent_; - }; - /** - * Adds or removes this child from its parent based on whether it's empty or not. - * - * @private - */ - Tree.prototype.updateParents_ = function () { - if (this.parent_ !== null) - this.parent_.updateChild_(this.name_, this); - }; - /** - * Adds or removes the passed child to this tree node, depending on whether it's empty. - * - * @param {string} childName The name of the child to update. - * @param {!Tree.} child The child to update. - * @private - */ - Tree.prototype.updateChild_ = function (childName, child) { - var childEmpty = child.isEmpty(); - var childExists = contains(this.node_.children, childName); - if (childEmpty && childExists) { - delete this.node_.children[childName]; - this.node_.childCount--; - this.updateParents_(); - } - else if (!childEmpty && !childExists) { - this.node_.children[childName] = child.node_; - this.node_.childCount++; - this.updateParents_(); - } - }; - return Tree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific -// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well -// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first. -// For now it's part of Repo, but in its own file. -/** - * @enum {number} - */ -var TransactionStatus; -(function (TransactionStatus) { - // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the - // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to - // mismatched hash. - TransactionStatus[TransactionStatus["RUN"] = 0] = "RUN"; - // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted - // or rejected yet). - TransactionStatus[TransactionStatus["SENT"] = 1] = "SENT"; - // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be - // removed when we get a chance to prune completed ones. - TransactionStatus[TransactionStatus["COMPLETED"] = 2] = "COMPLETED"; - // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made). - // If it comes back as unsuccessful, we'll abort it. - TransactionStatus[TransactionStatus["SENT_NEEDS_ABORT"] = 3] = "SENT_NEEDS_ABORT"; - // Temporary state used to mark transactions that need to be aborted. - TransactionStatus[TransactionStatus["NEEDS_ABORT"] = 4] = "NEEDS_ABORT"; -})(TransactionStatus || (TransactionStatus = {})); -/** - * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's - * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely. - * @type {number} - * @const - * @private - */ -Repo.MAX_TRANSACTION_RETRIES_ = 25; -/** - * Setup the transaction data structures - * @private - */ -Repo.prototype.transactions_init_ = function () { - /** - * Stores queues of outstanding transactions for Firebase locations. - * - * @type {!Tree.>} - * @private - */ - this.transactionQueueTree_ = new Tree(); -}; -/** - * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible. - * - * @param {!Path} path Path at which to do transaction. - * @param {function(*):*} transactionUpdate Update callback. - * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback. - * @param {boolean} applyLocally Whether or not to make intermediate results visible - */ -Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) { - this.log_('transaction on ' + path); - // Add a watch to make sure we get server updates. - var valueCallback = function () { }; - var watchRef = new Reference(this, path); - watchRef.on('value', valueCallback); - var unwatcher = function () { - watchRef.off('value', valueCallback); - }; - // Initialize transaction. - var transaction = { - path: path, - update: transactionUpdate, - onComplete: onComplete, - // One of TransactionStatus enums. - status: null, - // Used when combining transactions at different locations to figure out which one goes first. - order: LUIDGenerator(), - // Whether to raise local events for this transaction. - applyLocally: applyLocally, - // Count of how many times we've retried the transaction. - retryCount: 0, - // Function to call to clean up our .on() listener. - unwatcher: unwatcher, - // Stores why a transaction was aborted. - abortReason: null, - currentWriteId: null, - currentInputSnapshot: null, - currentOutputSnapshotRaw: null, - currentOutputSnapshotResolved: null - }; - // Run transaction initially. - var currentState = this.getLatestState_(path); - transaction.currentInputSnapshot = currentState; - var newVal = transaction.update(currentState.val()); - if (newVal === undefined) { - // Abort transaction. - transaction.unwatcher(); - transaction.currentOutputSnapshotRaw = null; - transaction.currentOutputSnapshotResolved = null; - if (transaction.onComplete) { - // We just set the input snapshot, so this cast should be safe - var snapshot = new DataSnapshot(transaction.currentInputSnapshot, new Reference(this, transaction.path), PRIORITY_INDEX); - transaction.onComplete(null, false, snapshot); - } - } - else { - validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); - // Mark as run and add to our queue. - transaction.status = TransactionStatus.RUN; - var queueNode = this.transactionQueueTree_.subTree(path); - var nodeQueue = queueNode.getValue() || []; - nodeQueue.push(transaction); - queueNode.setValue(nodeQueue); - // Update visibleData and raise events - // Note: We intentionally raise events after updating all of our transaction state, since the user could - // start new transactions from the event callbacks. - var priorityForNode = void 0; - if (typeof newVal === 'object' && - newVal !== null && - contains(newVal, '.priority')) { - priorityForNode = safeGet(newVal, '.priority'); - assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + - 'Priority must be a valid string, finite number, server value, or null.'); - } - else { - var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) || - ChildrenNode.EMPTY_NODE; - priorityForNode = currentNode.getPriority().val(); - } - priorityForNode /** @type {null|number|string} */ = priorityForNode; - var serverValues = this.generateServerValues(); - var newNodeUnresolved = nodeFromJSON$1(newVal, priorityForNode); - var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - transaction.currentOutputSnapshotRaw = newNodeUnresolved; - transaction.currentOutputSnapshotResolved = newNode; - transaction.currentWriteId = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally); - this.eventQueue_.raiseEventsForChangedPath(path, events); - this.sendReadyTransactions_(); - } -}; -/** - * @param {!Path} path - * @param {Array.=} excludeSets A specific set to exclude - * @return {Node} - * @private - */ -Repo.prototype.getLatestState_ = function (path, excludeSets) { - return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) || - ChildrenNode.EMPTY_NODE); -}; -/** - * Sends any already-run transactions that aren't waiting for outstanding transactions to - * complete. - * - * Externally it's called with no arguments, but it calls itself recursively with a particular - * transactionQueueTree node to recurse through the tree. - * - * @param {Tree.>=} node transactionQueueTree node to start at. - * @private - */ -Repo.prototype.sendReadyTransactions_ = function (node) { - var _this = this; - if (node === void 0) { node = this.transactionQueueTree_; } - // Before recursing, make sure any completed transactions are removed. - if (!node) { - this.pruneCompletedTransactionsBelowNode_(node); - } - if (node.getValue() !== null) { - var queue = this.buildTransactionQueue_(node); - assert(queue.length > 0, 'Sending zero length transaction queue'); - var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; }); - // If they're all run (and not sent), we can send them. Else, we must wait. - if (allRun) { - this.sendTransactionQueue_(node.path(), queue); - } - } - else if (node.hasChildren()) { - node.forEachChild(function (childNode) { - _this.sendReadyTransactions_(childNode); - }); - } -}; -/** - * Given a list of run transactions, send them to the server and then handle the result (success or failure). - * - * @param {!Path} path The location of the queue. - * @param {!Array.} queue Queue of transactions under the specified location. - * @private - */ -Repo.prototype.sendTransactionQueue_ = function (path, queue) { - var _this = this; - // Mark transactions as sent and increment retry count! - var setsToIgnore = queue.map(function (txn) { - return txn.currentWriteId; - }); - var latestState = this.getLatestState_(path, setsToIgnore); - var snapToSend = latestState; - var latestHash = latestState.hash(); - for (var i = 0; i < queue.length; i++) { - var txn = queue[i]; - assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.'); - txn.status = TransactionStatus.SENT; - txn.retryCount++; - var relativePath = Path.relativePath(path, txn.path); - // If we've gotten to this point, the output snapshot must be defined. - snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw); - } - var dataToSend = snapToSend.val(true); - var pathToSend = path; - // Send the put. - this.server_.put(pathToSend.toString(), dataToSend, function (status) { - _this.log_('transaction put response', { - path: pathToSend.toString(), - status: status - }); - var events = []; - if (status === 'ok') { - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - for (var i = 0; i < queue.length; i++) { - queue[i].status = TransactionStatus.COMPLETED; - events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId)); - if (queue[i].onComplete) { - // We never unset the output snapshot, and given that this transaction is complete, it should be set - var node = queue[i].currentOutputSnapshotResolved; - var ref = new Reference(_this, queue[i].path); - var snapshot = new DataSnapshot(node, ref, PRIORITY_INDEX); - callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot)); - } - queue[i].unwatcher(); - } - // Now remove the completed transactions. - _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path)); - // There may be pending transactions that we can now send. - _this.sendReadyTransactions_(); - _this.eventQueue_.raiseEventsForChangedPath(path, events); - // Finally, trigger onComplete callbacks. - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - } - else { - // transactions are no longer sent. Update their status appropriately. - if (status === 'datastale') { - for (var i = 0; i < queue.length; i++) { - if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) - queue[i].status = TransactionStatus.NEEDS_ABORT; - else - queue[i].status = TransactionStatus.RUN; - } - } - else { - warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); - for (var i = 0; i < queue.length; i++) { - queue[i].status = TransactionStatus.NEEDS_ABORT; - queue[i].abortReason = status; - } - } - _this.rerunTransactions_(path); - } - }, latestHash); -}; -/** - * Finds all transactions dependent on the data at changedPath and reruns them. - * - * Should be called any time cached data changes. - * - * Return the highest path that was affected by rerunning transactions. This is the path at which events need to - * be raised for. - * - * @param {!Path} changedPath The path in mergedData that changed. - * @return {!Path} The rootmost path that was affected by rerunning transactions. - * @private - */ -Repo.prototype.rerunTransactions_ = function (changedPath) { - var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath); - var path = rootMostTransactionNode.path(); - var queue = this.buildTransactionQueue_(rootMostTransactionNode); - this.rerunTransactionQueue_(queue, path); - return path; -}; -/** - * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot). - * - * @param {Array.} queue The queue of transactions to run. - * @param {!Path} path The path the queue is for. - * @private - */ -Repo.prototype.rerunTransactionQueue_ = function (queue, path) { - if (queue.length === 0) { - return; // Nothing to do! - } - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - var events = []; - // Ignore all of the sets we're going to re-run. - var txnsToRerun = queue.filter(function (q) { - return q.status === TransactionStatus.RUN; - }); - var setsToIgnore = txnsToRerun.map(function (q) { - return q.currentWriteId; - }); - for (var i = 0; i < queue.length; i++) { - var transaction = queue[i]; - var relativePath = Path.relativePath(path, transaction.path); - var abortTransaction = false, abortReason = void 0; - assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); - if (transaction.status === TransactionStatus.NEEDS_ABORT) { - abortTransaction = true; - abortReason = transaction.abortReason; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - else if (transaction.status === TransactionStatus.RUN) { - if (transaction.retryCount >= Repo.MAX_TRANSACTION_RETRIES_) { - abortTransaction = true; - abortReason = 'maxretry'; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - else { - // This code reruns a transaction - var currentNode = this.getLatestState_(transaction.path, setsToIgnore); - transaction.currentInputSnapshot = currentNode; - var newData = queue[i].update(currentNode.val()); - if (newData !== undefined) { - validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); - var newDataNode = nodeFromJSON$1(newData); - var hasExplicitPriority = typeof newData === 'object' && - newData != null && - contains(newData, '.priority'); - if (!hasExplicitPriority) { - // Keep the old priority if there wasn't a priority explicitly specified. - newDataNode = newDataNode.updatePriority(currentNode.getPriority()); - } - var oldWriteId = transaction.currentWriteId; - var serverValues = this.generateServerValues(); - var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, serverValues); - transaction.currentOutputSnapshotRaw = newDataNode; - transaction.currentOutputSnapshotResolved = newNodeResolved; - transaction.currentWriteId = this.getNextWriteId_(); - // Mutates setsToIgnore in place - setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); - events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); - events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true)); - } - else { - abortTransaction = true; - abortReason = 'nodata'; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - } - } - this.eventQueue_.raiseEventsForChangedPath(path, events); - events = []; - if (abortTransaction) { - // Abort. - queue[i].status = TransactionStatus.COMPLETED; - // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data). - // So defer the unwatcher until we're done. - (function (unwatcher) { - setTimeout(unwatcher, Math.floor(0)); - })(queue[i].unwatcher); - if (queue[i].onComplete) { - if (abortReason === 'nodata') { - var ref = new Reference(this, queue[i].path); - // We set this field immediately, so it's safe to cast to an actual snapshot - var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot; - var snapshot = new DataSnapshot(lastInput, ref, PRIORITY_INDEX); - callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot)); - } - else { - callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null)); - } - } - } - } - // Clean up completed transactions. - this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_); - // Now fire callbacks, now that we're in a good, known state. - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - // Try to send the transaction result to the server. - this.sendReadyTransactions_(); -}; -/** - * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns - * the node for the given path if there are no pending transactions on any ancestor. - * - * @param {!Path} path The location to start at. - * @return {!Tree.>} The rootmost node with a transaction. - * @private - */ -Repo.prototype.getAncestorTransactionNode_ = function (path) { - var front; - // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions. - var transactionNode = this.transactionQueueTree_; - while ((front = path.getFront()) !== null && - transactionNode.getValue() === null) { - transactionNode = transactionNode.subTree(front); - path = path.popFront(); - } - return transactionNode; -}; -/** - * Builds the queue of all transactions at or below the specified transactionNode. - * - * @param {!Tree.>} transactionNode - * @return {Array.} The generated queue. - * @private - */ -Repo.prototype.buildTransactionQueue_ = function (transactionNode) { - // Walk any child transaction queues and aggregate them into a single queue. - var transactionQueue = []; - this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue); - // Sort them by the order the transactions were created. - transactionQueue.sort(function (a, b) { - return a.order - b.order; - }); - return transactionQueue; -}; -/** - * @param {!Tree.>} node - * @param {Array.} queue - * @private - */ -Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) { - var _this = this; - var nodeQueue = node.getValue(); - if (nodeQueue !== null) { - for (var i = 0; i < nodeQueue.length; i++) { - queue.push(nodeQueue[i]); - } - } - node.forEachChild(function (child) { - _this.aggregateTransactionQueuesForNode_(child, queue); - }); -}; -/** - * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. - * - * @param {!Tree.>} node - * @private - */ -Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) { - var _this = this; - var queue = node.getValue(); - if (queue) { - var to = 0; - for (var from = 0; from < queue.length; from++) { - if (queue[from].status !== TransactionStatus.COMPLETED) { - queue[to] = queue[from]; - to++; - } - } - queue.length = to; - node.setValue(queue.length > 0 ? queue : null); - } - node.forEachChild(function (childNode) { - _this.pruneCompletedTransactionsBelowNode_(childNode); - }); -}; -/** - * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update() - * since we consider them incompatible with transactions. - * - * @param {!Path} path Path for which we want to abort related transactions. - * @return {!Path} - * @private - */ -Repo.prototype.abortTransactions_ = function (path) { - var _this = this; - var affectedPath = this.getAncestorTransactionNode_(path).path(); - var transactionNode = this.transactionQueueTree_.subTree(path); - transactionNode.forEachAncestor(function (node) { - _this.abortTransactionsOnNode_(node); - }); - this.abortTransactionsOnNode_(transactionNode); - transactionNode.forEachDescendant(function (node) { - _this.abortTransactionsOnNode_(node); - }); - return affectedPath; -}; -/** - * Abort transactions stored in this transaction queue node. - * - * @param {!Tree.>} node Node to abort transactions for. - * @private - */ -Repo.prototype.abortTransactionsOnNode_ = function (node) { - var queue = node.getValue(); - if (queue !== null) { - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones - // can be immediately aborted and removed. - var events = []; - var lastSent = -1; - for (var i = 0; i < queue.length; i++) { - if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) { - // Already marked. No action needed. - } - else if (queue[i].status === TransactionStatus.SENT) { - assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); - lastSent = i; - // Mark transaction for abort when it comes back. - queue[i].status = TransactionStatus.SENT_NEEDS_ABORT; - queue[i].abortReason = 'set'; - } - else { - assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort'); - // We can abort it immediately. - queue[i].unwatcher(); - events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true)); - if (queue[i].onComplete) { - var snapshot = null; - callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot)); - } - } - } - if (lastSent === -1) { - // We're not waiting for any sent transactions. We can clear the queue. - node.setValue(null); - } - else { - // Remove the transactions we aborted. - queue.length = lastSent + 1; - } - // Now fire the callbacks. - this.eventQueue_.raiseEventsForChangedPath(node.path(), events); - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - } -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** @const {string} */ -var DATABASE_URL_OPTION = 'databaseURL'; -var _staticInstance; -/** - * Creates and caches Repo instances. - */ -var RepoManager = /** @class */ (function () { - function RepoManager() { - /** - * @private {!Object.>} - */ - this.repos_ = {}; - /** - * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes). - * @private {boolean} - */ - this.useRestClient_ = false; - } - RepoManager.getInstance = function () { - if (!_staticInstance) { - _staticInstance = new RepoManager(); - } - return _staticInstance; - }; - // TODO(koss): Remove these functions unless used in tests? - RepoManager.prototype.interrupt = function () { - for (var appName in this.repos_) { - for (var dbUrl in this.repos_[appName]) { - this.repos_[appName][dbUrl].interrupt(); - } - } - }; - RepoManager.prototype.resume = function () { - for (var appName in this.repos_) { - for (var dbUrl in this.repos_[appName]) { - this.repos_[appName][dbUrl].resume(); - } - } - }; - /** - * This function should only ever be called to CREATE a new database instance. - * - * @param {!FirebaseApp} app - * @return {!Database} - */ - RepoManager.prototype.databaseFromApp = function (app, url) { - var dbUrl = url || app.options[DATABASE_URL_OPTION]; - if (dbUrl === undefined) { - fatal("Can't determine Firebase Database URL. Be sure to include " + - DATABASE_URL_OPTION + - ' option when calling firebase.initializeApp().'); - } - var parsedUrl = parseRepoInfo(dbUrl); - var repoInfo = parsedUrl.repoInfo; - validateUrl('Invalid Firebase Database URL', 1, parsedUrl); - if (!parsedUrl.path.isEmpty()) { - fatal('Database URL must point to the root of a Firebase Database ' + - '(not including a child path).'); - } - var repo = this.createRepo(repoInfo, app); - return repo.database; - }; - /** - * Remove the repo and make sure it is disconnected. - * - * @param {!Repo} repo - */ - RepoManager.prototype.deleteRepo = function (repo) { - var appRepos = safeGet(this.repos_, repo.app.name); - // This should never happen... - if (!appRepos || safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) { - fatal("Database " + repo.app.name + "(" + repo.repoInfo_ + ") has already been deleted."); - } - repo.interrupt(); - delete appRepos[repo.repoInfo_.toURLString()]; - }; - /** - * Ensures a repo doesn't already exist and then creates one using the - * provided app. - * - * @param {!RepoInfo} repoInfo The metadata about the Repo - * @param {!FirebaseApp} app - * @return {!Repo} The Repo object for the specified server / repoName. - */ - RepoManager.prototype.createRepo = function (repoInfo, app) { - var appRepos = safeGet(this.repos_, app.name); - if (!appRepos) { - appRepos = {}; - this.repos_[app.name] = appRepos; - } - var repo = safeGet(appRepos, repoInfo.toURLString()); - if (repo) { - fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); - } - repo = new Repo(repoInfo, this.useRestClient_, app); - appRepos[repoInfo.toURLString()] = repo; - return repo; - }; - /** - * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. - * @param {boolean} forceRestClient - */ - RepoManager.prototype.forceRestClient = function (forceRestClient) { - this.useRestClient_ = forceRestClient; - }; - return RepoManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class representing a firebase database. - * @implements {FirebaseService} - */ -var Database = /** @class */ (function () { - /** - * The constructor should not be called by users of our public API. - * @param {!Repo} repo_ - */ - function Database(repo_) { - this.repo_ = repo_; - if (!(repo_ instanceof Repo)) { - fatal("Don't call new Database() directly - please use firebase.database()."); - } - /** @type {Reference} */ - this.root_ = new Reference(repo_, Path.Empty); - this.INTERNAL = new DatabaseInternals(this); - } - Object.defineProperty(Database.prototype, "app", { - get: function () { - return this.repo_.app; - }, - enumerable: true, - configurable: true - }); - Database.prototype.ref = function (path) { - this.checkDeleted_('ref'); - validateArgCount('database.ref', 0, 1, arguments.length); - if (path instanceof Reference) { - return this.refFromURL(path.toString()); - } - return path !== undefined ? this.root_.child(path) : this.root_; - }; - /** - * Returns a reference to the root or the path specified in url. - * We throw a exception if the url is not in the same domain as the - * current repo. - * @param {string} url - * @return {!Reference} Firebase reference. - */ - Database.prototype.refFromURL = function (url) { - /** @const {string} */ - var apiName = 'database.refFromURL'; - this.checkDeleted_(apiName); - validateArgCount(apiName, 1, 1, arguments.length); - var parsedURL = parseRepoInfo(url); - validateUrl(apiName, 1, parsedURL); - var repoInfo = parsedURL.repoInfo; - if (repoInfo.host !== this.repo_.repoInfo_.host) { - fatal(apiName + - ': Host name does not match the current database: ' + - '(found ' + - repoInfo.host + - ' but expected ' + - this.repo_.repoInfo_.host + - ')'); - } - return this.ref(parsedURL.path.toString()); - }; - /** - * @param {string} apiName - */ - Database.prototype.checkDeleted_ = function (apiName) { - if (this.repo_ === null) { - fatal('Cannot call ' + apiName + ' on a deleted database.'); - } - }; - // Make individual repo go offline. - Database.prototype.goOffline = function () { - validateArgCount('database.goOffline', 0, 0, arguments.length); - this.checkDeleted_('goOffline'); - this.repo_.interrupt(); - }; - Database.prototype.goOnline = function () { - validateArgCount('database.goOnline', 0, 0, arguments.length); - this.checkDeleted_('goOnline'); - this.repo_.resume(); - }; - Database.ServerValue = { - TIMESTAMP: { - '.sv': 'timestamp' - } - }; - return Database; -}()); -var DatabaseInternals = /** @class */ (function () { - /** @param {!Database} database */ - function DatabaseInternals(database) { - this.database = database; - } - /** @return {Promise} */ - DatabaseInternals.prototype.delete = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - this.database.checkDeleted_('delete'); - RepoManager.getInstance().deleteRepo(this.database.repo_); - this.database.repo_ = null; - this.database.root_ = null; - this.database.INTERNAL = null; - this.database = null; - return [2 /*return*/]; - }); - }); - }; - return DatabaseInternals; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * INTERNAL methods for internal-use only (tests, etc.). - * - * Customers shouldn't use these or else should be aware that they could break at any time. - * - * @const - */ -var forceLongPolling = function () { - WebSocketConnection.forceDisallow(); - BrowserPollConnection.forceAllow(); -}; -var forceWebSockets = function () { - BrowserPollConnection.forceDisallow(); -}; -/* Used by App Manager */ -var isWebSocketsAvailable = function () { - return WebSocketConnection['isAvailable'](); -}; -var setSecurityDebugCallback = function (ref, callback) { - ref.repo.persistentConnection_.securityDebugCallback_ = callback; -}; -var stats = function (ref, showDelta) { - ref.repo.stats(showDelta); -}; -var statsIncrementCounter = function (ref, metric) { - ref.repo.statsIncrementCounter(metric); -}; -var dataUpdateCount = function (ref) { - return ref.repo.dataUpdateCount; -}; -var interceptServerData = function (ref, callback) { - return ref.repo.interceptServerData_(callback); -}; - -var INTERNAL = /*#__PURE__*/Object.freeze({ - forceLongPolling: forceLongPolling, - forceWebSockets: forceWebSockets, - isWebSocketsAvailable: isWebSocketsAvailable, - setSecurityDebugCallback: setSecurityDebugCallback, - stats: stats, - statsIncrementCounter: statsIncrementCounter, - dataUpdateCount: dataUpdateCount, - interceptServerData: interceptServerData -}); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DataConnection = PersistentConnection; -/** - * @param {!string} pathString - * @param {function(*)} onComplete - */ -PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { - this.sendRequest('q', { p: pathString }, onComplete); -}; -/** - * @param {*} data - * @param {function(*)} onEcho - */ -PersistentConnection.prototype.echo = function (data, onEcho) { - this.sendRequest('echo', { d: data }, onEcho); -}; -// RealTimeConnection properties that we use in tests. -var RealTimeConnection = Connection; -/** - * @param {function(): string} newHash - * @return {function()} - */ -var hijackHash = function (newHash) { - var oldPut = PersistentConnection.prototype.put; - PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) { - if (opt_hash !== undefined) { - opt_hash = newHash(); - } - oldPut.call(this, pathString, data, opt_onComplete, opt_hash); - }; - return function () { - PersistentConnection.prototype.put = oldPut; - }; -}; -/** - * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined} - */ -var ConnectionTarget = RepoInfo; -/** - * @param {!Query} query - * @return {!string} - */ -var queryIdentifier = function (query) { - return query.queryIdentifier(); -}; -/** - * @param {!Query} firebaseRef - * @return {!Object} - */ -var listens = function (firebaseRef) { - return firebaseRef.repo.persistentConnection_.listens_; -}; -/** - * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. - * - * @param {boolean} forceRestClient - */ -var forceRestClient = function (forceRestClient) { - RepoManager.getInstance().forceRestClient(forceRestClient); -}; - -var TEST_ACCESS = /*#__PURE__*/Object.freeze({ - DataConnection: DataConnection, - RealTimeConnection: RealTimeConnection, - hijackHash: hijackHash, - ConnectionTarget: ConnectionTarget, - queryIdentifier: queryIdentifier, - listens: listens, - forceRestClient: forceRestClient -}); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ServerValue = Database.ServerValue; -function registerDatabase(instance) { - // Register the Database Service with the 'firebase' namespace. - var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager.getInstance().databaseFromApp(app, url); }, - // firebase.database namespace properties - { - Reference: Reference, - Query: Query, - Database: Database, - enableLogging: enableLogging, - INTERNAL: INTERNAL, - ServerValue: ServerValue, - TEST_ACCESS: TEST_ACCESS - }, null, true); - if (isNodeSdk()) { - module.exports = namespace; - } -} -registerDatabase(firebase); - -export { registerDatabase, Database, Query, Reference, enableLogging, ServerValue, DataSnapshot, OnDisconnect }; diff --git a/functions/node_modules/@firebase/database/dist/index.node.cjs.js b/functions/node_modules/@firebase/database/dist/index.node.cjs.js deleted file mode 100644 index e3a1cd07..00000000 --- a/functions/node_modules/@firebase/database/dist/index.node.cjs.js +++ /dev/null @@ -1,15553 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var util = require('@firebase/util'); -var logger = require('@firebase/logger'); -var tslib_1 = require('tslib'); -var firebase = _interopDefault(require('@firebase/app')); -var fayeWebsocket = require('faye-websocket'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Wraps a DOM Storage object and: - * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. - * - prefixes names with "firebase:" to avoid collisions with app data. - * - * We automatically (see storage.js) create two such wrappers, one for sessionStorage, - * and one for localStorage. - * - * @constructor - */ -var DOMStorageWrapper = /** @class */ (function () { - /** - * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage) - */ - function DOMStorageWrapper(domStorage_) { - this.domStorage_ = domStorage_; - // Use a prefix to avoid collisions with other stuff saved by the app. - this.prefix_ = 'firebase:'; - } - /** - * @param {string} key The key to save the value under - * @param {?Object} value The value being stored, or null to remove the key. - */ - DOMStorageWrapper.prototype.set = function (key, value) { - if (value == null) { - this.domStorage_.removeItem(this.prefixedName_(key)); - } - else { - this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value)); - } - }; - /** - * @param {string} key - * @return {*} The value that was stored under this key, or null - */ - DOMStorageWrapper.prototype.get = function (key) { - var storedVal = this.domStorage_.getItem(this.prefixedName_(key)); - if (storedVal == null) { - return null; - } - else { - return util.jsonEval(storedVal); - } - }; - /** - * @param {string} key - */ - DOMStorageWrapper.prototype.remove = function (key) { - this.domStorage_.removeItem(this.prefixedName_(key)); - }; - /** - * @param {string} name - * @return {string} - */ - DOMStorageWrapper.prototype.prefixedName_ = function (name) { - return this.prefix_ + name; - }; - DOMStorageWrapper.prototype.toString = function () { - return this.domStorage_.toString(); - }; - return DOMStorageWrapper; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An in-memory storage implementation that matches the API of DOMStorageWrapper - * (TODO: create interface for both to implement). - * - * @constructor - */ -var MemoryStorage = /** @class */ (function () { - function MemoryStorage() { - this.cache_ = {}; - this.isInMemoryStorage = true; - } - MemoryStorage.prototype.set = function (key, value) { - if (value == null) { - delete this.cache_[key]; - } - else { - this.cache_[key] = value; - } - }; - MemoryStorage.prototype.get = function (key) { - if (util.contains(this.cache_, key)) { - return this.cache_[key]; - } - return null; - }; - MemoryStorage.prototype.remove = function (key) { - delete this.cache_[key]; - }; - return MemoryStorage; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage. - * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change - * to reflect this type - * - * @param {string} domStorageName Name of the underlying storage object - * (e.g. 'localStorage' or 'sessionStorage'). - * @return {?} Turning off type information until a common interface is defined. - */ -var createStoragefor = function (domStorageName) { - try { - // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception, - // so it must be inside the try/catch. - if (typeof window !== 'undefined' && - typeof window[domStorageName] !== 'undefined') { - // Need to test cache. Just because it's here doesn't mean it works - var domStorage = window[domStorageName]; - domStorage.setItem('firebase:sentinel', 'cache'); - domStorage.removeItem('firebase:sentinel'); - return new DOMStorageWrapper(domStorage); - } - } - catch (e) { } - // Failed to create wrapper. Just return in-memory storage. - // TODO: log? - return new MemoryStorage(); -}; -/** A storage object that lasts across sessions */ -var PersistentStorage = createStoragefor('localStorage'); -/** A storage object that only lasts one session */ -var SessionStorage = createStoragefor('sessionStorage'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var logClient = new logger.Logger('@firebase/database'); -/** - * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). - * @type {function(): number} Generated ID. - */ -var LUIDGenerator = (function () { - var id = 1; - return function () { - return id++; - }; -})(); -/** - * Sha1 hash of the input string - * @param {!string} str The string to hash - * @return {!string} The resulting hash - */ -var sha1 = function (str) { - var utf8Bytes = util.stringToByteArray(str); - var sha1 = new util.Sha1(); - sha1.update(utf8Bytes); - var sha1Bytes = sha1.digest(); - return util.base64.encodeByteArray(sha1Bytes); -}; -/** - * @param {...*} var_args - * @return {string} - * @private - */ -var buildLogMessage_ = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = ''; - for (var i = 0; i < var_args.length; i++) { - if (Array.isArray(var_args[i]) || - (var_args[i] && - typeof var_args[i] === 'object' && - typeof var_args[i].length === 'number')) { - message += buildLogMessage_.apply(null, var_args[i]); - } - else if (typeof var_args[i] === 'object') { - message += util.stringify(var_args[i]); - } - else { - message += var_args[i]; - } - message += ' '; - } - return message; -}; -/** - * Use this for all debug messages in Firebase. - * @type {?function(string)} - */ -var logger$1 = null; -/** - * Flag to check for log availability on first log message - * @type {boolean} - * @private - */ -var firstLog_ = true; -/** - * The implementation of Firebase.enableLogging (defined here to break dependencies) - * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger - * @param {boolean=} persistent Whether or not to persist logging settings across refreshes - */ -var enableLogging = function (logger_, persistent) { - util.assert(!persistent || (logger_ === true || logger_ === false), "Can't turn on custom loggers persistently."); - if (logger_ === true) { - logClient.logLevel = logger.LogLevel.VERBOSE; - logger$1 = logClient.log.bind(logClient); - if (persistent) - SessionStorage.set('logging_enabled', true); - } - else if (typeof logger_ === 'function') { - logger$1 = logger_; - } - else { - logger$1 = null; - SessionStorage.remove('logging_enabled'); - } -}; -/** - * - * @param {...(string|Arguments)} var_args - */ -var log = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - if (firstLog_ === true) { - firstLog_ = false; - if (logger$1 === null && SessionStorage.get('logging_enabled') === true) - enableLogging(true); - } - if (logger$1) { - var message = buildLogMessage_.apply(null, var_args); - logger$1(message); - } -}; -/** - * @param {!string} prefix - * @return {function(...[*])} - */ -var logWrapper = function (prefix) { - return function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - log.apply(void 0, [prefix].concat(var_args)); - }; -}; -/** - * @param {...string} var_args - */ -var error = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args); - logClient.error(message); -}; -/** - * @param {...string} var_args - */ -var fatal = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = "FIREBASE FATAL ERROR: " + buildLogMessage_.apply(void 0, var_args); - logClient.error(message); - throw new Error(message); -}; -/** - * @param {...*} var_args - */ -var warn = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args); - logClient.warn(message); -}; -/** - * Logs a warning if the containing page uses https. Called when a call to new Firebase - * does not use https. - */ -var warnIfPageIsSecure = function () { - // Be very careful accessing browser globals. Who knows what may or may not exist. - if (typeof window !== 'undefined' && - window.location && - window.location.protocol && - window.location.protocol.indexOf('https:') !== -1) { - warn('Insecure Firebase access from a secure page. ' + - 'Please use https in calls to new Firebase().'); - } -}; -/** - * Returns true if data is NaN, or +/- Infinity. - * @param {*} data - * @return {boolean} - */ -var isInvalidJSONNumber = function (data) { - return (typeof data === 'number' && - (data != data || // NaN - data == Number.POSITIVE_INFINITY || - data == Number.NEGATIVE_INFINITY)); -}; -/** - * @param {function()} fn - */ -var executeWhenDOMReady = function (fn) { - if (util.isNodeSdk() || document.readyState === 'complete') { - fn(); - } - else { - // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which - // fire before onload), but fall back to onload. - var called_1 = false; - var wrappedFn_1 = function () { - if (!document.body) { - setTimeout(wrappedFn_1, Math.floor(10)); - return; - } - if (!called_1) { - called_1 = true; - fn(); - } - }; - if (document.addEventListener) { - document.addEventListener('DOMContentLoaded', wrappedFn_1, false); - // fallback to onload. - window.addEventListener('load', wrappedFn_1, false); - } - else if (document.attachEvent) { - // IE. - document.attachEvent('onreadystatechange', function () { - if (document.readyState === 'complete') - wrappedFn_1(); - }); - // fallback to onload. - window.attachEvent('onload', wrappedFn_1); - // jQuery has an extra hack for IE that we could employ (based on - // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old. - // I'm hoping we don't need it. - } - } -}; -/** - * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names - * @type {!string} - */ -var MIN_NAME = '[MIN_NAME]'; -/** - * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names - * @type {!string} - */ -var MAX_NAME = '[MAX_NAME]'; -/** - * Compares valid Firebase key names, plus min and max name - * @param {!string} a - * @param {!string} b - * @return {!number} - */ -var nameCompare = function (a, b) { - if (a === b) { - return 0; - } - else if (a === MIN_NAME || b === MAX_NAME) { - return -1; - } - else if (b === MIN_NAME || a === MAX_NAME) { - return 1; - } - else { - var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b); - if (aAsInt !== null) { - if (bAsInt !== null) { - return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt; - } - else { - return -1; - } - } - else if (bAsInt !== null) { - return 1; - } - else { - return a < b ? -1 : 1; - } - } -}; -/** - * @param {!string} a - * @param {!string} b - * @return {!number} comparison result. - */ -var stringCompare = function (a, b) { - if (a === b) { - return 0; - } - else if (a < b) { - return -1; - } - else { - return 1; - } -}; -/** - * @param {string} key - * @param {Object} obj - * @return {*} - */ -var requireKey = function (key, obj) { - if (obj && key in obj) { - return obj[key]; - } - else { - throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj)); - } -}; -/** - * @param {*} obj - * @return {string} - */ -var ObjectToUniqueKey = function (obj) { - if (typeof obj !== 'object' || obj === null) - return util.stringify(obj); - var keys = []; - for (var k in obj) { - keys.push(k); - } - // Export as json, but with the keys sorted. - keys.sort(); - var key = '{'; - for (var i = 0; i < keys.length; i++) { - if (i !== 0) - key += ','; - key += util.stringify(keys[i]); - key += ':'; - key += ObjectToUniqueKey(obj[keys[i]]); - } - key += '}'; - return key; -}; -/** - * Splits a string into a number of smaller segments of maximum size - * @param {!string} str The string - * @param {!number} segsize The maximum number of chars in the string. - * @return {Array.} The string, split into appropriately-sized chunks - */ -var splitStringBySize = function (str, segsize) { - var len = str.length; - if (len <= segsize) { - return [str]; - } - var dataSegs = []; - for (var c = 0; c < len; c += segsize) { - if (c + segsize > len) { - dataSegs.push(str.substring(c, len)); - } - else { - dataSegs.push(str.substring(c, c + segsize)); - } - } - return dataSegs; -}; -/** - * Apply a function to each (key, value) pair in an object or - * apply a function to each (index, value) pair in an array - * @param {!(Object|Array)} obj The object or array to iterate over - * @param {function(?, ?)} fn The function to apply - */ -var each = function (obj, fn) { - if (Array.isArray(obj)) { - for (var i = 0; i < obj.length; ++i) { - fn(i, obj[i]); - } - } - else { - /** - * in the conversion of code we removed the goog.object.forEach - * function which did a value,key callback. We standardized on - * a single impl that does a key, value callback. So we invert - * to not have to touch the `each` code points - */ - util.forEach(obj, function (key, val) { return fn(val, key); }); - } -}; -/** - * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) - * I made one modification at the end and removed the NaN / Infinity - * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. - * @param {!number} v A double - * @return {string} - */ -var doubleToIEEE754String = function (v) { - util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL - var ebits = 11, fbits = 52; - var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str; - // Compute sign, exponent, fraction - // Skip NaN / Infinity handling --MJL. - if (v === 0) { - e = 0; - f = 0; - s = 1 / v === -Infinity ? 1 : 0; - } - else { - s = v < 0; - v = Math.abs(v); - if (v >= Math.pow(2, 1 - bias)) { - // Normalized - ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); - e = ln + bias; - f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits)); - } - else { - // Denormalized - e = 0; - f = Math.round(v / Math.pow(2, 1 - bias - fbits)); - } - } - // Pack sign, exponent, fraction - bits = []; - for (i = fbits; i; i -= 1) { - bits.push(f % 2 ? 1 : 0); - f = Math.floor(f / 2); - } - for (i = ebits; i; i -= 1) { - bits.push(e % 2 ? 1 : 0); - e = Math.floor(e / 2); - } - bits.push(s ? 1 : 0); - bits.reverse(); - str = bits.join(''); - // Return the data as a hex string. --MJL - var hexByteString = ''; - for (i = 0; i < 64; i += 8) { - var hexByte = parseInt(str.substr(i, 8), 2).toString(16); - if (hexByte.length === 1) - hexByte = '0' + hexByte; - hexByteString = hexByteString + hexByte; - } - return hexByteString.toLowerCase(); -}; -/** - * Used to detect if we're in a Chrome content script (which executes in an - * isolated environment where long-polling doesn't work). - * @return {boolean} - */ -var isChromeExtensionContentScript = function () { - return !!(typeof window === 'object' && - window['chrome'] && - window['chrome']['extension'] && - !/^chrome/.test(window.location.href)); -}; -/** - * Used to detect if we're in a Windows 8 Store app. - * @return {boolean} - */ -var isWindowsStoreApp = function () { - // Check for the presence of a couple WinRT globals - return typeof Windows === 'object' && typeof Windows.UI === 'object'; -}; -/** - * Converts a server error code to a Javascript Error - * @param {!string} code - * @param {!Query} query - * @return {Error} - */ -var errorForServerCode = function (code, query) { - var reason = 'Unknown Error'; - if (code === 'too_big') { - reason = - 'The data requested exceeds the maximum size ' + - 'that can be accessed with a single request.'; - } - else if (code == 'permission_denied') { - reason = "Client doesn't have permission to access the desired data."; - } - else if (code == 'unavailable') { - reason = 'The service is unavailable'; - } - var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason); - error.code = code.toUpperCase(); - return error; -}; -/** - * Used to test for integer-looking strings - * @type {RegExp} - * @private - */ -var INTEGER_REGEXP_ = new RegExp('^-?\\d{1,10}$'); -/** - * If the string contains a 32-bit integer, return it. Else return null. - * @param {!string} str - * @return {?number} - */ -var tryParseInt = function (str) { - if (INTEGER_REGEXP_.test(str)) { - var intVal = Number(str); - if (intVal >= -2147483648 && intVal <= 2147483647) { - return intVal; - } - } - return null; -}; -/** - * Helper to run some code but catch any exceptions and re-throw them later. - * Useful for preventing user callbacks from breaking internal code. - * - * Re-throwing the exception from a setTimeout is a little evil, but it's very - * convenient (we don't have to try to figure out when is a safe point to - * re-throw it), and the behavior seems reasonable: - * - * * If you aren't pausing on exceptions, you get an error in the console with - * the correct stack trace. - * * If you're pausing on all exceptions, the debugger will pause on your - * exception and then again when we rethrow it. - * * If you're only pausing on uncaught exceptions, the debugger will only pause - * on us re-throwing it. - * - * @param {!function()} fn The code to guard. - */ -var exceptionGuard = function (fn) { - try { - fn(); - } - catch (e) { - // Re-throw exception when it's safe. - setTimeout(function () { - // It used to be that "throw e" would result in a good console error with - // relevant context, but as of Chrome 39, you just get the firebase.js - // file/line number where we re-throw it, which is useless. So we log - // e.stack explicitly. - var stack = e.stack || ''; - warn('Exception was thrown by user callback.', stack); - throw e; - }, Math.floor(0)); - } -}; -/** - * @return {boolean} true if we think we're currently being crawled. - */ -var beingCrawled = function () { - var userAgent = (typeof window === 'object' && - window['navigator'] && - window['navigator']['userAgent']) || - ''; - // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we - // believe to support JavaScript/AJAX rendering. - // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website - // would have seen the page" is flaky if we don't treat it as a crawler. - return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0); -}; -/** - * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. - * - * It is removed with clearTimeout() as normal. - * - * @param {Function} fn Function to run. - * @param {number} time Milliseconds to wait before running. - * @return {number|Object} The setTimeout() return value. - */ -var setTimeoutNonBlocking = function (fn, time) { - var timeout = setTimeout(fn, time); - if (typeof timeout === 'object' && timeout['unref']) { - timeout['unref'](); - } - return timeout; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An immutable object representing a parsed path. It's immutable so that you - * can pass them around to other functions without worrying about them changing - * it. - */ -var Path = /** @class */ (function () { - /** - * @param {string|Array.} pathOrString Path string to parse, - * or another path, or the raw tokens array - * @param {number=} pieceNum - */ - function Path(pathOrString, pieceNum) { - if (pieceNum === void 0) { - this.pieces_ = pathOrString.split('/'); - // Remove empty pieces. - var copyTo = 0; - for (var i = 0; i < this.pieces_.length; i++) { - if (this.pieces_[i].length > 0) { - this.pieces_[copyTo] = this.pieces_[i]; - copyTo++; - } - } - this.pieces_.length = copyTo; - this.pieceNum_ = 0; - } - else { - this.pieces_ = pathOrString; - this.pieceNum_ = pieceNum; - } - } - Object.defineProperty(Path, "Empty", { - /** - * Singleton to represent an empty path - * - * @const - */ - get: function () { - return new Path(''); - }, - enumerable: true, - configurable: true - }); - Path.prototype.getFront = function () { - if (this.pieceNum_ >= this.pieces_.length) - return null; - return this.pieces_[this.pieceNum_]; - }; - /** - * @return {number} The number of segments in this path - */ - Path.prototype.getLength = function () { - return this.pieces_.length - this.pieceNum_; - }; - /** - * @return {!Path} - */ - Path.prototype.popFront = function () { - var pieceNum = this.pieceNum_; - if (pieceNum < this.pieces_.length) { - pieceNum++; - } - return new Path(this.pieces_, pieceNum); - }; - /** - * @return {?string} - */ - Path.prototype.getBack = function () { - if (this.pieceNum_ < this.pieces_.length) - return this.pieces_[this.pieces_.length - 1]; - return null; - }; - Path.prototype.toString = function () { - var pathString = ''; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) { - if (this.pieces_[i] !== '') - pathString += '/' + this.pieces_[i]; - } - return pathString || '/'; - }; - Path.prototype.toUrlEncodedString = function () { - var pathString = ''; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) { - if (this.pieces_[i] !== '') - pathString += '/' + encodeURIComponent(String(this.pieces_[i])); - } - return pathString || '/'; - }; - /** - * Shallow copy of the parts of the path. - * - * @param {number=} begin - * @return {!Array} - */ - Path.prototype.slice = function (begin) { - if (begin === void 0) { begin = 0; } - return this.pieces_.slice(this.pieceNum_ + begin); - }; - /** - * @return {?Path} - */ - Path.prototype.parent = function () { - if (this.pieceNum_ >= this.pieces_.length) - return null; - var pieces = []; - for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++) - pieces.push(this.pieces_[i]); - return new Path(pieces, 0); - }; - /** - * @param {string|!Path} childPathObj - * @return {!Path} - */ - Path.prototype.child = function (childPathObj) { - var pieces = []; - for (var i = this.pieceNum_; i < this.pieces_.length; i++) - pieces.push(this.pieces_[i]); - if (childPathObj instanceof Path) { - for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) { - pieces.push(childPathObj.pieces_[i]); - } - } - else { - var childPieces = childPathObj.split('/'); - for (var i = 0; i < childPieces.length; i++) { - if (childPieces[i].length > 0) - pieces.push(childPieces[i]); - } - } - return new Path(pieces, 0); - }; - /** - * @return {boolean} True if there are no segments in this path - */ - Path.prototype.isEmpty = function () { - return this.pieceNum_ >= this.pieces_.length; - }; - /** - * @param {!Path} outerPath - * @param {!Path} innerPath - * @return {!Path} The path from outerPath to innerPath - */ - Path.relativePath = function (outerPath, innerPath) { - var outer = outerPath.getFront(), inner = innerPath.getFront(); - if (outer === null) { - return innerPath; - } - else if (outer === inner) { - return Path.relativePath(outerPath.popFront(), innerPath.popFront()); - } - else { - throw new Error('INTERNAL ERROR: innerPath (' + - innerPath + - ') is not within ' + - 'outerPath (' + - outerPath + - ')'); - } - }; - /** - * @param {!Path} left - * @param {!Path} right - * @return {number} -1, 0, 1 if left is less, equal, or greater than the right. - */ - Path.comparePaths = function (left, right) { - var leftKeys = left.slice(); - var rightKeys = right.slice(); - for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) { - var cmp = nameCompare(leftKeys[i], rightKeys[i]); - if (cmp !== 0) - return cmp; - } - if (leftKeys.length === rightKeys.length) - return 0; - return leftKeys.length < rightKeys.length ? -1 : 1; - }; - /** - * - * @param {Path} other - * @return {boolean} true if paths are the same. - */ - Path.prototype.equals = function (other) { - if (this.getLength() !== other.getLength()) { - return false; - } - for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) { - if (this.pieces_[i] !== other.pieces_[j]) { - return false; - } - } - return true; - }; - /** - * - * @param {!Path} other - * @return {boolean} True if this path is a parent (or the same as) other - */ - Path.prototype.contains = function (other) { - var i = this.pieceNum_; - var j = other.pieceNum_; - if (this.getLength() > other.getLength()) { - return false; - } - while (i < this.pieces_.length) { - if (this.pieces_[i] !== other.pieces_[j]) { - return false; - } - ++i; - ++j; - } - return true; - }; - return Path; -}()); // end Path -/** - * Dynamic (mutable) path used to count path lengths. - * - * This class is used to efficiently check paths for valid - * length (in UTF8 bytes) and depth (used in path validation). - * - * Throws Error exception if path is ever invalid. - * - * The definition of a path always begins with '/'. - */ -var ValidationPath = /** @class */ (function () { - /** - * @param {!Path} path Initial Path. - * @param {string} errorPrefix_ Prefix for any error messages. - */ - function ValidationPath(path, errorPrefix_) { - this.errorPrefix_ = errorPrefix_; - /** @type {!Array} */ - this.parts_ = path.slice(); - /** @type {number} Initialize to number of '/' chars needed in path. */ - this.byteLength_ = Math.max(1, this.parts_.length); - for (var i = 0; i < this.parts_.length; i++) { - this.byteLength_ += util.stringLength(this.parts_[i]); - } - this.checkValid_(); - } - Object.defineProperty(ValidationPath, "MAX_PATH_DEPTH", { - /** @const {number} Maximum key depth. */ - get: function () { - return 32; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ValidationPath, "MAX_PATH_LENGTH_BYTES", { - /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */ - get: function () { - return 768; - }, - enumerable: true, - configurable: true - }); - /** @param {string} child */ - ValidationPath.prototype.push = function (child) { - // Count the needed '/' - if (this.parts_.length > 0) { - this.byteLength_ += 1; - } - this.parts_.push(child); - this.byteLength_ += util.stringLength(child); - this.checkValid_(); - }; - ValidationPath.prototype.pop = function () { - var last = this.parts_.pop(); - this.byteLength_ -= util.stringLength(last); - // Un-count the previous '/' - if (this.parts_.length > 0) { - this.byteLength_ -= 1; - } - }; - ValidationPath.prototype.checkValid_ = function () { - if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) { - throw new Error(this.errorPrefix_ + - 'has a key path longer than ' + - ValidationPath.MAX_PATH_LENGTH_BYTES + - ' bytes (' + - this.byteLength_ + - ').'); - } - if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) { - throw new Error(this.errorPrefix_ + - 'path specified exceeds the maximum depth that can be written (' + - ValidationPath.MAX_PATH_DEPTH + - ') or object contains a cycle ' + - this.toErrorString()); - } - }; - /** - * String for use in error messages - uses '.' notation for path. - * - * @return {string} - */ - ValidationPath.prototype.toErrorString = function () { - if (this.parts_.length == 0) { - return ''; - } - return "in property '" + this.parts_.join('.') + "'"; - }; - return ValidationPath; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var PROTOCOL_VERSION = '5'; -var VERSION_PARAM = 'v'; -var TRANSPORT_SESSION_PARAM = 's'; -var REFERER_PARAM = 'r'; -var FORGE_REF = 'f'; -var FORGE_DOMAIN = 'firebaseio.com'; -var LAST_SESSION_PARAM = 'ls'; -var WEBSOCKET = 'websocket'; -var LONG_POLLING = 'long_polling'; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A class that holds metadata about a Repo object - * - * @constructor - */ -var RepoInfo = /** @class */ (function () { - /** - * @param {string} host Hostname portion of the url for the repo - * @param {boolean} secure Whether or not this repo is accessed over ssl - * @param {string} namespace The namespace represented by the repo - * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest). - * @param {string=} persistenceKey Override the default session persistence storage key - */ - function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) { - if (persistenceKey === void 0) { persistenceKey = ''; } - this.secure = secure; - this.namespace = namespace; - this.webSocketOnly = webSocketOnly; - this.persistenceKey = persistenceKey; - this.host = host.toLowerCase(); - this.domain = this.host.substr(this.host.indexOf('.') + 1); - this.internalHost = PersistentStorage.get('host:' + host) || this.host; - } - RepoInfo.prototype.needsQueryParam = function () { - return this.host !== this.internalHost || this.isCustomHost(); - }; - RepoInfo.prototype.isCacheableHost = function () { - return this.internalHost.substr(0, 2) === 's-'; - }; - RepoInfo.prototype.isDemoHost = function () { - return this.domain === 'firebaseio-demo.com'; - }; - RepoInfo.prototype.isCustomHost = function () { - return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com'); - }; - RepoInfo.prototype.updateHost = function (newHost) { - if (newHost !== this.internalHost) { - this.internalHost = newHost; - if (this.isCacheableHost()) { - PersistentStorage.set('host:' + this.host, this.internalHost); - } - } - }; - /** - * Returns the websocket URL for this repo - * @param {string} type of connection - * @param {Object} params list - * @return {string} The URL for this repo - */ - RepoInfo.prototype.connectionURL = function (type, params) { - util.assert(typeof type === 'string', 'typeof type must == string'); - util.assert(typeof params === 'object', 'typeof params must == object'); - var connURL; - if (type === WEBSOCKET) { - connURL = - (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?'; - } - else if (type === LONG_POLLING) { - connURL = - (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?'; - } - else { - throw new Error('Unknown connection type: ' + type); - } - if (this.needsQueryParam()) { - params['ns'] = this.namespace; - } - var pairs = []; - util.forEach(params, function (key, value) { - pairs.push(key + '=' + value); - }); - return connURL + pairs.join('&'); - }; - /** @return {string} */ - RepoInfo.prototype.toString = function () { - var str = this.toURLString(); - if (this.persistenceKey) { - str += '<' + this.persistenceKey + '>'; - } - return str; - }; - /** @return {string} */ - RepoInfo.prototype.toURLString = function () { - return (this.secure ? 'https://' : 'http://') + this.host; - }; - return RepoInfo; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!string} pathString - * @return {string} - */ -function decodePath(pathString) { - var pathStringDecoded = ''; - var pieces = pathString.split('/'); - for (var i = 0; i < pieces.length; i++) { - if (pieces[i].length > 0) { - var piece = pieces[i]; - try { - piece = decodeURIComponent(piece.replace(/\+/g, ' ')); - } - catch (e) { } - pathStringDecoded += '/' + piece; - } - } - return pathStringDecoded; -} -/** - * @param {!string} queryString - * @return {!{[key:string]:string}} key value hash - */ -function decodeQuery(queryString) { - var results = {}; - if (queryString.charAt(0) === '?') { - queryString = queryString.substring(1); - } - for (var _i = 0, _a = queryString.split('&'); _i < _a.length; _i++) { - var segment = _a[_i]; - if (segment.length === 0) { - continue; - } - var kv = segment.split('='); - if (kv.length === 2) { - results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); - } - else { - warn("Invalid query segment '" + segment + "' in query '" + queryString + "'"); - } - } - return results; -} -/** - * - * @param {!string} dataURL - * @return {{repoInfo: !RepoInfo, path: !Path}} - */ -var parseRepoInfo = function (dataURL) { - var parsedUrl = parseURL(dataURL), namespace = parsedUrl.subdomain; - if (parsedUrl.domain === 'firebase') { - fatal(parsedUrl.host + - ' is no longer supported. ' + - 'Please use .firebaseio.com instead'); - } - // Catch common error of uninitialized namespace value. - if ((!namespace || namespace == 'undefined') && - parsedUrl.domain !== 'localhost') { - fatal('Cannot parse Firebase url. Please use https://.firebaseio.com'); - } - if (!parsedUrl.secure) { - warnIfPageIsSecure(); - } - var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss'; - return { - repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly), - path: new Path(parsedUrl.pathString) - }; -}; -/** - * - * @param {!string} dataURL - * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}} - */ -var parseURL = function (dataURL) { - // Default to empty strings in the event of a malformed string. - var host = '', domain = '', subdomain = '', pathString = ''; - // Always default to SSL, unless otherwise specified. - var secure = true, scheme = 'https', port = 443; - // Don't do any validation here. The caller is responsible for validating the result of parsing. - if (typeof dataURL === 'string') { - // Parse scheme. - var colonInd = dataURL.indexOf('//'); - if (colonInd >= 0) { - scheme = dataURL.substring(0, colonInd - 1); - dataURL = dataURL.substring(colonInd + 2); - } - // Parse host, path, and query string. - var slashInd = dataURL.indexOf('/'); - if (slashInd === -1) { - slashInd = dataURL.length; - } - var questionMarkInd = dataURL.indexOf('?'); - if (questionMarkInd === -1) { - questionMarkInd = dataURL.length; - } - host = dataURL.substring(0, Math.min(slashInd, questionMarkInd)); - if (slashInd < questionMarkInd) { - // For pathString, questionMarkInd will always come after slashInd - pathString = decodePath(dataURL.substring(slashInd, questionMarkInd)); - } - var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd))); - // If we have a port, use scheme for determining if it's secure. - colonInd = host.indexOf(':'); - if (colonInd >= 0) { - secure = scheme === 'https' || scheme === 'wss'; - port = parseInt(host.substring(colonInd + 1), 10); - } - else { - colonInd = dataURL.length; - } - var parts = host.split('.'); - if (parts.length === 3) { - // Normalize namespaces to lowercase to share storage / connection. - domain = parts[1]; - subdomain = parts[0].toLowerCase(); - } - else if (parts.length === 2) { - domain = parts[0]; - } - else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') { - domain = 'localhost'; - } - // Support `ns` query param if subdomain not already set - if (subdomain === '' && 'ns' in queryParams) { - subdomain = queryParams['ns']; - } - } - return { - host: host, - port: port, - domain: domain, - subdomain: subdomain, - secure: secure, - scheme: scheme, - pathString: pathString - }; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * True for invalid Firebase keys - * @type {RegExp} - * @private - */ -var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; -/** - * True for invalid Firebase paths. - * Allows '/' in paths. - * @type {RegExp} - * @private - */ -var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; -/** - * Maximum number of characters to allow in leaf value - * @type {number} - * @private - */ -var MAX_LEAF_SIZE_ = 10 * 1024 * 1024; -/** - * @param {*} key - * @return {boolean} - */ -var isValidKey = function (key) { - return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)); -}; -/** - * @param {string} pathString - * @return {boolean} - */ -var isValidPathString = function (pathString) { - return (typeof pathString === 'string' && - pathString.length !== 0 && - !INVALID_PATH_REGEX_.test(pathString)); -}; -/** - * @param {string} pathString - * @return {boolean} - */ -var isValidRootPathString = function (pathString) { - if (pathString) { - // Allow '/.info/' at the beginning. - pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); - } - return isValidPathString(pathString); -}; -/** - * @param {*} priority - * @return {boolean} - */ -var isValidPriority = function (priority) { - return (priority === null || - typeof priority === 'string' || - (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || - (priority && typeof priority === 'object' && util.contains(priority, '.sv'))); -}; -/** - * Pre-validate a datum passed as an argument to Firebase function. - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -var validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) { - if (optional && data === undefined) - return; - validateFirebaseData(util.errorPrefix(fnName, argumentNumber, optional), data, path); -}; -/** - * Validate a data object client-side before sending to server. - * - * @param {string} errorPrefix - * @param {*} data - * @param {!Path|!ValidationPath} path_ - */ -var validateFirebaseData = function (errorPrefix, data, path_) { - var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; - if (data === undefined) { - throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString()); - } - if (typeof data === 'function') { - throw new Error(errorPrefix + - 'contains a function ' + - path.toErrorString() + - ' with contents = ' + - data.toString()); - } - if (isInvalidJSONNumber(data)) { - throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString()); - } - // Check max leaf size, but try to avoid the utf8 conversion if we can. - if (typeof data === 'string' && - data.length > MAX_LEAF_SIZE_ / 3 && - util.stringLength(data) > MAX_LEAF_SIZE_) { - throw new Error(errorPrefix + - 'contains a string greater than ' + - MAX_LEAF_SIZE_ + - ' utf8 bytes ' + - path.toErrorString() + - " ('" + - data.substring(0, 50) + - "...')"); - } - // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON - // to save extra walking of large objects. - if (data && typeof data === 'object') { - var hasDotValue_1 = false, hasActualChild_1 = false; - util.forEach(data, function (key, value) { - if (key === '.value') { - hasDotValue_1 = true; - } - else if (key !== '.priority' && key !== '.sv') { - hasActualChild_1 = true; - if (!isValidKey(key)) { - throw new Error(errorPrefix + - ' contains an invalid key (' + - key + - ') ' + - path.toErrorString() + - '. Keys must be non-empty strings ' + - 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); - } - } - path.push(key); - validateFirebaseData(errorPrefix, value, path); - path.pop(); - }); - if (hasDotValue_1 && hasActualChild_1) { - throw new Error(errorPrefix + - ' contains ".value" child ' + - path.toErrorString() + - ' in addition to actual children.'); - } - } -}; -/** - * Pre-validate paths passed in the firebase function. - * - * @param {string} errorPrefix - * @param {Array} mergePaths - */ -var validateFirebaseMergePaths = function (errorPrefix, mergePaths) { - var i, curPath; - for (i = 0; i < mergePaths.length; i++) { - curPath = mergePaths[i]; - var keys = curPath.slice(); - for (var j = 0; j < keys.length; j++) { - if (keys[j] === '.priority' && j === keys.length - 1) { - // .priority is OK - } - else if (!isValidKey(keys[j])) { - throw new Error(errorPrefix + - 'contains an invalid key (' + - keys[j] + - ') in path ' + - curPath.toString() + - '. Keys must be non-empty strings ' + - 'and can\'t contain ".", "#", "$", "/", "[", or "]"'); - } - } - } - // Check that update keys are not descendants of each other. - // We rely on the property that sorting guarantees that ancestors come - // right before descendants. - mergePaths.sort(Path.comparePaths); - var prevPath = null; - for (i = 0; i < mergePaths.length; i++) { - curPath = mergePaths[i]; - if (prevPath !== null && prevPath.contains(curPath)) { - throw new Error(errorPrefix + - 'contains a path ' + - prevPath.toString() + - ' that is ancestor of another path ' + - curPath.toString()); - } - prevPath = curPath; - } -}; -/** - * pre-validate an object passed as an argument to firebase function ( - * must be an object - e.g. for firebase.update()). - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -var validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) { - if (optional && data === undefined) - return; - var errorPrefix = util.errorPrefix(fnName, argumentNumber, optional); - if (!(data && typeof data === 'object') || Array.isArray(data)) { - throw new Error(errorPrefix + ' must be an object containing the children to replace.'); - } - var mergePaths = []; - util.forEach(data, function (key, value) { - var curPath = new Path(key); - validateFirebaseData(errorPrefix, value, path.child(curPath)); - if (curPath.getBack() === '.priority') { - if (!isValidPriority(value)) { - throw new Error(errorPrefix + - "contains an invalid value for '" + - curPath.toString() + - "', which must be a valid " + - 'Firebase priority (a string, finite number, server value, or null).'); - } - } - mergePaths.push(curPath); - }); - validateFirebaseMergePaths(errorPrefix, mergePaths); -}; -var validatePriority = function (fnName, argumentNumber, priority, optional) { - if (optional && priority === undefined) - return; - if (isInvalidJSONNumber(priority)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'is ' + - priority.toString() + - ', but must be a valid Firebase priority (a string, finite number, ' + - 'server value, or null).'); - // Special case to allow importing data with a .sv. - if (!isValidPriority(priority)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid Firebase priority ' + - '(a string, finite number, server value, or null).'); -}; -var validateEventType = function (fnName, argumentNumber, eventType, optional) { - if (optional && eventType === undefined) - return; - switch (eventType) { - case 'value': - case 'child_added': - case 'child_removed': - case 'child_changed': - case 'child_moved': - break; - default: - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid event type = "value", "child_added", "child_removed", ' + - '"child_changed", or "child_moved".'); - } -}; -var validateKey = function (fnName, argumentNumber, key, optional) { - if (optional && key === undefined) - return; - if (!isValidKey(key)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'was an invalid key = "' + - key + - '". Firebase keys must be non-empty strings and ' + - 'can\'t contain ".", "#", "$", "/", "[", or "]").'); -}; -var validatePathString = function (fnName, argumentNumber, pathString, optional) { - if (optional && pathString === undefined) - return; - if (!isValidPathString(pathString)) - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + - 'was an invalid path = "' + - pathString + - '". Paths must be non-empty strings and ' + - 'can\'t contain ".", "#", "$", "[", or "]"'); -}; -var validateRootPathString = function (fnName, argumentNumber, pathString, optional) { - if (pathString) { - // Allow '/.info/' at the beginning. - pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); - } - validatePathString(fnName, argumentNumber, pathString, optional); -}; -var validateWritablePath = function (fnName, path) { - if (path.getFront() === '.info') { - throw new Error(fnName + " failed = Can't modify data under /.info/"); - } -}; -var validateUrl = function (fnName, argumentNumber, parsedUrl) { - // TODO = Validate server better. - var pathString = parsedUrl.path.toString(); - if (!(typeof parsedUrl.repoInfo.host === 'string') || - parsedUrl.repoInfo.host.length === 0 || - (!isValidKey(parsedUrl.repoInfo.namespace) && - parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || - (pathString.length !== 0 && !isValidRootPathString(pathString))) { - throw new Error(util.errorPrefix(fnName, argumentNumber, false) + - 'must be a valid firebase URL and ' + - 'the path can\'t contain ".", "#", "$", "[", or "]".'); - } -}; -var validateBoolean = function (fnName, argumentNumber, bool, optional) { - if (optional && bool === undefined) - return; - if (typeof bool !== 'boolean') - throw new Error(util.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.'); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - */ -var OnDisconnect = /** @class */ (function () { - /** - * @param {!Repo} repo_ - * @param {!Path} path_ - */ - function OnDisconnect(repo_, path_) { - this.repo_ = repo_; - this.path_ = path_; - } - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.cancel = function (onComplete) { - util.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length); - util.validateCallback('OnDisconnect.cancel', 1, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.remove = function (onComplete) { - util.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length); - validateWritablePath('OnDisconnect.remove', this.path_); - util.validateCallback('OnDisconnect.remove', 1, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} value - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.set = function (value, onComplete) { - util.validateArgCount('OnDisconnect.set', 1, 2, arguments.length); - validateWritablePath('OnDisconnect.set', this.path_); - validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false); - util.validateCallback('OnDisconnect.set', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} value - * @param {number|string|null} priority - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) { - util.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length); - validateWritablePath('OnDisconnect.setWithPriority', this.path_); - validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false); - validatePriority('OnDisconnect.setWithPriority', 2, priority, false); - util.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - OnDisconnect.prototype.update = function (objectToMerge, onComplete) { - util.validateArgCount('OnDisconnect.update', 1, 2, arguments.length); - validateWritablePath('OnDisconnect.update', this.path_); - if (Array.isArray(objectToMerge)) { - var newObjectToMerge = {}; - for (var i = 0; i < objectToMerge.length; ++i) { - newObjectToMerge['' + i] = objectToMerge[i]; - } - objectToMerge = newObjectToMerge; - warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' + - 'existing data, or an Object with integer keys if you really do want to only update some of the children.'); - } - validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false); - util.validateCallback('OnDisconnect.update', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - return OnDisconnect; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var TransactionResult = /** @class */ (function () { - /** - * A type for the resolve value of Firebase.transaction. - * @constructor - * @dict - * @param {boolean} committed - * @param {DataSnapshot} snapshot - */ - function TransactionResult(committed, snapshot) { - this.committed = committed; - this.snapshot = snapshot; - } - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users - TransactionResult.prototype.toJSON = function () { - util.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length); - return { committed: this.committed, snapshot: this.snapshot.toJSON() }; - }; - return TransactionResult; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Fancy ID generator that creates 20-character string identifiers with the - * following properties: - * - * 1. They're based on timestamp so that they sort *after* any existing ids. - * 2. They contain 72-bits of random data after the timestamp so that IDs won't - * collide with other clients' IDs. - * 3. They sort *lexicographically* (so the timestamp is converted to characters - * that will sort properly). - * 4. They're monotonically increasing. Even if you generate more than one in - * the same timestamp, the latter ones will sort after the former ones. We do - * this by using the previous random bits but "incrementing" them by 1 (only - * in the case of a timestamp collision). - */ -var nextPushId = (function () { - // Modeled after base64 web-safe chars, but ordered by ASCII. - var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; - // Timestamp of last push, used to prevent local collisions if you push twice - // in one ms. - var lastPushTime = 0; - // We generate 72-bits of randomness which get turned into 12 characters and - // appended to the timestamp to prevent collisions with other clients. We - // store the last characters we generated because in the event of a collision, - // we'll use those same characters except "incremented" by one. - var lastRandChars = []; - return function (now) { - var duplicateTime = now === lastPushTime; - lastPushTime = now; - var i; - var timeStampChars = new Array(8); - for (i = 7; i >= 0; i--) { - timeStampChars[i] = PUSH_CHARS.charAt(now % 64); - // NOTE: Can't use << here because javascript will convert to int and lose - // the upper bits. - now = Math.floor(now / 64); - } - util.assert(now === 0, 'Cannot push at time == 0'); - var id = timeStampChars.join(''); - if (!duplicateTime) { - for (i = 0; i < 12; i++) { - lastRandChars[i] = Math.floor(Math.random() * 64); - } - } - else { - // If the timestamp hasn't changed since last push, use the same random - // number, except incremented by 1. - for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) { - lastRandChars[i] = 0; - } - lastRandChars[i]++; - } - for (i = 0; i < 12; i++) { - id += PUSH_CHARS.charAt(lastRandChars[i]); - } - util.assert(id.length === 20, 'nextPushId: Length should be 20.'); - return id; - }; -})(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @param {!string} name - * @param {!Node} node - * @constructor - * @struct - */ -var NamedNode = /** @class */ (function () { - function NamedNode(name, node) { - this.name = name; - this.node = node; - } - /** - * - * @param {!string} name - * @param {!Node} node - * @return {NamedNode} - */ - NamedNode.Wrap = function (name, node) { - return new NamedNode(name, node); - }; - return NamedNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @constructor - */ -var Index = /** @class */ (function () { - function Index() { - } - /** - * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for - * this index - */ - Index.prototype.getCompare = function () { - return this.compare.bind(this); - }; - /** - * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, - * it's possible that the changes are isolated to parts of the snapshot that are not indexed. - * - * @param {!Node} oldNode - * @param {!Node} newNode - * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode - */ - Index.prototype.indexedValueChanged = function (oldNode, newNode) { - var oldWrapped = new NamedNode(MIN_NAME, oldNode); - var newWrapped = new NamedNode(MIN_NAME, newNode); - return this.compare(oldWrapped, newWrapped) !== 0; - }; - /** - * @return {!NamedNode} a node wrapper that will sort equal to or less than - * any other node wrapper, using this index - */ - Index.prototype.minPost = function () { - return NamedNode.MIN; - }; - return Index; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __EMPTY_NODE; -var KeyIndex = /** @class */ (function (_super) { - tslib_1.__extends(KeyIndex, _super); - function KeyIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(KeyIndex, "__EMPTY_NODE", { - get: function () { - return __EMPTY_NODE; - }, - set: function (val) { - __EMPTY_NODE = val; - }, - enumerable: true, - configurable: true - }); - /** - * @inheritDoc - */ - KeyIndex.prototype.compare = function (a, b) { - return nameCompare(a.name, b.name); - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.isDefinedOn = function (node) { - // We could probably return true here (since every node has a key), but it's never called - // so just leaving unimplemented for now. - throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.'); - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return false; // The key for a node never changes. - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - KeyIndex.prototype.maxPost = function () { - // TODO: This should really be created once and cached in a static property, but - // NamedNode isn't defined yet, so I can't use it in a static. Bleh. - return new NamedNode(MAX_NAME, __EMPTY_NODE); - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - KeyIndex.prototype.makePost = function (indexValue, name) { - util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.'); - // We just use empty node, but it'll never be compared, since our comparator only looks at name. - return new NamedNode(indexValue, __EMPTY_NODE); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - KeyIndex.prototype.toString = function () { - return '.key'; - }; - return KeyIndex; -}(Index)); -var KEY_INDEX = new KeyIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MAX_NODE; -function setMaxNode(val) { - MAX_NODE = val; -} -/** - * @param {(!string|!number)} priority - * @return {!string} - */ -var priorityHashText = function (priority) { - if (typeof priority === 'number') - return 'number:' + doubleToIEEE754String(priority); - else - return 'string:' + priority; -}; -/** - * Validates that a priority snapshot Node is valid. - * - * @param {!Node} priorityNode - */ -var validatePriorityNode = function (priorityNode) { - if (priorityNode.isLeafNode()) { - var val = priorityNode.val(); - util.assert(typeof val === 'string' || - typeof val === 'number' || - (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.'); - } - else { - util.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.'); - } - // Don't call getPriority() on MAX_NODE to avoid hitting assertion. - util.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own."); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __childrenNodeConstructor; -/** - * LeafNode is a class for storing leaf nodes in a DataSnapshot. It - * implements Node and stores the value of the node (a string, - * number, or boolean) accessible via getValue(). - */ -var LeafNode = /** @class */ (function () { - /** - * @implements {Node} - * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node. - * The object type is possible in the event of a deferred value - * @param {!Node=} priorityNode_ The priority of this node. - */ - function LeafNode(value_, priorityNode_) { - if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; } - this.value_ = value_; - this.priorityNode_ = priorityNode_; - this.lazyHash_ = null; - util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value."); - validatePriorityNode(this.priorityNode_); - } - Object.defineProperty(LeafNode, "__childrenNodeConstructor", { - get: function () { - return __childrenNodeConstructor; - }, - set: function (val) { - __childrenNodeConstructor = val; - }, - enumerable: true, - configurable: true - }); - /** @inheritDoc */ - LeafNode.prototype.isLeafNode = function () { - return true; - }; - /** @inheritDoc */ - LeafNode.prototype.getPriority = function () { - return this.priorityNode_; - }; - /** @inheritDoc */ - LeafNode.prototype.updatePriority = function (newPriorityNode) { - return new LeafNode(this.value_, newPriorityNode); - }; - /** @inheritDoc */ - LeafNode.prototype.getImmediateChild = function (childName) { - // Hack to treat priority as a regular child - if (childName === '.priority') { - return this.priorityNode_; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE; - } - }; - /** @inheritDoc */ - LeafNode.prototype.getChild = function (path) { - if (path.isEmpty()) { - return this; - } - else if (path.getFront() === '.priority') { - return this.priorityNode_; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE; - } - }; - /** - * @inheritDoc - */ - LeafNode.prototype.hasChild = function () { - return false; - }; - /** @inheritDoc */ - LeafNode.prototype.getPredecessorChildName = function (childName, childNode) { - return null; - }; - /** @inheritDoc */ - LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) { - if (childName === '.priority') { - return this.updatePriority(newChildNode); - } - else if (newChildNode.isEmpty() && childName !== '.priority') { - return this; - } - else { - return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_); - } - }; - /** @inheritDoc */ - LeafNode.prototype.updateChild = function (path, newChildNode) { - var front = path.getFront(); - if (front === null) { - return newChildNode; - } - else if (newChildNode.isEmpty() && front !== '.priority') { - return this; - } - else { - util.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path'); - return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode)); - } - }; - /** @inheritDoc */ - LeafNode.prototype.isEmpty = function () { - return false; - }; - /** @inheritDoc */ - LeafNode.prototype.numChildren = function () { - return 0; - }; - /** @inheritDoc */ - LeafNode.prototype.forEachChild = function (index, action) { - return false; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.val = function (exportFormat) { - if (exportFormat && !this.getPriority().isEmpty()) - return { - '.value': this.getValue(), - '.priority': this.getPriority().val() - }; - else - return this.getValue(); - }; - /** @inheritDoc */ - LeafNode.prototype.hash = function () { - if (this.lazyHash_ === null) { - var toHash = ''; - if (!this.priorityNode_.isEmpty()) - toHash += - 'priority:' + - priorityHashText(this.priorityNode_.val()) + - ':'; - var type = typeof this.value_; - toHash += type + ':'; - if (type === 'number') { - toHash += doubleToIEEE754String(this.value_); - } - else { - toHash += this.value_; - } - this.lazyHash_ = sha1(toHash); - } - return this.lazyHash_; - }; - /** - * Returns the value of the leaf node. - * @return {Object|string|number|boolean} The value of the node. - */ - LeafNode.prototype.getValue = function () { - return this.value_; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.compareTo = function (other) { - if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) { - return 1; - } - else if (other instanceof LeafNode.__childrenNodeConstructor) { - return -1; - } - else { - util.assert(other.isLeafNode(), 'Unknown node type'); - return this.compareToLeafNode_(other); - } - }; - /** - * Comparison specifically for two leaf nodes - * @param {!LeafNode} otherLeaf - * @return {!number} - * @private - */ - LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) { - var otherLeafType = typeof otherLeaf.value_; - var thisLeafType = typeof this.value_; - var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType); - var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType); - util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType); - util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType); - if (otherIndex === thisIndex) { - // Same type, compare values - if (thisLeafType === 'object') { - // Deferred value nodes are all equal, but we should also never get to this point... - return 0; - } - else { - // Note that this works because true > false, all others are number or string comparisons - if (this.value_ < otherLeaf.value_) { - return -1; - } - else if (this.value_ === otherLeaf.value_) { - return 0; - } - else { - return 1; - } - } - } - else { - return thisIndex - otherIndex; - } - }; - /** - * @inheritDoc - */ - LeafNode.prototype.withIndex = function () { - return this; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.isIndexed = function () { - return true; - }; - /** - * @inheritDoc - */ - LeafNode.prototype.equals = function (other) { - /** - * @inheritDoc - */ - if (other === this) { - return true; - } - else if (other.isLeafNode()) { - var otherLeaf = other; - return (this.value_ === otherLeaf.value_ && - this.priorityNode_.equals(otherLeaf.priorityNode_)); - } - else { - return false; - } - }; - /** - * The sort order for comparing leaf nodes of different types. If two leaf nodes have - * the same type, the comparison falls back to their value - * @type {Array.} - * @const - */ - LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string']; - return LeafNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var nodeFromJSON; -var MAX_NODE$1; -function setNodeFromJSON(val) { - nodeFromJSON = val; -} -function setMaxNode$1(val) { - MAX_NODE$1 = val; -} -/** - * @constructor - * @extends {Index} - * @private - */ -var PriorityIndex = /** @class */ (function (_super) { - tslib_1.__extends(PriorityIndex, _super); - function PriorityIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - PriorityIndex.prototype.compare = function (a, b) { - var aPriority = a.node.getPriority(); - var bPriority = b.node.getPriority(); - var indexCmp = aPriority.compareTo(bPriority); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.isDefinedOn = function (node) { - return !node.getPriority().isEmpty(); - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return !oldNode.getPriority().equals(newNode.getPriority()); - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - PriorityIndex.prototype.maxPost = function () { - return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1)); - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - PriorityIndex.prototype.makePost = function (indexValue, name) { - var priorityNode = nodeFromJSON(indexValue); - return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode)); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - PriorityIndex.prototype.toString = function () { - return '.priority'; - }; - return PriorityIndex; -}(Index)); -var PRIORITY_INDEX = new PriorityIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An iterator over an LLRBNode. - */ -var SortedMapIterator = /** @class */ (function () { - /** - * @template K, V, T - * @param {LLRBNode|LLRBEmptyNode} node Node to iterate. - * @param {?K} startKey - * @param {function(K, K): number} comparator - * @param {boolean} isReverse_ Whether or not to iterate in reverse - * @param {(function(K, V):T)=} resultGenerator_ - */ - function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) { - if (resultGenerator_ === void 0) { resultGenerator_ = null; } - this.isReverse_ = isReverse_; - this.resultGenerator_ = resultGenerator_; - /** @private - * @type {Array.} - */ - this.nodeStack_ = []; - var cmp = 1; - while (!node.isEmpty()) { - node = node; - cmp = startKey ? comparator(node.key, startKey) : 1; - // flip the comparison if we're going in reverse - if (isReverse_) - cmp *= -1; - if (cmp < 0) { - // This node is less than our start key. ignore it - if (this.isReverse_) { - node = node.left; - } - else { - node = node.right; - } - } - else if (cmp === 0) { - // This node is exactly equal to our start key. Push it on the stack, but stop iterating; - this.nodeStack_.push(node); - break; - } - else { - // This node is greater than our start key, add it to the stack and move to the next one - this.nodeStack_.push(node); - if (this.isReverse_) { - node = node.right; - } - else { - node = node.left; - } - } - } - } - SortedMapIterator.prototype.getNext = function () { - if (this.nodeStack_.length === 0) - return null; - var node = this.nodeStack_.pop(); - var result; - if (this.resultGenerator_) - result = this.resultGenerator_(node.key, node.value); - else - result = { key: node.key, value: node.value }; - if (this.isReverse_) { - node = node.left; - while (!node.isEmpty()) { - this.nodeStack_.push(node); - node = node.right; - } - } - else { - node = node.right; - while (!node.isEmpty()) { - this.nodeStack_.push(node); - node = node.left; - } - } - return result; - }; - SortedMapIterator.prototype.hasNext = function () { - return this.nodeStack_.length > 0; - }; - SortedMapIterator.prototype.peek = function () { - if (this.nodeStack_.length === 0) - return null; - var node = this.nodeStack_[this.nodeStack_.length - 1]; - if (this.resultGenerator_) { - return this.resultGenerator_(node.key, node.value); - } - else { - return { key: node.key, value: node.value }; - } - }; - return SortedMapIterator; -}()); -/** - * Represents a node in a Left-leaning Red-Black tree. - */ -var LLRBNode = /** @class */ (function () { - /** - * @template K, V - * @param {!K} key Key associated with this node. - * @param {!V} value Value associated with this node. - * @param {?boolean} color Whether this node is red. - * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child. - * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child. - */ - function LLRBNode(key, value, color, left, right) { - this.key = key; - this.value = value; - this.color = color != null ? color : LLRBNode.RED; - this.left = - left != null ? left : SortedMap.EMPTY_NODE; - this.right = - right != null ? right : SortedMap.EMPTY_NODE; - } - /** - * Returns a copy of the current node, optionally replacing pieces of it. - * - * @param {?K} key New key for the node, or null. - * @param {?V} value New value for the node, or null. - * @param {?boolean} color New color for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null. - * @return {!LLRBNode} The node copy. - */ - LLRBNode.prototype.copy = function (key, value, color, left, right) { - return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); - }; - /** - * @return {number} The total number of nodes in the tree. - */ - LLRBNode.prototype.count = function () { - return this.left.count() + 1 + this.right.count(); - }; - /** - * @return {boolean} True if the tree is empty. - */ - LLRBNode.prototype.isEmpty = function () { - return false; - }; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - LLRBNode.prototype.inorderTraversal = function (action) { - return (this.left.inorderTraversal(action) || - action(this.key, this.value) || - this.right.inorderTraversal(action)); - }; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!Object, !Object)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} True if traversal was aborted. - */ - LLRBNode.prototype.reverseTraversal = function (action) { - return (this.right.reverseTraversal(action) || - action(this.key, this.value) || - this.left.reverseTraversal(action)); - }; - /** - * @return {!Object} The minimum node in the tree. - * @private - */ - LLRBNode.prototype.min_ = function () { - if (this.left.isEmpty()) { - return this; - } - else { - return this.left.min_(); - } - }; - /** - * @return {!K} The maximum key in the tree. - */ - LLRBNode.prototype.minKey = function () { - return this.min_().key; - }; - /** - * @return {!K} The maximum key in the tree. - */ - LLRBNode.prototype.maxKey = function () { - if (this.right.isEmpty()) { - return this.key; - } - else { - return this.right.maxKey(); - } - }; - /** - * - * @param {!Object} key Key to insert. - * @param {!Object} value Value to insert. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with the key/value added. - */ - LLRBNode.prototype.insert = function (key, value, comparator) { - var cmp, n; - n = this; - cmp = comparator(key, n.key); - if (cmp < 0) { - n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); - } - else if (cmp === 0) { - n = n.copy(null, value, null, null, null); - } - else { - n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); - } - return n.fixUp_(); - }; - /** - * @private - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed. - */ - LLRBNode.prototype.removeMin_ = function () { - if (this.left.isEmpty()) { - return SortedMap.EMPTY_NODE; - } - var n = this; - if (!n.left.isRed_() && !n.left.left.isRed_()) - n = n.moveRedLeft_(); - n = n.copy(null, null, null, n.left.removeMin_(), null); - return n.fixUp_(); - }; - /** - * @param {!Object} key The key of the item to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed. - */ - LLRBNode.prototype.remove = function (key, comparator) { - var n, smallest; - n = this; - if (comparator(key, n.key) < 0) { - if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) { - n = n.moveRedLeft_(); - } - n = n.copy(null, null, null, n.left.remove(key, comparator), null); - } - else { - if (n.left.isRed_()) - n = n.rotateRight_(); - if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) { - n = n.moveRedRight_(); - } - if (comparator(key, n.key) === 0) { - if (n.right.isEmpty()) { - return SortedMap.EMPTY_NODE; - } - else { - smallest = n.right.min_(); - n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_()); - } - } - n = n.copy(null, null, null, null, n.right.remove(key, comparator)); - } - return n.fixUp_(); - }; - /** - * @private - * @return {boolean} Whether this is a RED node. - */ - LLRBNode.prototype.isRed_ = function () { - return this.color; - }; - /** - * @private - * @return {!LLRBNode} New tree after performing any needed rotations. - */ - LLRBNode.prototype.fixUp_ = function () { - var n = this; - if (n.right.isRed_() && !n.left.isRed_()) - n = n.rotateLeft_(); - if (n.left.isRed_() && n.left.left.isRed_()) - n = n.rotateRight_(); - if (n.left.isRed_() && n.right.isRed_()) - n = n.colorFlip_(); - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after moveRedLeft. - */ - LLRBNode.prototype.moveRedLeft_ = function () { - var n = this.colorFlip_(); - if (n.right.left.isRed_()) { - n = n.copy(null, null, null, null, n.right.rotateRight_()); - n = n.rotateLeft_(); - n = n.colorFlip_(); - } - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after moveRedRight. - */ - LLRBNode.prototype.moveRedRight_ = function () { - var n = this.colorFlip_(); - if (n.left.left.isRed_()) { - n = n.rotateRight_(); - n = n.colorFlip_(); - } - return n; - }; - /** - * @private - * @return {!LLRBNode} New tree, after rotateLeft. - */ - LLRBNode.prototype.rotateLeft_ = function () { - var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); - return this.right.copy(null, null, this.color, nl, null); - }; - /** - * @private - * @return {!LLRBNode} New tree, after rotateRight. - */ - LLRBNode.prototype.rotateRight_ = function () { - var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); - return this.left.copy(null, null, this.color, null, nr); - }; - /** - * @private - * @return {!LLRBNode} New tree, after colorFlip. - */ - LLRBNode.prototype.colorFlip_ = function () { - var left = this.left.copy(null, null, !this.left.color, null, null); - var right = this.right.copy(null, null, !this.right.color, null, null); - return this.copy(null, null, !this.color, left, right); - }; - /** - * For testing. - * - * @private - * @return {boolean} True if all is well. - */ - LLRBNode.prototype.checkMaxDepth_ = function () { - var blackDepth = this.check_(); - return Math.pow(2.0, blackDepth) <= this.count() + 1; - }; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - LLRBNode.prototype.check_ = function () { - var blackDepth; - if (this.isRed_() && this.left.isRed_()) { - throw new Error('Red node has red child(' + this.key + ',' + this.value + ')'); - } - if (this.right.isRed_()) { - throw new Error('Right child of (' + this.key + ',' + this.value + ') is red'); - } - blackDepth = this.left.check_(); - if (blackDepth !== this.right.check_()) { - throw new Error('Black depths differ'); - } - else { - return blackDepth + (this.isRed_() ? 0 : 1); - } - }; - LLRBNode.RED = true; - LLRBNode.BLACK = false; - return LLRBNode; -}()); -/** - * Represents an empty node (a leaf node in the Red-Black Tree). - */ -var LLRBEmptyNode = /** @class */ (function () { - function LLRBEmptyNode() { - } - /** - * Returns a copy of the current node. - * - * @return {!LLRBEmptyNode} The node copy. - */ - LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) { - return this; - }; - /** - * Returns a copy of the tree, with the specified key/value added. - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with item added. - */ - LLRBEmptyNode.prototype.insert = function (key, value, comparator) { - return new LLRBNode(key, value, null); - }; - /** - * Returns a copy of the tree, with the specified key removed. - * - * @param {!K} key The key to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBEmptyNode} New tree, with item removed. - */ - LLRBEmptyNode.prototype.remove = function (key, comparator) { - return this; - }; - /** - * @return {number} The total number of nodes in the tree. - */ - LLRBEmptyNode.prototype.count = function () { - return 0; - }; - /** - * @return {boolean} True if the tree is empty. - */ - LLRBEmptyNode.prototype.isEmpty = function () { - return true; - }; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - LLRBEmptyNode.prototype.inorderTraversal = function (action) { - return false; - }; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - LLRBEmptyNode.prototype.reverseTraversal = function (action) { - return false; - }; - /** - * @return {null} - */ - LLRBEmptyNode.prototype.minKey = function () { - return null; - }; - /** - * @return {null} - */ - LLRBEmptyNode.prototype.maxKey = function () { - return null; - }; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - LLRBEmptyNode.prototype.check_ = function () { - return 0; - }; - /** - * @private - * @return {boolean} Whether this node is red. - */ - LLRBEmptyNode.prototype.isRed_ = function () { - return false; - }; - return LLRBEmptyNode; -}()); -/** - * An immutable sorted map implementation, based on a Left-leaning Red-Black - * tree. - */ -var SortedMap = /** @class */ (function () { - /** - * @template K, V - * @param {function(K, K):number} comparator_ Key comparator. - * @param {LLRBNode=} root_ (Optional) Root node for the map. - */ - function SortedMap(comparator_, root_) { - if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; } - this.comparator_ = comparator_; - this.root_ = root_; - } - /** - * Returns a copy of the map, with the specified key/value added or replaced. - * (TODO: We should perhaps rename this method to 'put') - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @return {!SortedMap.} New map, with item added. - */ - SortedMap.prototype.insert = function (key, value) { - return new SortedMap(this.comparator_, this.root_ - .insert(key, value, this.comparator_) - .copy(null, null, LLRBNode.BLACK, null, null)); - }; - /** - * Returns a copy of the map, with the specified key removed. - * - * @param {!K} key The key to remove. - * @return {!SortedMap.} New map, with item removed. - */ - SortedMap.prototype.remove = function (key) { - return new SortedMap(this.comparator_, this.root_ - .remove(key, this.comparator_) - .copy(null, null, LLRBNode.BLACK, null, null)); - }; - /** - * Returns the value of the node with the given key, or null. - * - * @param {!K} key The key to look up. - * @return {?V} The value of the node with the given key, or null if the - * key doesn't exist. - */ - SortedMap.prototype.get = function (key) { - var cmp; - var node = this.root_; - while (!node.isEmpty()) { - cmp = this.comparator_(key, node.key); - if (cmp === 0) { - return node.value; - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - node = node.right; - } - } - return null; - }; - /** - * Returns the key of the item *before* the specified key, or null if key is the first item. - * @param {K} key The key to find the predecessor of - * @return {?K} The predecessor key. - */ - SortedMap.prototype.getPredecessorKey = function (key) { - var cmp, node = this.root_, rightParent = null; - while (!node.isEmpty()) { - cmp = this.comparator_(key, node.key); - if (cmp === 0) { - if (!node.left.isEmpty()) { - node = node.left; - while (!node.right.isEmpty()) - node = node.right; - return node.key; - } - else if (rightParent) { - return rightParent.key; - } - else { - return null; // first item. - } - } - else if (cmp < 0) { - node = node.left; - } - else if (cmp > 0) { - rightParent = node; - node = node.right; - } - } - throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?'); - }; - /** - * @return {boolean} True if the map is empty. - */ - SortedMap.prototype.isEmpty = function () { - return this.root_.isEmpty(); - }; - /** - * @return {number} The total number of nodes in the map. - */ - SortedMap.prototype.count = function () { - return this.root_.count(); - }; - /** - * @return {?K} The minimum key in the map. - */ - SortedMap.prototype.minKey = function () { - return this.root_.minKey(); - }; - /** - * @return {?K} The maximum key in the map. - */ - SortedMap.prototype.maxKey = function () { - return this.root_.maxKey(); - }; - /** - * Traverses the map in key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!K, !V):*} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - SortedMap.prototype.inorderTraversal = function (action) { - return this.root_.inorderTraversal(action); - }; - /** - * Traverses the map in reverse key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!Object, !Object)} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} True if the traversal was aborted. - */ - SortedMap.prototype.reverseTraversal = function (action) { - return this.root_.reverseTraversal(action); - }; - /** - * Returns an iterator over the SortedMap. - * @template T - * @param {(function(K, V):T)=} resultGenerator - * @return {SortedMapIterator.} The iterator. - */ - SortedMap.prototype.getIterator = function (resultGenerator) { - return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator); - }; - SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) { - return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator); - }; - SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) { - return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator); - }; - SortedMap.prototype.getReverseIterator = function (resultGenerator) { - return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator); - }; - /** - * Always use the same empty node, to reduce memory. - * @const - */ - SortedMap.EMPTY_NODE = new LLRBEmptyNode(); - return SortedMap; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var LOG_2 = Math.log(2); -/** - * @constructor - */ -var Base12Num = /** @class */ (function () { - /** - * @param {number} length - */ - function Base12Num(length) { - var logBase2 = function (num) { - return parseInt((Math.log(num) / LOG_2), 10); - }; - var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); }; - this.count = logBase2(length + 1); - this.current_ = this.count - 1; - var mask = bitMask(this.count); - this.bits_ = (length + 1) & mask; - } - /** - * @return {boolean} - */ - Base12Num.prototype.nextBitIsOne = function () { - //noinspection JSBitwiseOperatorUsage - var result = !(this.bits_ & (0x1 << this.current_)); - this.current_--; - return result; - }; - return Base12Num; -}()); -/** - * Takes a list of child nodes and constructs a SortedSet using the given comparison - * function - * - * Uses the algorithm described in the paper linked here: - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 - * - * @template K, V - * @param {Array.} childList Unsorted list of children - * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used - * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's - * type is not NamedNode - * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map - * @return {SortedMap.} - */ -var buildChildSet = function (childList, cmp, keyFn, mapSortFn) { - childList.sort(cmp); - var buildBalancedTree = function (low, high) { - var length = high - low; - var namedNode; - var key; - if (length == 0) { - return null; - } - else if (length == 1) { - namedNode = childList[low]; - key = keyFn ? keyFn(namedNode) : namedNode; - return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null); - } - else { - var middle = parseInt((length / 2), 10) + low; - var left = buildBalancedTree(low, middle); - var right = buildBalancedTree(middle + 1, high); - namedNode = childList[middle]; - key = keyFn ? keyFn(namedNode) : namedNode; - return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right); - } - }; - var buildFrom12Array = function (base12) { - var node = null; - var root = null; - var index = childList.length; - var buildPennant = function (chunkSize, color) { - var low = index - chunkSize; - var high = index; - index -= chunkSize; - var childTree = buildBalancedTree(low + 1, high); - var namedNode = childList[low]; - var key = keyFn ? keyFn(namedNode) : namedNode; - attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree)); - }; - var attachPennant = function (pennant) { - if (node) { - node.left = pennant; - node = pennant; - } - else { - root = pennant; - node = pennant; - } - }; - for (var i = 0; i < base12.count; ++i) { - var isOne = base12.nextBitIsOne(); - // The number of nodes taken in each slice is 2^(arr.length - (i + 1)) - var chunkSize = Math.pow(2, base12.count - (i + 1)); - if (isOne) { - buildPennant(chunkSize, LLRBNode.BLACK); - } - else { - // current == 2 - buildPennant(chunkSize, LLRBNode.BLACK); - buildPennant(chunkSize, LLRBNode.RED); - } - } - return root; - }; - var base12 = new Base12Num(childList.length); - var root = buildFrom12Array(base12); - return new SortedMap(mapSortFn || cmp, root); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var _defaultIndexMap; -var fallbackObject = {}; -/** - * - * @param {Object.>} indexes - * @param {Object.} indexSet - * @constructor - */ -var IndexMap = /** @class */ (function () { - function IndexMap(indexes_, indexSet_) { - this.indexes_ = indexes_; - this.indexSet_ = indexSet_; - } - Object.defineProperty(IndexMap, "Default", { - /** - * The default IndexMap for nodes without a priority - * @type {!IndexMap} - * @const - */ - get: function () { - util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded'); - _defaultIndexMap = - _defaultIndexMap || - new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX }); - return _defaultIndexMap; - }, - enumerable: true, - configurable: true - }); - /** - * - * @param {!string} indexKey - * @return {?SortedMap.} - */ - IndexMap.prototype.get = function (indexKey) { - var sortedMap = util.safeGet(this.indexes_, indexKey); - if (!sortedMap) - throw new Error('No index defined for ' + indexKey); - if (sortedMap === fallbackObject) { - // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the - // regular child map - return null; - } - else { - return sortedMap; - } - }; - /** - * @param {!Index} indexDefinition - * @return {boolean} - */ - IndexMap.prototype.hasIndex = function (indexDefinition) { - return util.contains(this.indexSet_, indexDefinition.toString()); - }; - /** - * @param {!Index} indexDefinition - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) { - util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap."); - var childList = []; - var sawIndexedValue = false; - var iter = existingChildren.getIterator(NamedNode.Wrap); - var next = iter.getNext(); - while (next) { - sawIndexedValue = - sawIndexedValue || indexDefinition.isDefinedOn(next.node); - childList.push(next); - next = iter.getNext(); - } - var newIndex; - if (sawIndexedValue) { - newIndex = buildChildSet(childList, indexDefinition.getCompare()); - } - else { - newIndex = fallbackObject; - } - var indexName = indexDefinition.toString(); - var newIndexSet = util.clone(this.indexSet_); - newIndexSet[indexName] = indexDefinition; - var newIndexes = util.clone(this.indexes_); - newIndexes[indexName] = newIndex; - return new IndexMap(newIndexes, newIndexSet); - }; - /** - * Ensure that this node is properly tracked in any indexes that we're maintaining - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) { - var _this = this; - var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) { - var index = util.safeGet(_this.indexSet_, indexName); - util.assert(index, 'Missing index implementation for ' + indexName); - if (indexedChildren === fallbackObject) { - // Check to see if we need to index everything - if (index.isDefinedOn(namedNode.node)) { - // We need to build this index - var childList = []; - var iter = existingChildren.getIterator(NamedNode.Wrap); - var next = iter.getNext(); - while (next) { - if (next.name != namedNode.name) { - childList.push(next); - } - next = iter.getNext(); - } - childList.push(namedNode); - return buildChildSet(childList, index.getCompare()); - } - else { - // No change, this remains a fallback - return fallbackObject; - } - } - else { - var existingSnap = existingChildren.get(namedNode.name); - var newChildren = indexedChildren; - if (existingSnap) { - newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap)); - } - return newChildren.insert(namedNode, namedNode.node); - } - }); - return new IndexMap(newIndexes, this.indexSet_); - }; - /** - * Create a new IndexMap instance with the given value removed - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) { - var newIndexes = util.map(this.indexes_, function (indexedChildren) { - if (indexedChildren === fallbackObject) { - // This is the fallback. Just return it, nothing to do in this case - return indexedChildren; - } - else { - var existingSnap = existingChildren.get(namedNode.name); - if (existingSnap) { - return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap)); - } - else { - // No record of this child - return indexedChildren; - } - } - }); - return new IndexMap(newIndexes, this.indexSet_); - }; - return IndexMap; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function NAME_ONLY_COMPARATOR(left, right) { - return nameCompare(left.name, right.name); -} -function NAME_COMPARATOR(left, right) { - return nameCompare(left, right); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// TODO: For memory savings, don't store priorityNode_ if it's empty. -var EMPTY_NODE; -/** - * ChildrenNode is a class for storing internal nodes in a DataSnapshot - * (i.e. nodes with children). It implements Node and stores the - * list of children in the children property, sorted by child name. - * - * @constructor - * @implements {Node} - */ -var ChildrenNode = /** @class */ (function () { - /** - * - * @param {!SortedMap.} children_ List of children - * of this node.. - * @param {?Node} priorityNode_ The priority of this node (as a snapshot node). - * @param {!IndexMap} indexMap_ - */ - function ChildrenNode(children_, priorityNode_, indexMap_) { - this.children_ = children_; - this.priorityNode_ = priorityNode_; - this.indexMap_ = indexMap_; - this.lazyHash_ = null; - /** - * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use - * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own - * class instead of an empty ChildrenNode. - */ - if (this.priorityNode_) { - validatePriorityNode(this.priorityNode_); - } - if (this.children_.isEmpty()) { - util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority'); - } - } - Object.defineProperty(ChildrenNode, "EMPTY_NODE", { - get: function () { - return (EMPTY_NODE || - (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default))); - }, - enumerable: true, - configurable: true - }); - /** @inheritDoc */ - ChildrenNode.prototype.isLeafNode = function () { - return false; - }; - /** @inheritDoc */ - ChildrenNode.prototype.getPriority = function () { - return this.priorityNode_ || EMPTY_NODE; - }; - /** @inheritDoc */ - ChildrenNode.prototype.updatePriority = function (newPriorityNode) { - if (this.children_.isEmpty()) { - // Don't allow priorities on empty nodes - return this; - } - else { - return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.getImmediateChild = function (childName) { - // Hack to treat priority as a regular child - if (childName === '.priority') { - return this.getPriority(); - } - else { - var child = this.children_.get(childName); - return child === null ? EMPTY_NODE : child; - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.getChild = function (path) { - var front = path.getFront(); - if (front === null) - return this; - return this.getImmediateChild(front).getChild(path.popFront()); - }; - /** @inheritDoc */ - ChildrenNode.prototype.hasChild = function (childName) { - return this.children_.get(childName) !== null; - }; - /** @inheritDoc */ - ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) { - util.assert(newChildNode, 'We should always be passing snapshot nodes'); - if (childName === '.priority') { - return this.updatePriority(newChildNode); - } - else { - var namedNode = new NamedNode(childName, newChildNode); - var newChildren = void 0, newIndexMap = void 0, newPriority = void 0; - if (newChildNode.isEmpty()) { - newChildren = this.children_.remove(childName); - newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_); - } - else { - newChildren = this.children_.insert(childName, newChildNode); - newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_); - } - newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_; - return new ChildrenNode(newChildren, newPriority, newIndexMap); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.updateChild = function (path, newChildNode) { - var front = path.getFront(); - if (front === null) { - return newChildNode; - } - else { - util.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path'); - var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode); - return this.updateImmediateChild(front, newImmediateChild); - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.isEmpty = function () { - return this.children_.isEmpty(); - }; - /** @inheritDoc */ - ChildrenNode.prototype.numChildren = function () { - return this.children_.count(); - }; - /** @inheritDoc */ - ChildrenNode.prototype.val = function (exportFormat) { - if (this.isEmpty()) - return null; - var obj = {}; - var numKeys = 0, maxKey = 0, allIntegerKeys = true; - this.forEachChild(PRIORITY_INDEX, function (key, childNode) { - obj[key] = childNode.val(exportFormat); - numKeys++; - if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) { - maxKey = Math.max(maxKey, Number(key)); - } - else { - allIntegerKeys = false; - } - }); - if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) { - // convert to array. - var array = []; - for (var key in obj) - array[key] = obj[key]; - return array; - } - else { - if (exportFormat && !this.getPriority().isEmpty()) { - obj['.priority'] = this.getPriority().val(); - } - return obj; - } - }; - /** @inheritDoc */ - ChildrenNode.prototype.hash = function () { - if (this.lazyHash_ === null) { - var toHash_1 = ''; - if (!this.getPriority().isEmpty()) - toHash_1 += - 'priority:' + - priorityHashText(this.getPriority().val()) + - ':'; - this.forEachChild(PRIORITY_INDEX, function (key, childNode) { - var childHash = childNode.hash(); - if (childHash !== '') - toHash_1 += ':' + key + ':' + childHash; - }); - this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1); - } - return this.lazyHash_; - }; - /** @inheritDoc */ - ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) { - var idx = this.resolveIndex_(index); - if (idx) { - var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode)); - return predecessor ? predecessor.name : null; - } - else { - return this.children_.getPredecessorKey(childName); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?string} - */ - ChildrenNode.prototype.getFirstChildName = function (indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - var minKey = idx.minKey(); - return minKey && minKey.name; - } - else { - return this.children_.minKey(); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - ChildrenNode.prototype.getFirstChild = function (indexDefinition) { - var minKey = this.getFirstChildName(indexDefinition); - if (minKey) { - return new NamedNode(minKey, this.children_.get(minKey)); - } - else { - return null; - } - }; - /** - * Given an index, return the key name of the largest value we have, according to that index - * @param {!Index} indexDefinition - * @return {?string} - */ - ChildrenNode.prototype.getLastChildName = function (indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - var maxKey = idx.maxKey(); - return maxKey && maxKey.name; - } - else { - return this.children_.maxKey(); - } - }; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - ChildrenNode.prototype.getLastChild = function (indexDefinition) { - var maxKey = this.getLastChildName(indexDefinition); - if (maxKey) { - return new NamedNode(maxKey, this.children_.get(maxKey)); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.forEachChild = function (index, action) { - var idx = this.resolveIndex_(index); - if (idx) { - return idx.inorderTraversal(function (wrappedNode) { - return action(wrappedNode.name, wrappedNode.node); - }); - } - else { - return this.children_.inorderTraversal(action); - } - }; - /** - * @param {!Index} indexDefinition - * @return {SortedMapIterator} - */ - ChildrenNode.prototype.getIterator = function (indexDefinition) { - return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition); - }; - /** - * - * @param {!NamedNode} startPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - return idx.getIteratorFrom(startPost, function (key) { return key; }); - } - else { - var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap); - var next = iterator.peek(); - while (next != null && indexDefinition.compare(next, startPost) < 0) { - iterator.getNext(); - next = iterator.peek(); - } - return iterator; - } - }; - /** - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getReverseIterator = function (indexDefinition) { - return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition); - }; - /** - * @param {!NamedNode} endPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) { - var idx = this.resolveIndex_(indexDefinition); - if (idx) { - return idx.getReverseIteratorFrom(endPost, function (key) { - return key; - }); - } - else { - var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap); - var next = iterator.peek(); - while (next != null && indexDefinition.compare(next, endPost) > 0) { - iterator.getNext(); - next = iterator.peek(); - } - return iterator; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.compareTo = function (other) { - if (this.isEmpty()) { - if (other.isEmpty()) { - return 0; - } - else { - return -1; - } - } - else if (other.isLeafNode() || other.isEmpty()) { - return 1; - } - else if (other === MAX_NODE$2) { - return -1; - } - else { - // Must be another node with children. - return 0; - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.withIndex = function (indexDefinition) { - if (indexDefinition === KEY_INDEX || - this.indexMap_.hasIndex(indexDefinition)) { - return this; - } - else { - var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_); - return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap); - } - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.isIndexed = function (index) { - return index === KEY_INDEX || this.indexMap_.hasIndex(index); - }; - /** - * @inheritDoc - */ - ChildrenNode.prototype.equals = function (other) { - if (other === this) { - return true; - } - else if (other.isLeafNode()) { - return false; - } - else { - var otherChildrenNode = other; - if (!this.getPriority().equals(otherChildrenNode.getPriority())) { - return false; - } - else if (this.children_.count() === otherChildrenNode.children_.count()) { - var thisIter = this.getIterator(PRIORITY_INDEX); - var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX); - var thisCurrent = thisIter.getNext(); - var otherCurrent = otherIter.getNext(); - while (thisCurrent && otherCurrent) { - if (thisCurrent.name !== otherCurrent.name || - !thisCurrent.node.equals(otherCurrent.node)) { - return false; - } - thisCurrent = thisIter.getNext(); - otherCurrent = otherIter.getNext(); - } - return thisCurrent === null && otherCurrent === null; - } - else { - return false; - } - } - }; - /** - * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used - * instead. - * - * @private - * @param {!Index} indexDefinition - * @return {?SortedMap.} - */ - ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) { - if (indexDefinition === KEY_INDEX) { - return null; - } - else { - return this.indexMap_.get(indexDefinition.toString()); - } - }; - /** - * @private - * @type {RegExp} - */ - ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/; - return ChildrenNode; -}()); -/** - * @constructor - * @extends {ChildrenNode} - * @private - */ -var MaxNode = /** @class */ (function (_super) { - tslib_1.__extends(MaxNode, _super); - function MaxNode() { - return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this; - } - MaxNode.prototype.compareTo = function (other) { - if (other === this) { - return 0; - } - else { - return 1; - } - }; - MaxNode.prototype.equals = function (other) { - // Not that we every compare it, but MAX_NODE is only ever equal to itself - return other === this; - }; - MaxNode.prototype.getPriority = function () { - return this; - }; - MaxNode.prototype.getImmediateChild = function (childName) { - return ChildrenNode.EMPTY_NODE; - }; - MaxNode.prototype.isEmpty = function () { - return false; - }; - return MaxNode; -}(ChildrenNode)); -/** - * Marker that will sort higher than any other snapshot. - * @type {!MAX_NODE} - * @const - */ -var MAX_NODE$2 = new MaxNode(); -Object.defineProperties(NamedNode, { - MIN: { - value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE) - }, - MAX: { - value: new NamedNode(MAX_NAME, MAX_NODE$2) - } -}); -/** - * Reference Extensions - */ -KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE; -LeafNode.__childrenNodeConstructor = ChildrenNode; -setMaxNode(MAX_NODE$2); -setMaxNode$1(MAX_NODE$2); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var USE_HINZE = true; -/** - * Constructs a snapshot node representing the passed JSON and returns it. - * @param {*} json JSON to create a node for. - * @param {?string|?number=} priority Optional priority to use. This will be ignored if the - * passed JSON contains a .priority property. - * @return {!Node} - */ -function nodeFromJSON$1(json, priority) { - if (priority === void 0) { priority = null; } - if (json === null) { - return ChildrenNode.EMPTY_NODE; - } - if (typeof json === 'object' && '.priority' in json) { - priority = json['.priority']; - } - util.assert(priority === null || - typeof priority === 'string' || - typeof priority === 'number' || - (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority); - if (typeof json === 'object' && '.value' in json && json['.value'] !== null) { - json = json['.value']; - } - // Valid leaf nodes include non-objects or server-value wrapper objects - if (typeof json !== 'object' || '.sv' in json) { - var jsonLeaf = json; - return new LeafNode(jsonLeaf, nodeFromJSON$1(priority)); - } - if (!(json instanceof Array) && USE_HINZE) { - var children_1 = []; - var childrenHavePriority_1 = false; - var hinzeJsonObj_1 = json; - util.forEach(hinzeJsonObj_1, function (key, child) { - if (typeof key !== 'string' || key.substring(0, 1) !== '.') { - // Ignore metadata nodes - var childNode = nodeFromJSON$1(hinzeJsonObj_1[key]); - if (!childNode.isEmpty()) { - childrenHavePriority_1 = - childrenHavePriority_1 || !childNode.getPriority().isEmpty(); - children_1.push(new NamedNode(key, childNode)); - } - } - }); - if (children_1.length == 0) { - return ChildrenNode.EMPTY_NODE; - } - var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR); - if (childrenHavePriority_1) { - var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare()); - return new ChildrenNode(childSet, nodeFromJSON$1(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX })); - } - else { - return new ChildrenNode(childSet, nodeFromJSON$1(priority), IndexMap.Default); - } - } - else { - var node_1 = ChildrenNode.EMPTY_NODE; - var jsonObj_1 = json; - util.forEach(jsonObj_1, function (key, childData) { - if (util.contains(jsonObj_1, key)) { - if (key.substring(0, 1) !== '.') { - // ignore metadata nodes. - var childNode = nodeFromJSON$1(childData); - if (childNode.isLeafNode() || !childNode.isEmpty()) - node_1 = node_1.updateImmediateChild(key, childNode); - } - } - }); - return node_1.updatePriority(nodeFromJSON$1(priority)); - } -} -setNodeFromJSON(nodeFromJSON$1); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @extends {Index} - * @private - */ -var ValueIndex = /** @class */ (function (_super) { - tslib_1.__extends(ValueIndex, _super); - function ValueIndex() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - ValueIndex.prototype.compare = function (a, b) { - var indexCmp = a.node.compareTo(b.node); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.isDefinedOn = function (node) { - return true; - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) { - return !oldNode.equals(newNode); - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.minPost = function () { - return NamedNode.MIN; - }; - /** - * @inheritDoc - */ - ValueIndex.prototype.maxPost = function () { - return NamedNode.MAX; - }; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - ValueIndex.prototype.makePost = function (indexValue, name) { - var valueNode = nodeFromJSON$1(indexValue); - return new NamedNode(name, valueNode); - }; - /** - * @return {!string} String representation for inclusion in a query spec - */ - ValueIndex.prototype.toString = function () { - return '.value'; - }; - return ValueIndex; -}(Index)); -var VALUE_INDEX = new ValueIndex(); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!Path} indexPath - * @constructor - * @extends {Index} - */ -var PathIndex = /** @class */ (function (_super) { - tslib_1.__extends(PathIndex, _super); - function PathIndex(indexPath_) { - var _this = _super.call(this) || this; - _this.indexPath_ = indexPath_; - util.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', "Can't create PathIndex with empty path or .priority key"); - return _this; - } - /** - * @param {!Node} snap - * @return {!Node} - * @protected - */ - PathIndex.prototype.extractChild = function (snap) { - return snap.getChild(this.indexPath_); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.isDefinedOn = function (node) { - return !node.getChild(this.indexPath_).isEmpty(); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.compare = function (a, b) { - var aChild = this.extractChild(a.node); - var bChild = this.extractChild(b.node); - var indexCmp = aChild.compareTo(bChild); - if (indexCmp === 0) { - return nameCompare(a.name, b.name); - } - else { - return indexCmp; - } - }; - /** - * @inheritDoc - */ - PathIndex.prototype.makePost = function (indexValue, name) { - var valueNode = nodeFromJSON$1(indexValue); - var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode); - return new NamedNode(name, node); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.maxPost = function () { - var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE$2); - return new NamedNode(MAX_NAME, node); - }; - /** - * @inheritDoc - */ - PathIndex.prototype.toString = function () { - return this.indexPath_.slice().join('/'); - }; - return PathIndex; -}(Index)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class representing a firebase data snapshot. It wraps a SnapshotNode and - * surfaces the public methods (val, forEach, etc.) we want to expose. - */ -var DataSnapshot = /** @class */ (function () { - /** - * @param {!Node} node_ A SnapshotNode to wrap. - * @param {!Reference} ref_ The ref of the location this snapshot came from. - * @param {!Index} index_ The iteration order for this snapshot - */ - function DataSnapshot(node_, ref_, index_) { - this.node_ = node_; - this.ref_ = ref_; - this.index_ = index_; - } - /** - * Retrieves the snapshot contents as JSON. Returns null if the snapshot is - * empty. - * - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - DataSnapshot.prototype.val = function () { - util.validateArgCount('DataSnapshot.val', 0, 0, arguments.length); - return this.node_.val(); - }; - /** - * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting - * the entire node contents. - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - DataSnapshot.prototype.exportVal = function () { - util.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length); - return this.node_.val(true); - }; - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users - DataSnapshot.prototype.toJSON = function () { - // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content - util.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length); - return this.exportVal(); - }; - /** - * Returns whether the snapshot contains a non-null value. - * - * @return {boolean} Whether the snapshot contains a non-null value, or is empty. - */ - DataSnapshot.prototype.exists = function () { - util.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length); - return !this.node_.isEmpty(); - }; - /** - * Returns a DataSnapshot of the specified child node's contents. - * - * @param {!string} childPathString Path to a child. - * @return {!DataSnapshot} DataSnapshot for child node. - */ - DataSnapshot.prototype.child = function (childPathString) { - util.validateArgCount('DataSnapshot.child', 0, 1, arguments.length); - // Ensure the childPath is a string (can be a number) - childPathString = String(childPathString); - validatePathString('DataSnapshot.child', 1, childPathString, false); - var childPath = new Path(childPathString); - var childRef = this.ref_.child(childPath); - return new DataSnapshot(this.node_.getChild(childPath), childRef, PRIORITY_INDEX); - }; - /** - * Returns whether the snapshot contains a child at the specified path. - * - * @param {!string} childPathString Path to a child. - * @return {boolean} Whether the child exists. - */ - DataSnapshot.prototype.hasChild = function (childPathString) { - util.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length); - validatePathString('DataSnapshot.hasChild', 1, childPathString, false); - var childPath = new Path(childPathString); - return !this.node_.getChild(childPath).isEmpty(); - }; - /** - * Returns the priority of the object, or null if no priority was set. - * - * @return {string|number|null} The priority. - */ - DataSnapshot.prototype.getPriority = function () { - util.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length); - // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY) - return this.node_.getPriority().val(); - }; - /** - * Iterates through child nodes and calls the specified action for each one. - * - * @param {function(!DataSnapshot)} action Callback function to be called - * for each child. - * @return {boolean} True if forEach was canceled by action returning true for - * one of the child nodes. - */ - DataSnapshot.prototype.forEach = function (action) { - var _this = this; - util.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length); - util.validateCallback('DataSnapshot.forEach', 1, action, false); - if (this.node_.isLeafNode()) - return false; - var childrenNode = this.node_; - // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type... - return !!childrenNode.forEachChild(this.index_, function (key, node) { - return action(new DataSnapshot(node, _this.ref_.child(key), PRIORITY_INDEX)); - }); - }; - /** - * Returns whether this DataSnapshot has children. - * @return {boolean} True if the DataSnapshot contains 1 or more child nodes. - */ - DataSnapshot.prototype.hasChildren = function () { - util.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length); - if (this.node_.isLeafNode()) - return false; - else - return !this.node_.isEmpty(); - }; - Object.defineProperty(DataSnapshot.prototype, "key", { - get: function () { - return this.ref_.getKey(); - }, - enumerable: true, - configurable: true - }); - /** - * Returns the number of children for this DataSnapshot. - * @return {number} The number of children that this DataSnapshot contains. - */ - DataSnapshot.prototype.numChildren = function () { - util.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length); - return this.node_.numChildren(); - }; - /** - * @return {Reference} The Firebase reference for the location this snapshot's data came from. - */ - DataSnapshot.prototype.getRef = function () { - util.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length); - return this.ref_; - }; - Object.defineProperty(DataSnapshot.prototype, "ref", { - get: function () { - return this.getRef(); - }, - enumerable: true, - configurable: true - }); - return DataSnapshot; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Encapsulates the data needed to raise an event - * @implements {Event} - */ -var DataEvent = /** @class */ (function () { - /** - * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed - * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided - * @param {!DataSnapshot} snapshot The data backing the event - * @param {?string=} prevName Optional, the name of the previous child for child_* events. - */ - function DataEvent(eventType, eventRegistration, snapshot, prevName) { - this.eventType = eventType; - this.eventRegistration = eventRegistration; - this.snapshot = snapshot; - this.prevName = prevName; - } - /** - * @inheritDoc - */ - DataEvent.prototype.getPath = function () { - var ref = this.snapshot.getRef(); - if (this.eventType === 'value') { - return ref.path; - } - else { - return ref.getParent().path; - } - }; - /** - * @inheritDoc - */ - DataEvent.prototype.getEventType = function () { - return this.eventType; - }; - /** - * @inheritDoc - */ - DataEvent.prototype.getEventRunner = function () { - return this.eventRegistration.getEventRunner(this); - }; - /** - * @inheritDoc - */ - DataEvent.prototype.toString = function () { - return (this.getPath().toString() + - ':' + - this.eventType + - ':' + - util.stringify(this.snapshot.exportVal())); - }; - return DataEvent; -}()); -var CancelEvent = /** @class */ (function () { - /** - * @param {EventRegistration} eventRegistration - * @param {Error} error - * @param {!Path} path - */ - function CancelEvent(eventRegistration, error, path) { - this.eventRegistration = eventRegistration; - this.error = error; - this.path = path; - } - /** - * @inheritDoc - */ - CancelEvent.prototype.getPath = function () { - return this.path; - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.getEventType = function () { - return 'cancel'; - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.getEventRunner = function () { - return this.eventRegistration.getEventRunner(this); - }; - /** - * @inheritDoc - */ - CancelEvent.prototype.toString = function () { - return this.path.toString() + ':cancel'; - }; - return CancelEvent; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Represents registration for 'value' events. - */ -var ValueEventRegistration = /** @class */ (function () { - /** - * @param {?function(!DataSnapshot)} callback_ - * @param {?function(Error)} cancelCallback_ - * @param {?Object} context_ - */ - function ValueEventRegistration(callback_, cancelCallback_, context_) { - this.callback_ = callback_; - this.cancelCallback_ = cancelCallback_; - this.context_ = context_; - } - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.respondsTo = function (eventType) { - return eventType === 'value'; - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.createEvent = function (change, query) { - var index = query.getQueryParams().getIndex(); - return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, query.getRef(), index)); - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.getEventRunner = function (eventData) { - var ctx = this.context_; - if (eventData.getEventType() === 'cancel') { - util.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback'); - var cancelCB_1 = this.cancelCallback_; - return function () { - // We know that error exists, we checked above that this is a cancel event - cancelCB_1.call(ctx, eventData.error); - }; - } - else { - var cb_1 = this.callback_; - return function () { - cb_1.call(ctx, eventData.snapshot); - }; - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.createCancelEvent = function (error, path) { - if (this.cancelCallback_) { - return new CancelEvent(this, error, path); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.matches = function (other) { - if (!(other instanceof ValueEventRegistration)) { - return false; - } - else if (!other.callback_ || !this.callback_) { - // If no callback specified, we consider it to match any callback. - return true; - } - else { - return (other.callback_ === this.callback_ && other.context_ === this.context_); - } - }; - /** - * @inheritDoc - */ - ValueEventRegistration.prototype.hasAnyCallback = function () { - return this.callback_ !== null; - }; - return ValueEventRegistration; -}()); -/** - * Represents the registration of 1 or more child_xxx events. - * - * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you - * register a group of callbacks together in the future. - * - * @constructor - * @implements {EventRegistration} - */ -var ChildEventRegistration = /** @class */ (function () { - /** - * @param {?Object.} callbacks_ - * @param {?function(Error)} cancelCallback_ - * @param {Object=} context_ - */ - function ChildEventRegistration(callbacks_, cancelCallback_, context_) { - this.callbacks_ = callbacks_; - this.cancelCallback_ = cancelCallback_; - this.context_ = context_; - } - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.respondsTo = function (eventType) { - var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType; - eventToCheck = - eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck; - return util.contains(this.callbacks_, eventToCheck); - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.createCancelEvent = function (error, path) { - if (this.cancelCallback_) { - return new CancelEvent(this, error, path); - } - else { - return null; - } - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.createEvent = function (change, query) { - util.assert(change.childName != null, 'Child events should have a childName.'); - var ref = query.getRef().child(/** @type {!string} */ (change.childName)); - var index = query.getQueryParams().getIndex(); - return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, ref, index), change.prevName); - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.getEventRunner = function (eventData) { - var ctx = this.context_; - if (eventData.getEventType() === 'cancel') { - util.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback'); - var cancelCB_2 = this.cancelCallback_; - return function () { - // We know that error exists, we checked above that this is a cancel event - cancelCB_2.call(ctx, eventData.error); - }; - } - else { - var cb_2 = this.callbacks_[eventData.eventType]; - return function () { - cb_2.call(ctx, eventData.snapshot, eventData.prevName); - }; - } - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.matches = function (other) { - if (other instanceof ChildEventRegistration) { - if (!this.callbacks_ || !other.callbacks_) { - return true; - } - else if (this.context_ === other.context_) { - var otherCount = util.getCount(other.callbacks_); - var thisCount = util.getCount(this.callbacks_); - if (otherCount === thisCount) { - // If count is 1, do an exact match on eventType, if either is defined but null, it's a match. - // If event types don't match, not a match - // If count is not 1, exact match across all - if (otherCount === 1) { - var otherKey /** @type {!string} */ = util.getAnyKey(other.callbacks_); - var thisKey /** @type {!string} */ = util.getAnyKey(this.callbacks_); - return (thisKey === otherKey && - (!other.callbacks_[otherKey] || - !this.callbacks_[thisKey] || - other.callbacks_[otherKey] === this.callbacks_[thisKey])); - } - else { - // Exact match on each key. - return util.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; }); - } - } - } - } - return false; - }; - /** - * @inheritDoc - */ - ChildEventRegistration.prototype.hasAnyCallback = function () { - return this.callbacks_ !== null; - }; - return ChildEventRegistration; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __referenceConstructor; -/** - * A Query represents a filter to be applied to a firebase location. This object purely represents the - * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. - * - * Since every Firebase reference is a query, Firebase inherits from this object. - */ -var Query = /** @class */ (function () { - function Query(repo, path, queryParams_, orderByCalled_) { - this.repo = repo; - this.path = path; - this.queryParams_ = queryParams_; - this.orderByCalled_ = orderByCalled_; - } - Object.defineProperty(Query, "__referenceConstructor", { - get: function () { - util.assert(__referenceConstructor, 'Reference.ts has not been loaded'); - return __referenceConstructor; - }, - set: function (val) { - __referenceConstructor = val; - }, - enumerable: true, - configurable: true - }); - /** - * Validates start/end values for queries. - * @param {!QueryParams} params - * @private - */ - Query.validateQueryEndpoints_ = function (params) { - var startNode = null; - var endNode = null; - if (params.hasStart()) { - startNode = params.getIndexStartValue(); - } - if (params.hasEnd()) { - endNode = params.getIndexEndValue(); - } - if (params.getIndex() === KEY_INDEX) { - var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' + - 'startAt(), endAt(), or equalTo().'; - var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' + - 'or equalTo() must be a string.'; - if (params.hasStart()) { - var startName = params.getIndexStartName(); - if (startName != MIN_NAME) { - throw new Error(tooManyArgsError); - } - else if (typeof startNode !== 'string') { - throw new Error(wrongArgTypeError); - } - } - if (params.hasEnd()) { - var endName = params.getIndexEndName(); - if (endName != MAX_NAME) { - throw new Error(tooManyArgsError); - } - else if (typeof endNode !== 'string') { - throw new Error(wrongArgTypeError); - } - } - } - else if (params.getIndex() === PRIORITY_INDEX) { - if ((startNode != null && !isValidPriority(startNode)) || - (endNode != null && !isValidPriority(endNode))) { - throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' + - 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).'); - } - } - else { - util.assert(params.getIndex() instanceof PathIndex || - params.getIndex() === VALUE_INDEX, 'unknown index type.'); - if ((startNode != null && typeof startNode === 'object') || - (endNode != null && typeof endNode === 'object')) { - throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' + - 'an object.'); - } - } - }; - /** - * Validates that limit* has been called with the correct combination of parameters - * @param {!QueryParams} params - * @private - */ - Query.validateLimit_ = function (params) { - if (params.hasStart() && - params.hasEnd() && - params.hasLimit() && - !params.hasAnchoredLimit()) { - throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead."); - } - }; - /** - * Validates that no other order by call has been made - * @param {!string} fnName - * @private - */ - Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) { - if (this.orderByCalled_ === true) { - throw new Error(fnName + ": You can't combine multiple orderBy calls."); - } - }; - /** - * @return {!QueryParams} - */ - Query.prototype.getQueryParams = function () { - return this.queryParams_; - }; - /** - * @return {!Reference} - */ - Query.prototype.getRef = function () { - util.validateArgCount('Query.ref', 0, 0, arguments.length); - // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query. - // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this - // method gets called. - return new Query.__referenceConstructor(this.repo, this.path); - }; - /** - * @param {!string} eventType - * @param {!function(DataSnapshot, string=)} callback - * @param {(function(Error)|Object)=} cancelCallbackOrContext - * @param {Object=} context - * @return {!function(DataSnapshot, string=)} - */ - Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) { - util.validateArgCount('Query.on', 2, 4, arguments.length); - validateEventType('Query.on', 1, eventType, false); - util.validateCallback('Query.on', 2, callback, false); - var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context); - if (eventType === 'value') { - this.onValueEvent(callback, ret.cancel, ret.context); - } - else { - var callbacks = {}; - callbacks[eventType] = callback; - this.onChildEvent(callbacks, ret.cancel, ret.context); - } - return callback; - }; - /** - * @param {!function(!DataSnapshot)} callback - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - Query.prototype.onValueEvent = function (callback, cancelCallback, context) { - var container = new ValueEventRegistration(callback, cancelCallback || null, context || null); - this.repo.addEventCallbackForQuery(this, container); - }; - /** - * @param {!Object.} callbacks - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) { - var container = new ChildEventRegistration(callbacks, cancelCallback, context); - this.repo.addEventCallbackForQuery(this, container); - }; - /** - * @param {string=} eventType - * @param {(function(!DataSnapshot, ?string=))=} callback - * @param {Object=} context - */ - Query.prototype.off = function (eventType, callback, context) { - util.validateArgCount('Query.off', 0, 3, arguments.length); - validateEventType('Query.off', 1, eventType, true); - util.validateCallback('Query.off', 2, callback, true); - util.validateContextObject('Query.off', 3, context, true); - var container = null; - var callbacks = null; - if (eventType === 'value') { - var valueCallback = callback || null; - container = new ValueEventRegistration(valueCallback, null, context || null); - } - else if (eventType) { - if (callback) { - callbacks = {}; - callbacks[eventType] = callback; - } - container = new ChildEventRegistration(callbacks, null, context || null); - } - this.repo.removeEventCallbackForQuery(this, container); - }; - /** - * Attaches a listener, waits for the first event, and then removes the listener - * @param {!string} eventType - * @param {!function(!DataSnapshot, string=)} userCallback - * @param cancelOrContext - * @param context - * @return {!firebase.Promise} - */ - Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) { - var _this = this; - util.validateArgCount('Query.once', 1, 4, arguments.length); - validateEventType('Query.once', 1, eventType, false); - util.validateCallback('Query.once', 2, userCallback, true); - var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context); - // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event) - // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change - // because the API currently expects callbacks will be called synchronously if the data is cached, but this is - // against the Promise specification. - var firstCall = true; - var deferred = new util.Deferred(); - // A dummy error handler in case a user wasn't expecting promises - deferred.promise.catch(function () { }); - var onceCallback = function (snapshot) { - // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON) - // triggers multiple events (e.g. child_added or child_changed). - if (firstCall) { - firstCall = false; - _this.off(eventType, onceCallback); - if (userCallback) { - userCallback.bind(ret.context)(snapshot); - } - deferred.resolve(snapshot); - } - }; - this.on(eventType, onceCallback, - /*cancel=*/ function (err) { - _this.off(eventType, onceCallback); - if (ret.cancel) - ret.cancel.bind(ret.context)(err); - deferred.reject(err); - }); - return deferred.promise; - }; - /** - * Set a limit and anchor it to the start of the window. - * @param {!number} limit - * @return {!Query} - */ - Query.prototype.limitToFirst = function (limit) { - util.validateArgCount('Query.limitToFirst', 1, 1, arguments.length); - if (typeof limit !== 'number' || - Math.floor(limit) !== limit || - limit <= 0) { - throw new Error('Query.limitToFirst: First argument must be a positive integer.'); - } - if (this.queryParams_.hasLimit()) { - throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' + - 'limitToFirst, or limitToLast).'); - } - return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_); - }; - /** - * Set a limit and anchor it to the end of the window. - * @param {!number} limit - * @return {!Query} - */ - Query.prototype.limitToLast = function (limit) { - util.validateArgCount('Query.limitToLast', 1, 1, arguments.length); - if (typeof limit !== 'number' || - Math.floor(limit) !== limit || - limit <= 0) { - throw new Error('Query.limitToLast: First argument must be a positive integer.'); - } - if (this.queryParams_.hasLimit()) { - throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' + - 'limitToFirst, or limitToLast).'); - } - return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_); - }; - /** - * Given a child path, return a new query ordered by the specified grandchild path. - * @param {!string} path - * @return {!Query} - */ - Query.prototype.orderByChild = function (path) { - util.validateArgCount('Query.orderByChild', 1, 1, arguments.length); - if (path === '$key') { - throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKey() instead.'); - } - else if (path === '$priority') { - throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.orderByPriority() instead.'); - } - else if (path === '$value') { - throw new Error('Query.orderByChild: "$value" is invalid. Use Query.orderByValue() instead.'); - } - validatePathString('Query.orderByChild', 1, path, false); - this.validateNoPreviousOrderByCall_('Query.orderByChild'); - var parsedPath = new Path(path); - if (parsedPath.isEmpty()) { - throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.'); - } - var index = new PathIndex(parsedPath); - var newParams = this.queryParams_.orderBy(index); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the KeyIndex - * @return {!Query} - */ - Query.prototype.orderByKey = function () { - util.validateArgCount('Query.orderByKey', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByKey'); - var newParams = this.queryParams_.orderBy(KEY_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the PriorityIndex - * @return {!Query} - */ - Query.prototype.orderByPriority = function () { - util.validateArgCount('Query.orderByPriority', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByPriority'); - var newParams = this.queryParams_.orderBy(PRIORITY_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * Return a new query ordered by the ValueIndex - * @return {!Query} - */ - Query.prototype.orderByValue = function () { - util.validateArgCount('Query.orderByValue', 0, 0, arguments.length); - this.validateNoPreviousOrderByCall_('Query.orderByValue'); - var newParams = this.queryParams_.orderBy(VALUE_INDEX); - Query.validateQueryEndpoints_(newParams); - return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true); - }; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - Query.prototype.startAt = function (value, name) { - if (value === void 0) { value = null; } - util.validateArgCount('Query.startAt', 0, 2, arguments.length); - validateFirebaseDataArg('Query.startAt', 1, value, this.path, true); - validateKey('Query.startAt', 2, name, true); - var newParams = this.queryParams_.startAt(value, name); - Query.validateLimit_(newParams); - Query.validateQueryEndpoints_(newParams); - if (this.queryParams_.hasStart()) { - throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' + - 'or equalTo).'); - } - // Calling with no params tells us to start at the beginning. - if (value === undefined) { - value = null; - name = null; - } - return new Query(this.repo, this.path, newParams, this.orderByCalled_); - }; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - Query.prototype.endAt = function (value, name) { - if (value === void 0) { value = null; } - util.validateArgCount('Query.endAt', 0, 2, arguments.length); - validateFirebaseDataArg('Query.endAt', 1, value, this.path, true); - validateKey('Query.endAt', 2, name, true); - var newParams = this.queryParams_.endAt(value, name); - Query.validateLimit_(newParams); - Query.validateQueryEndpoints_(newParams); - if (this.queryParams_.hasEnd()) { - throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' + - 'equalTo).'); - } - return new Query(this.repo, this.path, newParams, this.orderByCalled_); - }; - /** - * Load the selection of children with exactly the specified value, and, optionally, - * the specified name. - * @param {number|string|boolean|null} value - * @param {string=} name - * @return {!Query} - */ - Query.prototype.equalTo = function (value, name) { - util.validateArgCount('Query.equalTo', 1, 2, arguments.length); - validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false); - validateKey('Query.equalTo', 2, name, true); - if (this.queryParams_.hasStart()) { - throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' + - 'equalTo).'); - } - if (this.queryParams_.hasEnd()) { - throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' + - 'equalTo).'); - } - return this.startAt(value, name).endAt(value, name); - }; - /** - * @return {!string} URL for this location. - */ - Query.prototype.toString = function () { - util.validateArgCount('Query.toString', 0, 0, arguments.length); - return this.repo.toString() + this.path.toUrlEncodedString(); - }; - // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary - // for end-users. - Query.prototype.toJSON = function () { - // An optional spacer argument is unnecessary for a string. - util.validateArgCount('Query.toJSON', 0, 1, arguments.length); - return this.toString(); - }; - /** - * An object representation of the query parameters used by this Query. - * @return {!Object} - */ - Query.prototype.queryObject = function () { - return this.queryParams_.getQueryObject(); - }; - /** - * @return {!string} - */ - Query.prototype.queryIdentifier = function () { - var obj = this.queryObject(); - var id = ObjectToUniqueKey(obj); - return id === '{}' ? 'default' : id; - }; - /** - * Return true if this query and the provided query are equivalent; otherwise, return false. - * @param {Query} other - * @return {boolean} - */ - Query.prototype.isEqual = function (other) { - util.validateArgCount('Query.isEqual', 1, 1, arguments.length); - if (!(other instanceof Query)) { - var error$$1 = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.'; - throw new Error(error$$1); - } - var sameRepo = this.repo === other.repo; - var samePath = this.path.equals(other.path); - var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier(); - return sameRepo && samePath && sameQueryIdentifier; - }; - /** - * Helper used by .on and .once to extract the context and or cancel arguments. - * @param {!string} fnName The function name (on or once) - * @param {(function(Error)|Object)=} cancelOrContext - * @param {Object=} context - * @return {{cancel: ?function(Error), context: ?Object}} - * @private - */ - Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) { - var ret = { cancel: null, context: null }; - if (cancelOrContext && context) { - ret.cancel = cancelOrContext; - util.validateCallback(fnName, 3, ret.cancel, true); - ret.context = context; - util.validateContextObject(fnName, 4, ret.context, true); - } - else if (cancelOrContext) { - // we have either a cancel callback or a context. - if (typeof cancelOrContext === 'object' && cancelOrContext !== null) { - // it's a context! - ret.context = cancelOrContext; - } - else if (typeof cancelOrContext === 'function') { - ret.cancel = cancelOrContext; - } - else { - throw new Error(util.errorPrefix(fnName, 3, true) + - ' must either be a cancel callback or a context object.'); - } - } - return ret; - }; - Object.defineProperty(Query.prototype, "ref", { - get: function () { - return this.getRef(); - }, - enumerable: true, - configurable: true - }); - return Query; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Implements a set with a count of elements. - * - * @template K, V - */ -var CountedSet = /** @class */ (function () { - function CountedSet() { - this.set = {}; - } - /** - * @param {!K} item - * @param {V} val - */ - CountedSet.prototype.add = function (item, val) { - this.set[item] = val !== null ? val : true; - }; - /** - * @param {!K} key - * @return {boolean} - */ - CountedSet.prototype.contains = function (key) { - return util.contains(this.set, key); - }; - /** - * @param {!K} item - * @return {V} - */ - CountedSet.prototype.get = function (item) { - return this.contains(item) ? this.set[item] : undefined; - }; - /** - * @param {!K} item - */ - CountedSet.prototype.remove = function (item) { - delete this.set[item]; - }; - /** - * Deletes everything in the set - */ - CountedSet.prototype.clear = function () { - this.set = {}; - }; - /** - * True if there's nothing in the set - * @return {boolean} - */ - CountedSet.prototype.isEmpty = function () { - return util.isEmpty(this.set); - }; - /** - * @return {number} The number of items in the set - */ - CountedSet.prototype.count = function () { - return util.getCount(this.set); - }; - /** - * Run a function on each k,v pair in the set - * @param {function(K, V)} fn - */ - CountedSet.prototype.each = function (fn) { - util.forEach(this.set, function (k, v) { return fn(k, v); }); - }; - /** - * Mostly for debugging - * @return {Array.} The keys present in this CountedSet - */ - CountedSet.prototype.keys = function () { - var keys = []; - util.forEach(this.set, function (k) { - keys.push(k); - }); - return keys; - }; - return CountedSet; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Helper class to store a sparse set of snapshots. - * - * @constructor - */ -var SparseSnapshotTree = /** @class */ (function () { - function SparseSnapshotTree() { - /** - * @private - * @type {Node} - */ - this.value_ = null; - /** - * @private - * @type {CountedSet} - */ - this.children_ = null; - } - /** - * Gets the node stored at the given path if one exists. - * - * @param {!Path} path Path to look up snapshot for. - * @return {?Node} The retrieved node, or null. - */ - SparseSnapshotTree.prototype.find = function (path) { - if (this.value_ != null) { - return this.value_.getChild(path); - } - else if (!path.isEmpty() && this.children_ != null) { - var childKey = path.getFront(); - path = path.popFront(); - if (this.children_.contains(childKey)) { - var childTree = this.children_.get(childKey); - return childTree.find(path); - } - else { - return null; - } - } - else { - return null; - } - }; - /** - * Stores the given node at the specified path. If there is already a node - * at a shallower path, it merges the new data into that snapshot node. - * - * @param {!Path} path Path to look up snapshot for. - * @param {!Node} data The new data, or null. - */ - SparseSnapshotTree.prototype.remember = function (path, data) { - if (path.isEmpty()) { - this.value_ = data; - this.children_ = null; - } - else if (this.value_ !== null) { - this.value_ = this.value_.updateChild(path, data); - } - else { - if (this.children_ == null) { - this.children_ = new CountedSet(); - } - var childKey = path.getFront(); - if (!this.children_.contains(childKey)) { - this.children_.add(childKey, new SparseSnapshotTree()); - } - var child = this.children_.get(childKey); - path = path.popFront(); - child.remember(path, data); - } - }; - /** - * Purge the data at path from the cache. - * - * @param {!Path} path Path to look up snapshot for. - * @return {boolean} True if this node should now be removed. - */ - SparseSnapshotTree.prototype.forget = function (path) { - if (path.isEmpty()) { - this.value_ = null; - this.children_ = null; - return true; - } - else { - if (this.value_ !== null) { - if (this.value_.isLeafNode()) { - // We're trying to forget a node that doesn't exist - return false; - } - else { - var value = this.value_; - this.value_ = null; - var self_1 = this; - value.forEachChild(PRIORITY_INDEX, function (key, tree) { - self_1.remember(new Path(key), tree); - }); - return this.forget(path); - } - } - else if (this.children_ !== null) { - var childKey = path.getFront(); - path = path.popFront(); - if (this.children_.contains(childKey)) { - var safeToRemove = this.children_.get(childKey).forget(path); - if (safeToRemove) { - this.children_.remove(childKey); - } - } - if (this.children_.isEmpty()) { - this.children_ = null; - return true; - } - else { - return false; - } - } - else { - return true; - } - } - }; - /** - * Recursively iterates through all of the stored tree and calls the - * callback on each one. - * - * @param {!Path} prefixPath Path to look up node for. - * @param {!Function} func The function to invoke for each tree. - */ - SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) { - if (this.value_ !== null) { - func(prefixPath, this.value_); - } - else { - this.forEachChild(function (key, tree) { - var path = new Path(prefixPath.toString() + '/' + key); - tree.forEachTree(path, func); - }); - } - }; - /** - * Iterates through each immediate child and triggers the callback. - * - * @param {!Function} func The function to invoke for each child. - */ - SparseSnapshotTree.prototype.forEachChild = function (func) { - if (this.children_ !== null) { - this.children_.each(function (key, tree) { - func(key, tree); - }); - } - }; - return SparseSnapshotTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Generate placeholders for deferred values. - * @param {?Object} values - * @return {!Object} - */ -var generateWithValues = function (values) { - values = values || {}; - values['timestamp'] = values['timestamp'] || new Date().getTime(); - return values; -}; -/** - * Value to use when firing local events. When writing server values, fire - * local events with an approximate value, otherwise return value as-is. - * @param {(Object|string|number|boolean)} value - * @param {!Object} serverValues - * @return {!(string|number|boolean)} - */ -var resolveDeferredValue = function (value, serverValues) { - if (!value || typeof value !== 'object') { - return value; - } - else { - util.assert('.sv' in value, 'Unexpected leaf node or priority contents'); - return serverValues[value['.sv']]; - } -}; -/** - * Recursively replace all deferred values and priorities in the tree with the - * specified generated replacement values. - * @param {!SparseSnapshotTree} tree - * @param {!Object} serverValues - * @return {!SparseSnapshotTree} - */ -var resolveDeferredValueTree = function (tree, serverValues) { - var resolvedTree = new SparseSnapshotTree(); - tree.forEachTree(new Path(''), function (path, node) { - resolvedTree.remember(path, resolveDeferredValueSnapshot(node, serverValues)); - }); - return resolvedTree; -}; -/** - * Recursively replace all deferred values and priorities in the node with the - * specified generated replacement values. If there are no server values in the node, - * it'll be returned as-is. - * @param {!Node} node - * @param {!Object} serverValues - * @return {!Node} - */ -var resolveDeferredValueSnapshot = function (node, serverValues) { - var rawPri = node.getPriority().val(); - var priority = resolveDeferredValue(rawPri, serverValues); - var newNode; - if (node.isLeafNode()) { - var leafNode = node; - var value = resolveDeferredValue(leafNode.getValue(), serverValues); - if (value !== leafNode.getValue() || - priority !== leafNode.getPriority().val()) { - return new LeafNode(value, nodeFromJSON$1(priority)); - } - else { - return node; - } - } - else { - var childrenNode = node; - newNode = childrenNode; - if (priority !== childrenNode.getPriority().val()) { - newNode = newNode.updatePriority(new LeafNode(priority)); - } - childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - var newChildNode = resolveDeferredValueSnapshot(childNode, serverValues); - if (newChildNode !== childNode) { - newNode = newNode.updateImmediateChild(childName, newChildNode); - } - }); - return newNode; - } -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * - * @enum - */ -var OperationType; -(function (OperationType) { - OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE"; - OperationType[OperationType["MERGE"] = 1] = "MERGE"; - OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE"; - OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE"; -})(OperationType || (OperationType = {})); -/** - * @param {boolean} fromUser - * @param {boolean} fromServer - * @param {?string} queryId - * @param {boolean} tagged - * @constructor - */ -var OperationSource = /** @class */ (function () { - function OperationSource(fromUser, fromServer, queryId, tagged) { - this.fromUser = fromUser; - this.fromServer = fromServer; - this.queryId = queryId; - this.tagged = tagged; - util.assert(!tagged || fromServer, 'Tagged queries must be from server.'); - } - /** - * @const - * @type {!OperationSource} - */ - OperationSource.User = new OperationSource( - /*fromUser=*/ true, false, null, - /*tagged=*/ false); - /** - * @const - * @type {!OperationSource} - */ - OperationSource.Server = new OperationSource(false, - /*fromServer=*/ true, null, - /*tagged=*/ false); - /** - * @param {string} queryId - * @return {!OperationSource} - */ - OperationSource.forServerTaggedQuery = function (queryId) { - return new OperationSource(false, - /*fromServer=*/ true, queryId, - /*tagged=*/ true); - }; - return OperationSource; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var AckUserWrite = /** @class */ (function () { - /** - * - * @param {!Path} path - * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap. - * @param {!boolean} revert - */ - function AckUserWrite( - /**@inheritDoc */ path, - /**@inheritDoc */ affectedTree, - /**@inheritDoc */ revert) { - this.path = path; - this.affectedTree = affectedTree; - this.revert = revert; - /** @inheritDoc */ - this.type = OperationType.ACK_USER_WRITE; - /** @inheritDoc */ - this.source = OperationSource.User; - } - /** - * @inheritDoc - */ - AckUserWrite.prototype.operationForChild = function (childName) { - if (!this.path.isEmpty()) { - util.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.'); - return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert); - } - else if (this.affectedTree.value != null) { - util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.'); - // All child locations are affected as well; just return same operation. - return this; - } - else { - var childTree = this.affectedTree.subtree(new Path(childName)); - return new AckUserWrite(Path.Empty, childTree, this.revert); - } - }; - return AckUserWrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var emptyChildrenSingleton; -/** - * Singleton empty children collection. - * - * @const - * @type {!SortedMap.>} - */ -var EmptyChildren = function () { - if (!emptyChildrenSingleton) { - emptyChildrenSingleton = new SortedMap(stringCompare); - } - return emptyChildrenSingleton; -}; -/** - * A tree with immutable elements. - */ -var ImmutableTree = /** @class */ (function () { - /** - * @template T - * @param {?T} value - * @param {SortedMap.>=} children - */ - function ImmutableTree(value, children) { - if (children === void 0) { children = EmptyChildren(); } - this.value = value; - this.children = children; - } - /** - * @template T - * @param {!Object.} obj - * @return {!ImmutableTree.} - */ - ImmutableTree.fromObject = function (obj) { - var tree = ImmutableTree.Empty; - util.forEach(obj, function (childPath, childSnap) { - tree = tree.set(new Path(childPath), childSnap); - }); - return tree; - }; - /** - * True if the value is empty and there are no children - * @return {boolean} - */ - ImmutableTree.prototype.isEmpty = function () { - return this.value === null && this.children.isEmpty(); - }; - /** - * Given a path and predicate, return the first node and the path to that node - * where the predicate returns true. - * - * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects - * on the way back out, it may be better to pass down a pathSoFar obj. - * - * @param {!Path} relativePath The remainder of the path - * @param {function(T):boolean} predicate The predicate to satisfy to return a - * node - * @return {?{path:!Path, value:!T}} - */ - ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) { - if (this.value != null && predicate(this.value)) { - return { path: Path.Empty, value: this.value }; - } - else { - if (relativePath.isEmpty()) { - return null; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child !== null) { - var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate); - if (childExistingPathAndValue != null) { - var fullPath = new Path(front).child(childExistingPathAndValue.path); - return { path: fullPath, value: childExistingPathAndValue.value }; - } - else { - return null; - } - } - else { - return null; - } - } - } - }; - /** - * Find, if it exists, the shortest subpath of the given path that points a defined - * value in the tree - * @param {!Path} relativePath - * @return {?{path: !Path, value: !T}} - */ - ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) { - return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; }); - }; - /** - * @param {!Path} relativePath - * @return {!ImmutableTree.} The subtree at the given path - */ - ImmutableTree.prototype.subtree = function (relativePath) { - if (relativePath.isEmpty()) { - return this; - } - else { - var front = relativePath.getFront(); - var childTree = this.children.get(front); - if (childTree !== null) { - return childTree.subtree(relativePath.popFront()); - } - else { - return ImmutableTree.Empty; - } - } - }; - /** - * Sets a value at the specified path. - * - * @param {!Path} relativePath Path to set value at. - * @param {?T} toSet Value to set. - * @return {!ImmutableTree.} Resulting tree. - */ - ImmutableTree.prototype.set = function (relativePath, toSet) { - if (relativePath.isEmpty()) { - return new ImmutableTree(toSet, this.children); - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front) || ImmutableTree.Empty; - var newChild = child.set(relativePath.popFront(), toSet); - var newChildren = this.children.insert(front, newChild); - return new ImmutableTree(this.value, newChildren); - } - }; - /** - * Removes the value at the specified path. - * - * @param {!Path} relativePath Path to value to remove. - * @return {!ImmutableTree.} Resulting tree. - */ - ImmutableTree.prototype.remove = function (relativePath) { - if (relativePath.isEmpty()) { - if (this.children.isEmpty()) { - return ImmutableTree.Empty; - } - else { - return new ImmutableTree(null, this.children); - } - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child) { - var newChild = child.remove(relativePath.popFront()); - var newChildren = void 0; - if (newChild.isEmpty()) { - newChildren = this.children.remove(front); - } - else { - newChildren = this.children.insert(front, newChild); - } - if (this.value === null && newChildren.isEmpty()) { - return ImmutableTree.Empty; - } - else { - return new ImmutableTree(this.value, newChildren); - } - } - else { - return this; - } - } - }; - /** - * Gets a value from the tree. - * - * @param {!Path} relativePath Path to get value for. - * @return {?T} Value at path, or null. - */ - ImmutableTree.prototype.get = function (relativePath) { - if (relativePath.isEmpty()) { - return this.value; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front); - if (child) { - return child.get(relativePath.popFront()); - } - else { - return null; - } - } - }; - /** - * Replace the subtree at the specified path with the given new tree. - * - * @param {!Path} relativePath Path to replace subtree for. - * @param {!ImmutableTree} newTree New tree. - * @return {!ImmutableTree} Resulting tree. - */ - ImmutableTree.prototype.setTree = function (relativePath, newTree) { - if (relativePath.isEmpty()) { - return newTree; - } - else { - var front = relativePath.getFront(); - var child = this.children.get(front) || ImmutableTree.Empty; - var newChild = child.setTree(relativePath.popFront(), newTree); - var newChildren = void 0; - if (newChild.isEmpty()) { - newChildren = this.children.remove(front); - } - else { - newChildren = this.children.insert(front, newChild); - } - return new ImmutableTree(this.value, newChildren); - } - }; - /** - * Performs a depth first fold on this tree. Transforms a tree into a single - * value, given a function that operates on the path to a node, an optional - * current value, and a map of child names to folded subtrees - * @template V - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - */ - ImmutableTree.prototype.fold = function (fn) { - return this.fold_(Path.Empty, fn); - }; - /** - * Recursive helper for public-facing fold() method - * @template V - * @param {!Path} pathSoFar - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - * @private - */ - ImmutableTree.prototype.fold_ = function (pathSoFar, fn) { - var accum = {}; - this.children.inorderTraversal(function (childKey, childTree) { - accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn); - }); - return fn(pathSoFar, this.value, accum); - }; - /** - * Find the first matching value on the given path. Return the result of applying f to it. - * @template V - * @param {!Path} path - * @param {!function(!Path, !T):?V} f - * @return {?V} - */ - ImmutableTree.prototype.findOnPath = function (path, f) { - return this.findOnPath_(path, Path.Empty, f); - }; - ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) { - var result = this.value ? f(pathSoFar, this.value) : false; - if (result) { - return result; - } - else { - if (pathToFollow.isEmpty()) { - return null; - } - else { - var front = pathToFollow.getFront(); - var nextChild = this.children.get(front); - if (nextChild) { - return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f); - } - else { - return null; - } - } - } - }; - /** - * - * @param {!Path} path - * @param {!function(!Path, !T)} f - * @returns {!ImmutableTree.} - */ - ImmutableTree.prototype.foreachOnPath = function (path, f) { - return this.foreachOnPath_(path, Path.Empty, f); - }; - ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) { - if (pathToFollow.isEmpty()) { - return this; - } - else { - if (this.value) { - f(currentRelativePath, this.value); - } - var front = pathToFollow.getFront(); - var nextChild = this.children.get(front); - if (nextChild) { - return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f); - } - else { - return ImmutableTree.Empty; - } - } - }; - /** - * Calls the given function for each node in the tree that has a value. - * - * @param {function(!Path, !T)} f A function to be called with - * the path from the root of the tree to a node, and the value at that node. - * Called in depth-first order. - */ - ImmutableTree.prototype.foreach = function (f) { - this.foreach_(Path.Empty, f); - }; - ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) { - this.children.inorderTraversal(function (childName, childTree) { - childTree.foreach_(currentRelativePath.child(childName), f); - }); - if (this.value) { - f(currentRelativePath, this.value); - } - }; - /** - * - * @param {function(string, !T)} f - */ - ImmutableTree.prototype.foreachChild = function (f) { - this.children.inorderTraversal(function (childName, childTree) { - if (childTree.value) { - f(childName, childTree.value); - } - }); - }; - ImmutableTree.Empty = new ImmutableTree(null); - return ImmutableTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @constructor - * @implements {Operation} - */ -var ListenComplete = /** @class */ (function () { - function ListenComplete(source, path) { - this.source = source; - this.path = path; - /** @inheritDoc */ - this.type = OperationType.LISTEN_COMPLETE; - } - ListenComplete.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - return new ListenComplete(this.source, Path.Empty); - } - else { - return new ListenComplete(this.source, this.path.popFront()); - } - }; - return ListenComplete; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!Node} snap - * @constructor - * @implements {Operation} - */ -var Overwrite = /** @class */ (function () { - function Overwrite(source, path, snap) { - this.source = source; - this.path = path; - this.snap = snap; - /** @inheritDoc */ - this.type = OperationType.OVERWRITE; - } - Overwrite.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - return new Overwrite(this.source, Path.Empty, this.snap.getImmediateChild(childName)); - } - else { - return new Overwrite(this.source, this.path.popFront(), this.snap); - } - }; - return Overwrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!ImmutableTree.} children - * @constructor - * @implements {Operation} - */ -var Merge = /** @class */ (function () { - function Merge( - /**@inheritDoc */ source, - /**@inheritDoc */ path, - /**@inheritDoc */ children) { - this.source = source; - this.path = path; - this.children = children; - /** @inheritDoc */ - this.type = OperationType.MERGE; - } - /** - * @inheritDoc - */ - Merge.prototype.operationForChild = function (childName) { - if (this.path.isEmpty()) { - var childTree = this.children.subtree(new Path(childName)); - if (childTree.isEmpty()) { - // This child is unaffected - return null; - } - else if (childTree.value) { - // We have a snapshot for the child in question. This becomes an overwrite of the child. - return new Overwrite(this.source, Path.Empty, childTree.value); - } - else { - // This is a merge at a deeper level - return new Merge(this.source, Path.Empty, childTree); - } - } - else { - util.assert(this.path.getFront() === childName, "Can't get a merge for a child not on the path of the operation"); - return new Merge(this.source, this.path.popFront(), this.children); - } - }; - /** - * @inheritDoc - */ - Merge.prototype.toString = function () { - return ('Operation(' + - this.path + - ': ' + - this.source.toString() + - ' merge: ' + - this.children.toString() + - ')'); - }; - return Merge; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully - * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. - * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks - * whether a node potentially had children removed due to a filter. - */ -var CacheNode = /** @class */ (function () { - /** - * @param {!Node} node_ - * @param {boolean} fullyInitialized_ - * @param {boolean} filtered_ - */ - function CacheNode(node_, fullyInitialized_, filtered_) { - this.node_ = node_; - this.fullyInitialized_ = fullyInitialized_; - this.filtered_ = filtered_; - } - /** - * Returns whether this node was fully initialized with either server data or a complete overwrite by the client - * @return {boolean} - */ - CacheNode.prototype.isFullyInitialized = function () { - return this.fullyInitialized_; - }; - /** - * Returns whether this node is potentially missing children due to a filter applied to the node - * @return {boolean} - */ - CacheNode.prototype.isFiltered = function () { - return this.filtered_; - }; - /** - * @param {!Path} path - * @return {boolean} - */ - CacheNode.prototype.isCompleteForPath = function (path) { - if (path.isEmpty()) { - return this.isFullyInitialized() && !this.filtered_; - } - var childKey = path.getFront(); - return this.isCompleteForChild(childKey); - }; - /** - * @param {!string} key - * @return {boolean} - */ - CacheNode.prototype.isCompleteForChild = function (key) { - return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)); - }; - /** - * @return {!Node} - */ - CacheNode.prototype.getNode = function () { - return this.node_; - }; - return CacheNode; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Stores the data we have cached for a view. - * - * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). - * - * @constructor - */ -var ViewCache = /** @class */ (function () { - /** - * - * @param {!CacheNode} eventCache_ - * @param {!CacheNode} serverCache_ - */ - function ViewCache(eventCache_, serverCache_) { - this.eventCache_ = eventCache_; - this.serverCache_ = serverCache_; - } - /** - * @param {!Node} eventSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) { - return new ViewCache(new CacheNode(eventSnap, complete, filtered), this.serverCache_); - }; - /** - * @param {!Node} serverSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) { - return new ViewCache(this.eventCache_, new CacheNode(serverSnap, complete, filtered)); - }; - /** - * @return {!CacheNode} - */ - ViewCache.prototype.getEventCache = function () { - return this.eventCache_; - }; - /** - * @return {?Node} - */ - ViewCache.prototype.getCompleteEventSnap = function () { - return this.eventCache_.isFullyInitialized() - ? this.eventCache_.getNode() - : null; - }; - /** - * @return {!CacheNode} - */ - ViewCache.prototype.getServerCache = function () { - return this.serverCache_; - }; - /** - * @return {?Node} - */ - ViewCache.prototype.getCompleteServerSnap = function () { - return this.serverCache_.isFullyInitialized() - ? this.serverCache_.getNode() - : null; - }; - /** - * @const - * @type {ViewCache} - */ - ViewCache.Empty = new ViewCache(new CacheNode(ChildrenNode.EMPTY_NODE, - /*fullyInitialized=*/ false, - /*filtered=*/ false), new CacheNode(ChildrenNode.EMPTY_NODE, - /*fullyInitialized=*/ false, - /*filtered=*/ false)); - return ViewCache; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @struct - * @param {!string} type The event type - * @param {!Node} snapshotNode The data - * @param {string=} childName The name for this child, if it's a child event - * @param {Node=} oldSnap Used for intermediate processing of child changed events - * @param {string=} prevName The name for the previous child, if applicable - */ -var Change = /** @class */ (function () { - function Change(type, snapshotNode, childName, oldSnap, prevName) { - this.type = type; - this.snapshotNode = snapshotNode; - this.childName = childName; - this.oldSnap = oldSnap; - this.prevName = prevName; - } - /** - * @param {!Node} snapshot - * @return {!Change} - */ - Change.valueChange = function (snapshot) { - return new Change(Change.VALUE, snapshot); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childAddedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_ADDED, snapshot, childKey); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childRemovedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_REMOVED, snapshot, childKey); - }; - /** - * @param {string} childKey - * @param {!Node} newSnapshot - * @param {!Node} oldSnapshot - * @return {!Change} - */ - Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) { - return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot); - }; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - Change.childMovedChange = function (childKey, snapshot) { - return new Change(Change.CHILD_MOVED, snapshot, childKey); - }; - //event types - /** Event type for a child added */ - Change.CHILD_ADDED = 'child_added'; - /** Event type for a child removed */ - Change.CHILD_REMOVED = 'child_removed'; - /** Event type for a child changed */ - Change.CHILD_CHANGED = 'child_changed'; - /** Event type for a child moved */ - Change.CHILD_MOVED = 'child_moved'; - /** Event type for a value change */ - Change.VALUE = 'value'; - return Change; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Doesn't really filter nodes but applies an index to the node and keeps track of any changes - * - * @constructor - * @implements {NodeFilter} - * @param {!Index} index - */ -var IndexedFilter = /** @class */ (function () { - function IndexedFilter(index_) { - this.index_ = index_; - } - IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated'); - var oldChild = snap.getImmediateChild(key); - // Check if anything actually changed. - if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) { - // There's an edge case where a child can enter or leave the view because affectedPath was set to null. - // In this case, affectedPath will appear null in both the old and new snapshots. So we need - // to avoid treating these cases as "nothing changed." - if (oldChild.isEmpty() == newChild.isEmpty()) { - // Nothing changed. - // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it. - //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.'); - return snap; - } - } - if (optChangeAccumulator != null) { - if (newChild.isEmpty()) { - if (snap.hasChild(key)) { - optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, oldChild)); - } - else { - util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node'); - } - } - else if (oldChild.isEmpty()) { - optChangeAccumulator.trackChildChange(Change.childAddedChange(key, newChild)); - } - else { - optChangeAccumulator.trackChildChange(Change.childChangedChange(key, newChild, oldChild)); - } - } - if (snap.isLeafNode() && newChild.isEmpty()) { - return snap; - } - else { - // Make sure the node is indexed - return snap.updateImmediateChild(key, newChild).withIndex(this.index_); - } - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - if (optChangeAccumulator != null) { - if (!oldSnap.isLeafNode()) { - oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (!newSnap.hasChild(key)) { - optChangeAccumulator.trackChildChange(Change.childRemovedChange(key, childNode)); - } - }); - } - if (!newSnap.isLeafNode()) { - newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (oldSnap.hasChild(key)) { - var oldChild = oldSnap.getImmediateChild(key); - if (!oldChild.equals(childNode)) { - optChangeAccumulator.trackChildChange(Change.childChangedChange(key, childNode, oldChild)); - } - } - else { - optChangeAccumulator.trackChildChange(Change.childAddedChange(key, childNode)); - } - }); - } - } - return newSnap.withIndex(this.index_); - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - if (oldSnap.isEmpty()) { - return ChildrenNode.EMPTY_NODE; - } - else { - return oldSnap.updatePriority(newPriority); - } - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.filtersNodes = function () { - return false; - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.getIndexedFilter = function () { - return this; - }; - /** - * @inheritDoc - */ - IndexedFilter.prototype.getIndex = function () { - return this.index_; - }; - return IndexedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - */ -var ChildChangeAccumulator = /** @class */ (function () { - function ChildChangeAccumulator() { - this.changeMap_ = {}; - } - /** - * @param {!Change} change - */ - ChildChangeAccumulator.prototype.trackChildChange = function (change) { - var type = change.type; - var childKey /** @type {!string} */ = change.childName; - util.assert(type == Change.CHILD_ADDED || - type == Change.CHILD_CHANGED || - type == Change.CHILD_REMOVED, 'Only child changes supported for tracking'); - util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.'); - var oldChange = util.safeGet(this.changeMap_, childKey); - if (oldChange) { - var oldType = oldChange.type; - if (type == Change.CHILD_ADDED && oldType == Change.CHILD_REMOVED) { - this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode); - } - else if (type == Change.CHILD_REMOVED && - oldType == Change.CHILD_ADDED) { - delete this.changeMap_[childKey]; - } - else if (type == Change.CHILD_REMOVED && - oldType == Change.CHILD_CHANGED) { - this.changeMap_[childKey] = Change.childRemovedChange(childKey, oldChange.oldSnap); - } - else if (type == Change.CHILD_CHANGED && - oldType == Change.CHILD_ADDED) { - this.changeMap_[childKey] = Change.childAddedChange(childKey, change.snapshotNode); - } - else if (type == Change.CHILD_CHANGED && - oldType == Change.CHILD_CHANGED) { - this.changeMap_[childKey] = Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap); - } - else { - throw util.assertionError('Illegal combination of changes: ' + - change + - ' occurred after ' + - oldChange); - } - } - else { - this.changeMap_[childKey] = change; - } - }; - /** - * @return {!Array.} - */ - ChildChangeAccumulator.prototype.getChanges = function () { - return util.getValues(this.changeMap_); - }; - return ChildChangeAccumulator; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An implementation of CompleteChildSource that never returns any additional children - * - * @private - * @constructor - * @implements CompleteChildSource - */ -var NoCompleteChildSource_ = /** @class */ (function () { - function NoCompleteChildSource_() { - } - /** - * @inheritDoc - */ - NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) { - return null; - }; - /** - * @inheritDoc - */ - NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) { - return null; - }; - return NoCompleteChildSource_; -}()); -/** - * Singleton instance. - * @const - * @type {!CompleteChildSource} - */ -var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_(); -/** - * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or - * old event caches available to calculate complete children. - * - * - * @implements CompleteChildSource - */ -var WriteTreeCompleteChildSource = /** @class */ (function () { - /** - * @param {!WriteTreeRef} writes_ - * @param {!ViewCache} viewCache_ - * @param {?Node} optCompleteServerCache_ - */ - function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) { - if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; } - this.writes_ = writes_; - this.viewCache_ = viewCache_; - this.optCompleteServerCache_ = optCompleteServerCache_; - } - /** - * @inheritDoc - */ - WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) { - var node = this.viewCache_.getEventCache(); - if (node.isCompleteForChild(childKey)) { - return node.getNode().getImmediateChild(childKey); - } - else { - var serverNode = this.optCompleteServerCache_ != null - ? new CacheNode(this.optCompleteServerCache_, true, false) - : this.viewCache_.getServerCache(); - return this.writes_.calcCompleteChild(childKey, serverNode); - } - }; - /** - * @inheritDoc - */ - WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) { - var completeServerData = this.optCompleteServerCache_ != null - ? this.optCompleteServerCache_ - : this.viewCache_.getCompleteServerSnap(); - var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index); - if (nodes.length === 0) { - return null; - } - else { - return nodes[0]; - } - }; - return WriteTreeCompleteChildSource; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @constructor - * @struct - */ -var ProcessorResult = /** @class */ (function () { - /** - * @param {!ViewCache} viewCache - * @param {!Array.} changes - */ - function ProcessorResult(viewCache, changes) { - this.viewCache = viewCache; - this.changes = changes; - } - return ProcessorResult; -}()); -/** - * @constructor - */ -var ViewProcessor = /** @class */ (function () { - /** - * @param {!NodeFilter} filter_ - */ - function ViewProcessor(filter_) { - this.filter_ = filter_; - } - /** - * @param {!ViewCache} viewCache - */ - ViewProcessor.prototype.assertIndexed = function (viewCache) { - util.assert(viewCache - .getEventCache() - .getNode() - .isIndexed(this.filter_.getIndex()), 'Event snap not indexed'); - util.assert(viewCache - .getServerCache() - .getNode() - .isIndexed(this.filter_.getIndex()), 'Server snap not indexed'); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @return {!ProcessorResult} - */ - ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) { - var accumulator = new ChildChangeAccumulator(); - var newViewCache, filterServerNode; - if (operation.type === OperationType.OVERWRITE) { - var overwrite = operation; - if (overwrite.source.fromUser) { - newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator); - } - else { - util.assert(overwrite.source.fromServer, 'Unknown source.'); - // We filter the node if it's a tagged update or the node has been previously filtered and the - // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered - // again - filterServerNode = - overwrite.source.tagged || - (oldViewCache.getServerCache().isFiltered() && - !overwrite.path.isEmpty()); - newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator); - } - } - else if (operation.type === OperationType.MERGE) { - var merge = operation; - if (merge.source.fromUser) { - newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator); - } - else { - util.assert(merge.source.fromServer, 'Unknown source.'); - // We filter the node if it's a tagged update or the node has been previously filtered - filterServerNode = - merge.source.tagged || oldViewCache.getServerCache().isFiltered(); - newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator); - } - } - else if (operation.type === OperationType.ACK_USER_WRITE) { - var ackUserWrite = operation; - if (!ackUserWrite.revert) { - newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator); - } - else { - newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator); - } - } - else if (operation.type === OperationType.LISTEN_COMPLETE) { - newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator); - } - else { - throw util.assertionError('Unknown operation type: ' + operation.type); - } - var changes = accumulator.getChanges(); - ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes); - return new ProcessorResult(newViewCache, changes); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!ViewCache} newViewCache - * @param {!Array.} accumulator - * @private - */ - ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) { - var eventSnap = newViewCache.getEventCache(); - if (eventSnap.isFullyInitialized()) { - var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty(); - var oldCompleteSnap = oldViewCache.getCompleteEventSnap(); - if (accumulator.length > 0 || - !oldViewCache.getEventCache().isFullyInitialized() || - (isLeafOrEmpty && - !eventSnap - .getNode() - .equals(/** @type {!Node} */ (oldCompleteSnap))) || - !eventSnap - .getNode() - .getPriority() - .equals(oldCompleteSnap.getPriority())) { - accumulator.push(Change.valueChange( - /** @type {!Node} */ newViewCache.getCompleteEventSnap())); - } - } - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} changePath - * @param {!WriteTreeRef} writesCache - * @param {!CompleteChildSource} source - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) { - var oldEventSnap = viewCache.getEventCache(); - if (writesCache.shadowingWrite(changePath) != null) { - // we have a shadowing write, ignore changes - return viewCache; - } - else { - var newEventCache = void 0, serverNode = void 0; - if (changePath.isEmpty()) { - // TODO: figure out how this plays with "sliding ack windows" - util.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data'); - if (viewCache.getServerCache().isFiltered()) { - // We need to special case this, because we need to only apply writes to complete children, or - // we might end up raising events for incomplete children. If the server data is filtered deep - // writes cannot be guaranteed to be complete - var serverCache = viewCache.getCompleteServerSnap(); - var completeChildren = serverCache instanceof ChildrenNode - ? serverCache - : ChildrenNode.EMPTY_NODE; - var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren); - newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator); - } - else { - var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator); - } - } - else { - var childKey = changePath.getFront(); - if (childKey == '.priority') { - util.assert(changePath.getLength() == 1, "Can't have a priority with additional path components"); - var oldEventNode = oldEventSnap.getNode(); - serverNode = viewCache.getServerCache().getNode(); - // we might have overwrites for this priority - var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode); - if (updatedPriority != null) { - newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority); - } - else { - // priority didn't change, keep old node - newEventCache = oldEventSnap.getNode(); - } - } - else { - var childChangePath = changePath.popFront(); - // update child - var newEventChild = void 0; - if (oldEventSnap.isCompleteForChild(childKey)) { - serverNode = viewCache.getServerCache().getNode(); - var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode); - if (eventChildUpdate != null) { - newEventChild = oldEventSnap - .getNode() - .getImmediateChild(childKey) - .updateChild(childChangePath, eventChildUpdate); - } - else { - // Nothing changed, just keep the old child - newEventChild = oldEventSnap - .getNode() - .getImmediateChild(childKey); - } - } - else { - newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache()); - } - if (newEventChild != null) { - newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator); - } - else { - // no complete child available or no change - newEventCache = oldEventSnap.getNode(); - } - } - } - return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes()); - } - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) { - var oldServerSnap = oldViewCache.getServerCache(); - var newServerCache; - var serverFilter = filterServerNode - ? this.filter_ - : this.filter_.getIndexedFilter(); - if (changePath.isEmpty()) { - newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null); - } - else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { - // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update - var newServerNode = oldServerSnap - .getNode() - .updateChild(changePath, changedSnap); - newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null); - } - else { - var childKey = changePath.getFront(); - if (!oldServerSnap.isCompleteForPath(changePath) && - changePath.getLength() > 1) { - // We don't update incomplete nodes with updates intended for other listeners - return oldViewCache; - } - var childChangePath = changePath.popFront(); - var childNode = oldServerSnap.getNode().getImmediateChild(childKey); - var newChildNode = childNode.updateChild(childChangePath, changedSnap); - if (childKey == '.priority') { - newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode); - } - else { - newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null); - } - } - var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes()); - var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache); - return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator); - }; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) { - var oldEventSnap = oldViewCache.getEventCache(); - var newViewCache, newEventCache; - var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache); - if (changePath.isEmpty()) { - newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator); - newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes()); - } - else { - var childKey = changePath.getFront(); - if (childKey === '.priority') { - newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap); - newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered()); - } - else { - var childChangePath = changePath.popFront(); - var oldChild = oldEventSnap.getNode().getImmediateChild(childKey); - var newChild = void 0; - if (childChangePath.isEmpty()) { - // Child overwrite, we can replace the child - newChild = changedSnap; - } - else { - var childNode = source.getCompleteChild(childKey); - if (childNode != null) { - if (childChangePath.getBack() === '.priority' && - childNode.getChild(childChangePath.parent()).isEmpty()) { - // This is a priority update on an empty node. If this node exists on the server, the - // server will send down the priority in the update, so ignore for now - newChild = childNode; - } - else { - newChild = childNode.updateChild(childChangePath, changedSnap); - } - } - else { - // There is no complete child node available - newChild = ChildrenNode.EMPTY_NODE; - } - } - if (!oldChild.equals(newChild)) { - var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator); - newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes()); - } - else { - newViewCache = oldViewCache; - } - } - } - return newViewCache; - }; - /** - * @param {!ViewCache} viewCache - * @param {string} childKey - * @return {boolean} - * @private - */ - ViewProcessor.cacheHasChild_ = function (viewCache, childKey) { - return viewCache.getEventCache().isCompleteForChild(childKey); - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) { - var _this = this; - // HACK: In the case of a limit query, there may be some changes that bump things out of the - // window leaving room for new items. It's important we process these changes first, so we - // iterate the changes twice, first processing any that affect items currently in view. - // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server - // and event snap. I'm not sure if this will result in edge cases when a child is in one but - // not the other. - var curViewCache = viewCache; - changedChildren.foreach(function (relativePath, childNode) { - var writePath = path.child(relativePath); - if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) { - curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator); - } - }); - changedChildren.foreach(function (relativePath, childNode) { - var writePath = path.child(relativePath); - if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) { - curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator); - } - }); - return curViewCache; - }; - /** - * @param {!Node} node - * @param {ImmutableTree.} merge - * @return {!Node} - * @private - */ - ViewProcessor.prototype.applyMerge_ = function (node, merge) { - merge.foreach(function (relativePath, childNode) { - node = node.updateChild(relativePath, childNode); - }); - return node; - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) { - var _this = this; - // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and - // wait for the complete data update coming soon. - if (viewCache - .getServerCache() - .getNode() - .isEmpty() && - !viewCache.getServerCache().isFullyInitialized()) { - return viewCache; - } - // HACK: In the case of a limit query, there may be some changes that bump things out of the - // window leaving room for new items. It's important we process these changes first, so we - // iterate the changes twice, first processing any that affect items currently in view. - // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server - // and event snap. I'm not sure if this will result in edge cases when a child is in one but - // not the other. - var curViewCache = viewCache; - var viewMergeTree; - if (path.isEmpty()) { - viewMergeTree = changedChildren; - } - else { - viewMergeTree = ImmutableTree.Empty.setTree(path, changedChildren); - } - var serverNode = viewCache.getServerCache().getNode(); - viewMergeTree.children.inorderTraversal(function (childKey, childTree) { - if (serverNode.hasChild(childKey)) { - var serverChild = viewCache - .getServerCache() - .getNode() - .getImmediateChild(childKey); - var newChild = _this.applyMerge_(serverChild, childTree); - curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); - } - }); - viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) { - var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) && - childMergeTree.value == null; - if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { - var serverChild = viewCache - .getServerCache() - .getNode() - .getImmediateChild(childKey); - var newChild = _this.applyMerge_(serverChild, childMergeTree); - curViewCache = _this.applyServerOverwrite_(curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator); - } - }); - return curViewCache; - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} ackPath - * @param {!ImmutableTree} affectedTree - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) { - if (writesCache.shadowingWrite(ackPath) != null) { - return viewCache; - } - // Only filter server node if it is currently filtered - var filterServerNode = viewCache.getServerCache().isFiltered(); - // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update - // now that it won't be shadowed. - var serverCache = viewCache.getServerCache(); - if (affectedTree.value != null) { - // This is an overwrite. - if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) || - serverCache.isCompleteForPath(ackPath)) { - return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator); - } - else if (ackPath.isEmpty()) { - // This is a goofy edge case where we are acking data at this location but don't have full data. We - // should just re-apply whatever we have in our cache as a merge. - var changedChildren_1 = ImmutableTree.Empty; - serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) { - changedChildren_1 = changedChildren_1.set(new Path(name), node); - }); - return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator); - } - else { - return viewCache; - } - } - else { - // This is a merge. - var changedChildren_2 = ImmutableTree.Empty; - affectedTree.foreach(function (mergePath, value) { - var serverCachePath = ackPath.child(mergePath); - if (serverCache.isCompleteForPath(serverCachePath)) { - changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath)); - } - }); - return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator); - } - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) { - var oldServerNode = viewCache.getServerCache(); - var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered()); - return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator); - }; - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) { - var complete; - if (writesCache.shadowingWrite(path) != null) { - return viewCache; - } - else { - var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache); - var oldEventCache = viewCache.getEventCache().getNode(); - var newEventCache = void 0; - if (path.isEmpty() || path.getFront() === '.priority') { - var newNode = void 0; - if (viewCache.getServerCache().isFullyInitialized()) { - newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - } - else { - var serverChildren = viewCache.getServerCache().getNode(); - util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node'); - newNode = writesCache.calcCompleteEventChildren(serverChildren); - } - newNode = newNode; - newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator); - } - else { - var childKey = path.getFront(); - var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache()); - if (newChild == null && - viewCache.getServerCache().isCompleteForChild(childKey)) { - newChild = oldEventCache.getImmediateChild(childKey); - } - if (newChild != null) { - newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator); - } - else if (viewCache - .getEventCache() - .getNode() - .hasChild(childKey)) { - // No complete child available, delete the existing one, if any - newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator); - } - else { - newEventCache = oldEventCache; - } - if (newEventCache.isEmpty() && - viewCache.getServerCache().isFullyInitialized()) { - // We might have reverted all child writes. Maybe the old event was a leaf node - complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap()); - if (complete.isLeafNode()) { - newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator); - } - } - } - complete = - viewCache.getServerCache().isFullyInitialized() || - writesCache.shadowingWrite(Path.Empty) != null; - return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes()); - } - }; - return ViewProcessor; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An EventGenerator is used to convert "raw" changes (Change) as computed by the - * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() - * for details. - * - * @constructor - */ -var EventGenerator = /** @class */ (function () { - /** - * - * @param {!Query} query_ - */ - function EventGenerator(query_) { - this.query_ = query_; - /** - * @private - * @type {!Index} - */ - this.index_ = this.query_.getQueryParams().getIndex(); - } - /** - * Given a set of raw changes (no moved events and prevName not specified yet), and a set of - * EventRegistrations that should be notified of these changes, generate the actual events to be raised. - * - * Notes: - * - child_moved events will be synthesized at this time for any child_changed events that affect - * our index. - * - prevName will be calculated based on the index ordering. - * - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {!Array.} eventRegistrations - * @return {!Array.} - */ - EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) { - var _this = this; - var events = []; - var moves = []; - changes.forEach(function (change) { - if (change.type === Change.CHILD_CHANGED && - _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) { - moves.push(Change.childMovedChange(change.childName, change.snapshotNode)); - } - }); - this.generateEventsForType_(events, Change.CHILD_REMOVED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_ADDED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_MOVED, moves, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.CHILD_CHANGED, changes, eventRegistrations, eventCache); - this.generateEventsForType_(events, Change.VALUE, changes, eventRegistrations, eventCache); - return events; - }; - /** - * Given changes of a single change type, generate the corresponding events. - * - * @param {!Array.} events - * @param {!string} eventType - * @param {!Array.} changes - * @param {!Array.} registrations - * @param {!Node} eventCache - * @private - */ - EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) { - var _this = this; - var filteredChanges = changes.filter(function (change) { return change.type === eventType; }); - filteredChanges.sort(this.compareChanges_.bind(this)); - filteredChanges.forEach(function (change) { - var materializedChange = _this.materializeSingleChange_(change, eventCache); - registrations.forEach(function (registration) { - if (registration.respondsTo(change.type)) { - events.push(registration.createEvent(materializedChange, _this.query_)); - } - }); - }); - }; - /** - * @param {!Change} change - * @param {!Node} eventCache - * @return {!Change} - * @private - */ - EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) { - if (change.type === 'value' || change.type === 'child_removed') { - return change; - } - else { - change.prevName = eventCache.getPredecessorChildName( - /** @type {!string} */ - change.childName, change.snapshotNode, this.index_); - return change; - } - }; - /** - * @param {!Change} a - * @param {!Change} b - * @return {number} - * @private - */ - EventGenerator.prototype.compareChanges_ = function (a, b) { - if (a.childName == null || b.childName == null) { - throw util.assertionError('Should only compare child_ events.'); - } - var aWrapped = new NamedNode(a.childName, a.snapshotNode); - var bWrapped = new NamedNode(b.childName, b.snapshotNode); - return this.index_.compare(aWrapped, bWrapped); - }; - return EventGenerator; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A view represents a specific location and query that has 1 or more event registrations. - * - * It does several things: - * - Maintains the list of event registrations for this location/query. - * - Maintains a cache of the data visible for this location/query. - * - Applies new operations (via applyOperation), updates the cache, and based on the event - * registrations returns the set of events to be raised. - * @constructor - */ -var View = /** @class */ (function () { - /** - * - * @param {!Query} query_ - * @param {!ViewCache} initialViewCache - */ - function View(query_, initialViewCache) { - this.query_ = query_; - this.eventRegistrations_ = []; - var params = this.query_.getQueryParams(); - var indexFilter = new IndexedFilter(params.getIndex()); - var filter = params.getNodeFilter(); - /** - * @type {ViewProcessor} - * @private - */ - this.processor_ = new ViewProcessor(filter); - var initialServerCache = initialViewCache.getServerCache(); - var initialEventCache = initialViewCache.getEventCache(); - // Don't filter server node with other filter than index, wait for tagged listen - var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null); - var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null); - var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes()); - var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes()); - /** - * @type {!ViewCache} - * @private - */ - this.viewCache_ = new ViewCache(newEventCache, newServerCache); - /** - * @type {!EventGenerator} - * @private - */ - this.eventGenerator_ = new EventGenerator(this.query_); - } - /** - * @return {!Query} - */ - View.prototype.getQuery = function () { - return this.query_; - }; - /** - * @return {?Node} - */ - View.prototype.getServerCache = function () { - return this.viewCache_.getServerCache().getNode(); - }; - /** - * @param {!Path} path - * @return {?Node} - */ - View.prototype.getCompleteServerCache = function (path) { - var cache = this.viewCache_.getCompleteServerSnap(); - if (cache) { - // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and - // we need to see if it contains the child we're interested in. - if (this.query_.getQueryParams().loadsAllData() || - (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) { - return cache.getChild(path); - } - } - return null; - }; - /** - * @return {boolean} - */ - View.prototype.isEmpty = function () { - return this.eventRegistrations_.length === 0; - }; - /** - * @param {!EventRegistration} eventRegistration - */ - View.prototype.addEventRegistration = function (eventRegistration) { - this.eventRegistrations_.push(eventRegistration); - }; - /** - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - View.prototype.removeEventRegistration = function (eventRegistration, cancelError) { - var cancelEvents = []; - if (cancelError) { - util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.'); - var path_1 = this.query_.path; - this.eventRegistrations_.forEach(function (registration) { - cancelError /** @type {!Error} */ = cancelError; - var maybeEvent = registration.createCancelEvent(cancelError, path_1); - if (maybeEvent) { - cancelEvents.push(maybeEvent); - } - }); - } - if (eventRegistration) { - var remaining = []; - for (var i = 0; i < this.eventRegistrations_.length; ++i) { - var existing = this.eventRegistrations_[i]; - if (!existing.matches(eventRegistration)) { - remaining.push(existing); - } - else if (eventRegistration.hasAnyCallback()) { - // We're removing just this one - remaining = remaining.concat(this.eventRegistrations_.slice(i + 1)); - break; - } - } - this.eventRegistrations_ = remaining; - } - else { - this.eventRegistrations_ = []; - } - return cancelEvents; - }; - /** - * Applies the given Operation, updates our cache, and returns the appropriate events. - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @return {!Array.} - */ - View.prototype.applyOperation = function (operation, writesCache, completeServerCache) { - if (operation.type === OperationType.MERGE && - operation.source.queryId !== null) { - util.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges'); - util.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache'); - } - var oldViewCache = this.viewCache_; - var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache); - this.processor_.assertIndexed(result.viewCache); - util.assert(result.viewCache.getServerCache().isFullyInitialized() || - !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back'); - this.viewCache_ = result.viewCache; - return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null); - }; - /** - * @param {!EventRegistration} registration - * @return {!Array.} - */ - View.prototype.getInitialEvents = function (registration) { - var eventSnap = this.viewCache_.getEventCache(); - var initialChanges = []; - if (!eventSnap.getNode().isLeafNode()) { - var eventNode = eventSnap.getNode(); - eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) { - initialChanges.push(Change.childAddedChange(key, childNode)); - }); - } - if (eventSnap.isFullyInitialized()) { - initialChanges.push(Change.valueChange(eventSnap.getNode())); - } - return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration); - }; - /** - * @private - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {EventRegistration=} eventRegistration - * @return {!Array.} - */ - View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) { - var registrations = eventRegistration - ? [eventRegistration] - : this.eventRegistrations_; - return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations); - }; - return View; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __referenceConstructor$1; -/** - * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to - * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes - * and user writes (set, transaction, update). - * - * It's responsible for: - * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). - * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, - * applyUserOverwrite, etc.) - */ -var SyncPoint = /** @class */ (function () { - function SyncPoint() { - /** - * The Views being tracked at this location in the tree, stored as a map where the key is a - * queryId and the value is the View for that query. - * - * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). - * - * @type {!Object.} - * @private - */ - this.views_ = {}; - } - Object.defineProperty(SyncPoint, "__referenceConstructor", { - get: function () { - util.assert(__referenceConstructor$1, 'Reference.ts has not been loaded'); - return __referenceConstructor$1; - }, - set: function (val) { - util.assert(!__referenceConstructor$1, '__referenceConstructor has already been defined'); - __referenceConstructor$1 = val; - }, - enumerable: true, - configurable: true - }); - /** - * @return {boolean} - */ - SyncPoint.prototype.isEmpty = function () { - return util.isEmpty(this.views_); - }; - /** - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} optCompleteServerCache - * @return {!Array.} - */ - SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) { - var queryId = operation.source.queryId; - if (queryId !== null) { - var view = util.safeGet(this.views_, queryId); - util.assert(view != null, 'SyncTree gave us an op for an invalid query.'); - return view.applyOperation(operation, writesCache, optCompleteServerCache); - } - else { - var events_1 = []; - util.forEach(this.views_, function (key, view) { - events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache)); - }); - return events_1; - } - }; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache Complete server cache, if we have it. - * @param {boolean} serverCacheComplete - * @return {!Array.} Events to raise. - */ - SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) { - var queryId = query.queryIdentifier(); - var view = util.safeGet(this.views_, queryId); - if (!view) { - // TODO: make writesCache take flag for complete server node - var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null); - var eventCacheComplete = false; - if (eventCache) { - eventCacheComplete = true; - } - else if (serverCache instanceof ChildrenNode) { - eventCache = writesCache.calcCompleteEventChildren(serverCache); - eventCacheComplete = false; - } - else { - eventCache = ChildrenNode.EMPTY_NODE; - eventCacheComplete = false; - } - var viewCache = new ViewCache(new CacheNode( - /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode( - /** @type {!Node} */ (serverCache), serverCacheComplete, false)); - view = new View(query, viewCache); - this.views_[queryId] = view; - } - // This is guaranteed to exist now, we just created anything that was missing - view.addEventRegistration(eventRegistration); - return view.getInitialEvents(eventRegistration); - }; - /** - * Remove event callback(s). Return cancelEvents if a cancelError is specified. - * - * If query is the default query, we'll check all views for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified view(s). - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events - */ - SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) { - var queryId = query.queryIdentifier(); - var removed = []; - var cancelEvents = []; - var hadCompleteView = this.hasCompleteView(); - if (queryId === 'default') { - // When you do ref.off(...), we search all views for the registration to remove. - var self_1 = this; - util.forEach(this.views_, function (viewQueryId, view) { - cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError)); - if (view.isEmpty()) { - delete self_1.views_[viewQueryId]; - // We'll deal with complete views later. - if (!view - .getQuery() - .getQueryParams() - .loadsAllData()) { - removed.push(view.getQuery()); - } - } - }); - } - else { - // remove the callback from the specific view. - var view = util.safeGet(this.views_, queryId); - if (view) { - cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError)); - if (view.isEmpty()) { - delete this.views_[queryId]; - // We'll deal with complete views later. - if (!view - .getQuery() - .getQueryParams() - .loadsAllData()) { - removed.push(view.getQuery()); - } - } - } - } - if (hadCompleteView && !this.hasCompleteView()) { - // We removed our last complete view. - removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path)); - } - return { removed: removed, events: cancelEvents }; - }; - /** - * @return {!Array.} - */ - SyncPoint.prototype.getQueryViews = function () { - var _this = this; - var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; }); - return values.filter(function (view) { - return !view - .getQuery() - .getQueryParams() - .loadsAllData(); - }); - }; - /** - * - * @param {!Path} path The path to the desired complete snapshot - * @return {?Node} A complete cache, if it exists - */ - SyncPoint.prototype.getCompleteServerCache = function (path) { - var serverCache = null; - util.forEach(this.views_, function (key, view) { - serverCache = serverCache || view.getCompleteServerCache(path); - }); - return serverCache; - }; - /** - * @param {!Query} query - * @return {?View} - */ - SyncPoint.prototype.viewForQuery = function (query) { - var params = query.getQueryParams(); - if (params.loadsAllData()) { - return this.getCompleteView(); - } - else { - var queryId = query.queryIdentifier(); - return util.safeGet(this.views_, queryId); - } - }; - /** - * @param {!Query} query - * @return {boolean} - */ - SyncPoint.prototype.viewExistsForQuery = function (query) { - return this.viewForQuery(query) != null; - }; - /** - * @return {boolean} - */ - SyncPoint.prototype.hasCompleteView = function () { - return this.getCompleteView() != null; - }; - /** - * @return {?View} - */ - SyncPoint.prototype.getCompleteView = function () { - var completeView = util.findValue(this.views_, function (view) { - return view - .getQuery() - .getQueryParams() - .loadsAllData(); - }); - return completeView || null; - }; - return SyncPoint; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with - * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write - * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write - * to reflect the write added. - * - * @constructor - * @param {!ImmutableTree.} writeTree - */ -var CompoundWrite = /** @class */ (function () { - function CompoundWrite(writeTree_) { - this.writeTree_ = writeTree_; - } - /** - * @param {!Path} path - * @param {!Node} node - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.addWrite = function (path, node) { - if (path.isEmpty()) { - return new CompoundWrite(new ImmutableTree(node)); - } - else { - var rootmost = this.writeTree_.findRootMostValueAndPath(path); - if (rootmost != null) { - var rootMostPath = rootmost.path; - var value = rootmost.value; - var relativePath = Path.relativePath(rootMostPath, path); - value = value.updateChild(relativePath, node); - return new CompoundWrite(this.writeTree_.set(rootMostPath, value)); - } - else { - var subtree = new ImmutableTree(node); - var newWriteTree = this.writeTree_.setTree(path, subtree); - return new CompoundWrite(newWriteTree); - } - } - }; - /** - * @param {!Path} path - * @param {!Object.} updates - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.addWrites = function (path, updates) { - var newWrite = this; - util.forEach(updates, function (childKey, node) { - newWrite = newWrite.addWrite(path.child(childKey), node); - }); - return newWrite; - }; - /** - * Will remove a write at the given path and deeper paths. This will not modify a write at a higher - * location, which must be removed by calling this method with that path. - * - * @param {!Path} path The path at which a write and all deeper writes should be removed - * @return {!CompoundWrite} The new CompoundWrite with the removed path - */ - CompoundWrite.prototype.removeWrite = function (path) { - if (path.isEmpty()) { - return CompoundWrite.Empty; - } - else { - var newWriteTree = this.writeTree_.setTree(path, ImmutableTree.Empty); - return new CompoundWrite(newWriteTree); - } - }; - /** - * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be - * considered "complete". - * - * @param {!Path} path The path to check for - * @return {boolean} Whether there is a complete write at that path - */ - CompoundWrite.prototype.hasCompleteWrite = function (path) { - return this.getCompleteNode(path) != null; - }; - /** - * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate - * writes from deeper paths, but will return child nodes from a more shallow path. - * - * @param {!Path} path The path to get a complete write - * @return {?Node} The node if complete at that path, or null otherwise. - */ - CompoundWrite.prototype.getCompleteNode = function (path) { - var rootmost = this.writeTree_.findRootMostValueAndPath(path); - if (rootmost != null) { - return this.writeTree_ - .get(rootmost.path) - .getChild(Path.relativePath(rootmost.path, path)); - } - else { - return null; - } - }; - /** - * Returns all children that are guaranteed to be a complete overwrite. - * - * @return {!Array.} A list of all complete children. - */ - CompoundWrite.prototype.getCompleteChildren = function () { - var children = []; - var node = this.writeTree_.value; - if (node != null) { - // If it's a leaf node, it has no children; so nothing to do. - if (!node.isLeafNode()) { - node.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - children.push(new NamedNode(childName, childNode)); - }); - } - } - else { - this.writeTree_.children.inorderTraversal(function (childName, childTree) { - if (childTree.value != null) { - children.push(new NamedNode(childName, childTree.value)); - } - }); - } - return children; - }; - /** - * @param {!Path} path - * @return {!CompoundWrite} - */ - CompoundWrite.prototype.childCompoundWrite = function (path) { - if (path.isEmpty()) { - return this; - } - else { - var shadowingNode = this.getCompleteNode(path); - if (shadowingNode != null) { - return new CompoundWrite(new ImmutableTree(shadowingNode)); - } - else { - return new CompoundWrite(this.writeTree_.subtree(path)); - } - } - }; - /** - * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. - * @return {boolean} Whether this CompoundWrite is empty - */ - CompoundWrite.prototype.isEmpty = function () { - return this.writeTree_.isEmpty(); - }; - /** - * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the - * node - * @param {!Node} node The node to apply this CompoundWrite to - * @return {!Node} The node with all writes applied - */ - CompoundWrite.prototype.apply = function (node) { - return CompoundWrite.applySubtreeWrite_(Path.Empty, this.writeTree_, node); - }; - /** - * @type {!CompoundWrite} - */ - CompoundWrite.Empty = new CompoundWrite(new ImmutableTree(null)); - /** - * @param {!Path} relativePath - * @param {!ImmutableTree.} writeTree - * @param {!Node} node - * @return {!Node} - * @private - */ - CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) { - if (writeTree.value != null) { - // Since there a write is always a leaf, we're done here - return node.updateChild(relativePath, writeTree.value); - } - else { - var priorityWrite_1 = null; - writeTree.children.inorderTraversal(function (childKey, childTree) { - if (childKey === '.priority') { - // Apply priorities at the end so we don't update priorities for either empty nodes or forget - // to apply priorities to empty nodes that are later filled - util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes'); - priorityWrite_1 = childTree.value; - } - else { - node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node); - } - }); - // If there was a priority write, we only apply it if the node is not empty - if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) { - node = node.updateChild(relativePath.child('.priority'), priorityWrite_1); - } - return node; - } - }; - return CompoundWrite; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them - * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() - * and addMerge(), and removed with removeWrite(). - * - * @constructor - */ -var WriteTree = /** @class */ (function () { - function WriteTree() { - /** - * A tree tracking the result of applying all visible writes. This does not include transactions with - * applyLocally=false or writes that are completely shadowed by other writes. - * - * @type {!CompoundWrite} - * @private - */ - this.visibleWrites_ = CompoundWrite.Empty; - /** - * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary - * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also - * used by transactions). - * - * @type {!Array.} - * @private - */ - this.allWrites_ = []; - this.lastWriteId_ = -1; - } - /** - * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. - * - * @param {!Path} path - * @return {!WriteTreeRef} - */ - WriteTree.prototype.childWrites = function (path) { - return new WriteTreeRef(path, this); - }; - /** - * Record a new overwrite from user code. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} writeId - * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches - */ - WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) { - util.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones'); - if (visible === undefined) { - visible = true; - } - this.allWrites_.push({ - path: path, - snap: snap, - writeId: writeId, - visible: visible - }); - if (visible) { - this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap); - } - this.lastWriteId_ = writeId; - }; - /** - * Record a new merge from user code. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - */ - WriteTree.prototype.addMerge = function (path, changedChildren, writeId) { - util.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones'); - this.allWrites_.push({ - path: path, - children: changedChildren, - writeId: writeId, - visible: true - }); - this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren); - this.lastWriteId_ = writeId; - }; - /** - * @param {!number} writeId - * @return {?WriteRecord} - */ - WriteTree.prototype.getWrite = function (writeId) { - for (var i = 0; i < this.allWrites_.length; i++) { - var record = this.allWrites_[i]; - if (record.writeId === writeId) { - return record; - } - } - return null; - }; - /** - * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates - * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. - * - * @param {!number} writeId - * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise - * events as a result). - */ - WriteTree.prototype.removeWrite = function (writeId) { - // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied - // out of order. - //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId; - //assert(validClear, "Either we don't have this write, or it's the first one in the queue"); - var _this = this; - var idx = this.allWrites_.findIndex(function (s) { - return s.writeId === writeId; - }); - util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.'); - var writeToRemove = this.allWrites_[idx]; - this.allWrites_.splice(idx, 1); - var removedWriteWasVisible = writeToRemove.visible; - var removedWriteOverlapsWithOtherWrites = false; - var i = this.allWrites_.length - 1; - while (removedWriteWasVisible && i >= 0) { - var currentWrite = this.allWrites_[i]; - if (currentWrite.visible) { - if (i >= idx && - this.recordContainsPath_(currentWrite, writeToRemove.path)) { - // The removed write was completely shadowed by a subsequent write. - removedWriteWasVisible = false; - } - else if (writeToRemove.path.contains(currentWrite.path)) { - // Either we're covering some writes or they're covering part of us (depending on which came first). - removedWriteOverlapsWithOtherWrites = true; - } - } - i--; - } - if (!removedWriteWasVisible) { - return false; - } - else if (removedWriteOverlapsWithOtherWrites) { - // There's some shadowing going on. Just rebuild the visible writes from scratch. - this.resetTree_(); - return true; - } - else { - // There's no shadowing. We can safely just remove the write(s) from visibleWrites. - if (writeToRemove.snap) { - this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path); - } - else { - var children = writeToRemove.children; - util.forEach(children, function (childName) { - _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName)); - }); - } - return true; - } - }; - /** - * Return a complete snapshot for the given path if there's visible write data at that path, else null. - * No server data is considered. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTree.prototype.getCompleteWriteData = function (path) { - return this.visibleWrites_.getCompleteNode(path); - }; - /** - * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden - * writes), attempt to calculate a complete snapshot for the given path - * - * @param {!Path} treePath - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude An optional set to be excluded - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) { - if (!writeIdsToExclude && !includeHiddenWrites) { - var shadowingNode = this.visibleWrites_.getCompleteNode(treePath); - if (shadowingNode != null) { - return shadowingNode; - } - else { - var subMerge = this.visibleWrites_.childCompoundWrite(treePath); - if (subMerge.isEmpty()) { - return completeServerCache; - } - else if (completeServerCache == null && - !subMerge.hasCompleteWrite(Path.Empty)) { - // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow - return null; - } - else { - var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; - return subMerge.apply(layeredCache); - } - } - } - else { - var merge = this.visibleWrites_.childCompoundWrite(treePath); - if (!includeHiddenWrites && merge.isEmpty()) { - return completeServerCache; - } - else { - // If the server cache is null, and we don't have a complete cache, we need to return null - if (!includeHiddenWrites && - completeServerCache == null && - !merge.hasCompleteWrite(Path.Empty)) { - return null; - } - else { - var filter = function (write) { - return ((write.visible || includeHiddenWrites) && - (!writeIdsToExclude || - !~writeIdsToExclude.indexOf(write.writeId)) && - (write.path.contains(treePath) || treePath.contains(write.path))); - }; - var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath); - var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE; - return mergeAtPath.apply(layeredCache); - } - } - } - }; - /** - * With optional, underlying server data, attempt to return a children node of children that we have complete data for. - * Used when creating new views, to pre-fill their complete event children snapshot. - * - * @param {!Path} treePath - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) { - var completeChildren = ChildrenNode.EMPTY_NODE; - var topLevelSet = this.visibleWrites_.getCompleteNode(treePath); - if (topLevelSet) { - if (!topLevelSet.isLeafNode()) { - // we're shadowing everything. Return the children. - topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) { - completeChildren = completeChildren.updateImmediateChild(childName, childSnap); - }); - } - return completeChildren; - } - else if (completeServerChildren) { - // Layer any children we have on top of this - // We know we don't have a top-level set, so just enumerate existing children - var merge_1 = this.visibleWrites_.childCompoundWrite(treePath); - completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) { - var node = merge_1 - .childCompoundWrite(new Path(childName)) - .apply(childNode); - completeChildren = completeChildren.updateImmediateChild(childName, node); - }); - // Add any complete children we have from the set - merge_1.getCompleteChildren().forEach(function (namedNode) { - completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); - }); - return completeChildren; - } - else { - // We don't have anything to layer on top of. Layer on any children we have - // Note that we can return an empty snap if we have a defined delete - var merge = this.visibleWrites_.childCompoundWrite(treePath); - merge.getCompleteChildren().forEach(function (namedNode) { - completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node); - }); - return completeChildren; - } - }; - /** - * Given that the underlying server data has updated, determine what, if anything, needs to be - * applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events - * - * Either existingEventSnap or existingServerSnap must exist - * - * @param {!Path} treePath - * @param {!Path} childPath - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) { - util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist'); - var path = treePath.child(childPath); - if (this.visibleWrites_.hasCompleteWrite(path)) { - // At this point we can probably guarantee that we're in case 2, meaning no events - // May need to check visibility while doing the findRootMostValueAndPath call - return null; - } - else { - // No complete shadowing. We're either partially shadowing or not shadowing at all. - var childMerge = this.visibleWrites_.childCompoundWrite(path); - if (childMerge.isEmpty()) { - // We're not shadowing at all. Case 1 - return existingServerSnap.getChild(childPath); - } - else { - // This could be more efficient if the serverNode + updates doesn't change the eventSnap - // However this is tricky to find out, since user updates don't necessary change the server - // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server - // adds nodes, but doesn't change any existing writes. It is therefore not enough to - // only check if the updates change the serverNode. - // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case? - return childMerge.apply(existingServerSnap.getChild(childPath)); - } - } - }; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!Path} treePath - * @param {!string} childKey - * @param {!CacheNode} existingServerSnap - * @return {?Node} - */ - WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) { - var path = treePath.child(childKey); - var shadowingNode = this.visibleWrites_.getCompleteNode(path); - if (shadowingNode != null) { - return shadowingNode; - } - else { - if (existingServerSnap.isCompleteForChild(childKey)) { - var childMerge = this.visibleWrites_.childCompoundWrite(path); - return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey)); - } - else { - return null; - } - } - }; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTree.prototype.shadowingWrite = function (path) { - return this.visibleWrites_.getCompleteNode(path); - }; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window. - * - * @param {!Path} treePath - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) { - var toIterate; - var merge = this.visibleWrites_.childCompoundWrite(treePath); - var shadowingNode = merge.getCompleteNode(Path.Empty); - if (shadowingNode != null) { - toIterate = shadowingNode; - } - else if (completeServerData != null) { - toIterate = merge.apply(completeServerData); - } - else { - // no children to iterate on - return []; - } - toIterate = toIterate.withIndex(index); - if (!toIterate.isEmpty() && !toIterate.isLeafNode()) { - var nodes = []; - var cmp = index.getCompare(); - var iter = reverse - ? toIterate.getReverseIteratorFrom(startPost, index) - : toIterate.getIteratorFrom(startPost, index); - var next = iter.getNext(); - while (next && nodes.length < count) { - if (cmp(next, startPost) !== 0) { - nodes.push(next); - } - next = iter.getNext(); - } - return nodes; - } - else { - return []; - } - }; - /** - * @param {!WriteRecord} writeRecord - * @param {!Path} path - * @return {boolean} - * @private - */ - WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) { - if (writeRecord.snap) { - return writeRecord.path.contains(path); - } - else { - // findKey can return undefined, so use !! to coerce to boolean - return !!util.findKey(writeRecord.children, function (childSnap, childName) { - return writeRecord.path.child(childName).contains(path); - }); - } - }; - /** - * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots - * @private - */ - WriteTree.prototype.resetTree_ = function () { - this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path.Empty); - if (this.allWrites_.length > 0) { - this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId; - } - else { - this.lastWriteId_ = -1; - } - }; - /** - * The default filter used when constructing the tree. Keep everything that's visible. - * - * @param {!WriteRecord} write - * @return {boolean} - * @private - */ - WriteTree.DefaultFilter_ = function (write) { - return write.visible; - }; - /** - * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of - * event data at that path. - * - * @param {!Array.} writes - * @param {!function(!WriteRecord):boolean} filter - * @param {!Path} treeRoot - * @return {!CompoundWrite} - * @private - */ - WriteTree.layerTree_ = function (writes, filter, treeRoot) { - var compoundWrite = CompoundWrite.Empty; - for (var i = 0; i < writes.length; ++i) { - var write = writes[i]; - // Theory, a later set will either: - // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction - // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction - if (filter(write)) { - var writePath = write.path; - var relativePath = void 0; - if (write.snap) { - if (treeRoot.contains(writePath)) { - relativePath = Path.relativePath(treeRoot, writePath); - compoundWrite = compoundWrite.addWrite(relativePath, write.snap); - } - else if (writePath.contains(treeRoot)) { - relativePath = Path.relativePath(writePath, treeRoot); - compoundWrite = compoundWrite.addWrite(Path.Empty, write.snap.getChild(relativePath)); - } - else { - // There is no overlap between root path and write path, ignore write - } - } - else if (write.children) { - if (treeRoot.contains(writePath)) { - relativePath = Path.relativePath(treeRoot, writePath); - compoundWrite = compoundWrite.addWrites(relativePath, write.children); - } - else if (writePath.contains(treeRoot)) { - relativePath = Path.relativePath(writePath, treeRoot); - if (relativePath.isEmpty()) { - compoundWrite = compoundWrite.addWrites(Path.Empty, write.children); - } - else { - var child = util.safeGet(write.children, relativePath.getFront()); - if (child) { - // There exists a child in this node that matches the root path - var deepNode = child.getChild(relativePath.popFront()); - compoundWrite = compoundWrite.addWrite(Path.Empty, deepNode); - } - } - } - else { - // There is no overlap between root path and write path, ignore write - } - } - else { - throw util.assertionError('WriteRecord should have .snap or .children'); - } - } - } - return compoundWrite; - }; - return WriteTree; -}()); -/** - * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods - * just proxy to the underlying WriteTree. - * - * @constructor - */ -var WriteTreeRef = /** @class */ (function () { - /** - * @param {!Path} path - * @param {!WriteTree} writeTree - */ - function WriteTreeRef(path, writeTree) { - this.treePath_ = path; - this.writeTree_ = writeTree; - } - /** - * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used - * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node - * can lead to a more expensive calculation. - * - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude Optional writes to exclude. - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) { - return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites); - }; - /** - * If possible, returns a children node containing all of the complete children we have data for. The returned data is a - * mix of the given server data and write data. - * - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) { - return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren); - }; - /** - * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, - * if anything, needs to be applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events should be raised - * - * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert - * - * @param {!Path} path - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) { - return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap); - }; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - WriteTreeRef.prototype.shadowingWrite = function (path) { - return this.writeTree_.shadowingWrite(this.treePath_.child(path)); - }; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window - * - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) { - return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index); - }; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!string} childKey - * @param {!CacheNode} existingServerCache - * @return {?Node} - */ - WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) { - return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache); - }; - /** - * Return a WriteTreeRef for a child. - * - * @param {string} childName - * @return {!WriteTreeRef} - */ - WriteTreeRef.prototype.child = function (childName) { - return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_); - }; - return WriteTreeRef; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SyncTree is the central class for managing event callback registration, data caching, views - * (query processing), and event generation. There are typically two SyncTree instances for - * each Repo, one for the normal Firebase data, and one for the .info data. - * - * It has a number of responsibilities, including: - * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). - * - Applying and caching data changes for user set(), transaction(), and update() calls - * (applyUserOverwrite(), applyUserMerge()). - * - Applying and caching data changes for server data changes (applyServerOverwrite(), - * applyServerMerge()). - * - Generating user-facing events for server and user changes (all of the apply* methods - * return the set of events that need to be raised as a result). - * - Maintaining the appropriate set of server listens to ensure we are always subscribed - * to the correct set of paths and queries to satisfy the current set of user event - * callbacks (listens are started/stopped using the provided listenProvider). - * - * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual - * events are returned to the caller rather than raised synchronously. - * - * @constructor - */ -var SyncTree = /** @class */ (function () { - /** - * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening - * to server data. - */ - function SyncTree(listenProvider_) { - this.listenProvider_ = listenProvider_; - /** - * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. - * @type {!ImmutableTree.} - * @private - */ - this.syncPointTree_ = ImmutableTree.Empty; - /** - * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). - * @type {!WriteTree} - * @private - */ - this.pendingWriteTree_ = new WriteTree(); - this.tagToQueryMap_ = {}; - this.queryToTagMap_ = {}; - } - /** - * Apply the data changes for a user-generated set() or transaction() call. - * - * @param {!Path} path - * @param {!Node} newData - * @param {number} writeId - * @param {boolean=} visible - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) { - // Record pending write. - this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible); - if (!visible) { - return []; - } - else { - return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.User, path, newData)); - } - }; - /** - * Apply the data from a user-generated update() call - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) { - // Record pending merge. - this.pendingWriteTree_.addMerge(path, changedChildren, writeId); - var changeTree = ImmutableTree.fromObject(changedChildren); - return this.applyOperationToSyncPoints_(new Merge(OperationSource.User, path, changeTree)); - }; - /** - * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). - * - * @param {!number} writeId - * @param {boolean=} revert True if the given write failed and needs to be reverted - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.ackUserWrite = function (writeId, revert) { - if (revert === void 0) { revert = false; } - var write = this.pendingWriteTree_.getWrite(writeId); - var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId); - if (!needToReevaluate) { - return []; - } - else { - var affectedTree_1 = ImmutableTree.Empty; - if (write.snap != null) { - // overwrite - affectedTree_1 = affectedTree_1.set(Path.Empty, true); - } - else { - util.forEach(write.children, function (pathString, node) { - affectedTree_1 = affectedTree_1.set(new Path(pathString), node); - }); - } - return this.applyOperationToSyncPoints_(new AckUserWrite(write.path, affectedTree_1, revert)); - } - }; - /** - * Apply new server data for the specified path.. - * - * @param {!Path} path - * @param {!Node} newData - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyServerOverwrite = function (path, newData) { - return this.applyOperationToSyncPoints_(new Overwrite(OperationSource.Server, path, newData)); - }; - /** - * Apply new server data to be merged in at the specified path. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyServerMerge = function (path, changedChildren) { - var changeTree = ImmutableTree.fromObject(changedChildren); - return this.applyOperationToSyncPoints_(new Merge(OperationSource.Server, path, changeTree)); - }; - /** - * Apply a listen complete for a query - * - * @param {!Path} path - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyListenComplete = function (path) { - return this.applyOperationToSyncPoints_(new ListenComplete(OperationSource.Server, path)); - }; - /** - * Apply new server data for the specified tagged query. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey != null) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var op = new Overwrite(OperationSource.forServerTaggedQuery(queryId), relativePath, snap); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // Query must have been removed already - return []; - } - }; - /** - * Apply server data to be merged in for the specified tagged query. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var changeTree = ImmutableTree.fromObject(changedChildren); - var op = new Merge(OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // We've already removed the query. No big deal, ignore the update - return []; - } - }; - /** - * Apply a listen complete for a tagged query - * - * @param {!Path} path - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.applyTaggedListenComplete = function (path, tag) { - var queryKey = this.queryKeyForTag_(tag); - if (queryKey) { - var r = SyncTree.parseQueryKey_(queryKey); - var queryPath = r.path, queryId = r.queryId; - var relativePath = Path.relativePath(queryPath, path); - var op = new ListenComplete(OperationSource.forServerTaggedQuery(queryId), relativePath); - return this.applyTaggedOperation_(queryPath, op); - } - else { - // We've already removed the query. No big deal, ignore the update - return []; - } - }; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @return {!Array.} Events to raise. - */ - SyncTree.prototype.addEventRegistration = function (query, eventRegistration) { - var path = query.path; - var serverCache = null; - var foundAncestorDefaultView = false; - // Any covering writes will necessarily be at the root, so really all we need to find is the server cache. - // Consider optimizing this once there's a better understanding of what actual behavior will be. - this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) { - var relativePath = Path.relativePath(pathToSyncPoint, path); - serverCache = serverCache || sp.getCompleteServerCache(relativePath); - foundAncestorDefaultView = - foundAncestorDefaultView || sp.hasCompleteView(); - }); - var syncPoint = this.syncPointTree_.get(path); - if (!syncPoint) { - syncPoint = new SyncPoint(); - this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint); - } - else { - foundAncestorDefaultView = - foundAncestorDefaultView || syncPoint.hasCompleteView(); - serverCache = serverCache || syncPoint.getCompleteServerCache(Path.Empty); - } - var serverCacheComplete; - if (serverCache != null) { - serverCacheComplete = true; - } - else { - serverCacheComplete = false; - serverCache = ChildrenNode.EMPTY_NODE; - var subtree = this.syncPointTree_.subtree(path); - subtree.foreachChild(function (childName, childSyncPoint) { - var completeCache = childSyncPoint.getCompleteServerCache(Path.Empty); - if (completeCache) { - serverCache = serverCache.updateImmediateChild(childName, completeCache); - } - }); - } - var viewAlreadyExists = syncPoint.viewExistsForQuery(query); - if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) { - // We need to track a tag for this query - var queryKey = SyncTree.makeQueryKey_(query); - util.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag'); - var tag = SyncTree.getNextQueryTag_(); - this.queryToTagMap_[queryKey] = tag; - // Coerce to string to avoid sparse arrays. - this.tagToQueryMap_['_' + tag] = queryKey; - } - var writesCache = this.pendingWriteTree_.childWrites(path); - var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete); - if (!viewAlreadyExists && !foundAncestorDefaultView) { - var view /** @type !View */ = syncPoint.viewForQuery(query); - events = events.concat(this.setupListener_(query, view)); - } - return events; - }; - /** - * Remove event callback(s). - * - * If query is the default query, we'll check all queries for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, all callbacks are removed. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) { - var _this = this; - // Find the syncPoint first. Then deal with whether or not it has matching listeners - var path = query.path; - var maybeSyncPoint = this.syncPointTree_.get(path); - var cancelEvents = []; - // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without - // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and - // not loadsAllData(). - if (maybeSyncPoint && - (query.queryIdentifier() === 'default' || - maybeSyncPoint.viewExistsForQuery(query))) { - /** - * @type {{removed: !Array., events: !Array.}} - */ - var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError); - if (maybeSyncPoint.isEmpty()) { - this.syncPointTree_ = this.syncPointTree_.remove(path); - } - var removed = removedAndEvents.removed; - cancelEvents = removedAndEvents.events; - // We may have just removed one of many listeners and can short-circuit this whole process - // We may also not have removed a default listener, in which case all of the descendant listeners should already be - // properly set up. - // - // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of - // queryId === 'default' - var removingDefault = -1 !== - removed.findIndex(function (query) { - return query.getQueryParams().loadsAllData(); - }); - var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) { - return parentSyncPoint.hasCompleteView(); - }); - if (removingDefault && !covered) { - var subtree = this.syncPointTree_.subtree(path); - // There are potentially child listeners. Determine what if any listens we need to send before executing the - // removal - if (!subtree.isEmpty()) { - // We need to fold over our subtree and collect the listeners to send - var newViews = this.collectDistinctViewsForSubTree_(subtree); - // Ok, we've collected all the listens we need. Set them up. - for (var i = 0; i < newViews.length; ++i) { - var view = newViews[i], newQuery = view.getQuery(); - var listener = this.createListenerForView_(view); - this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete); - } - } - else { - // There's nothing below us, so nothing we need to start listening on - } - } - // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query - // The above block has us covered in terms of making sure we're set up on listens lower in the tree. - // Also, note that if we have a cancelError, it's already been removed at the provider level. - if (!covered && removed.length > 0 && !cancelError) { - // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one - // default. Otherwise, we need to iterate through and cancel each individual query - if (removingDefault) { - // We don't tag default listeners - var defaultTag = null; - this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag); - } - else { - removed.forEach(function (queryToRemove) { - var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)]; - _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove); - }); - } - } - // Now, clear all of the tags we're tracking for the removed listens - this.removeTags_(removed); - } - else { - // No-op, this listener must've been already removed - } - return cancelEvents; - }; - /** - * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above - * it, but as this is only used by transaction code, that should always be the case anyways. - * - * Note: this method will *include* hidden writes from transaction with applyLocally set to false. - * @param {!Path} path The path to the data we want - * @param {Array.=} writeIdsToExclude A specific set to be excluded - * @return {?Node} - */ - SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) { - var includeHiddenSets = true; - var writeTree = this.pendingWriteTree_; - var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) { - var relativePath = Path.relativePath(pathSoFar, path); - var serverCache = syncPoint.getCompleteServerCache(relativePath); - if (serverCache) { - return serverCache; - } - }); - return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets); - }; - /** - * This collapses multiple unfiltered views into a single view, since we only need a single - * listener for them. - * - * @param {!ImmutableTree.} subtree - * @return {!Array.} - * @private - */ - SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) { - return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) { - if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) { - var completeView = maybeChildSyncPoint.getCompleteView(); - return [completeView]; - } - else { - // No complete view here, flatten any deeper listens into an array - var views_1 = []; - if (maybeChildSyncPoint) { - views_1 = maybeChildSyncPoint.getQueryViews(); - } - util.forEach(childMap, function (key, childViews) { - views_1 = views_1.concat(childViews); - }); - return views_1; - } - }); - }; - /** - * @param {!Array.} queries - * @private - */ - SyncTree.prototype.removeTags_ = function (queries) { - for (var j = 0; j < queries.length; ++j) { - var removedQuery = queries[j]; - if (!removedQuery.getQueryParams().loadsAllData()) { - // We should have a tag for this - var removedQueryKey = SyncTree.makeQueryKey_(removedQuery); - var removedQueryTag = this.queryToTagMap_[removedQueryKey]; - delete this.queryToTagMap_[removedQueryKey]; - delete this.tagToQueryMap_['_' + removedQueryTag]; - } - } - }; - /** - * Normalizes a query to a query we send the server for listening - * @param {!Query} query - * @return {!Query} The normalized query - * @private - */ - SyncTree.queryForListening_ = function (query) { - if (query.getQueryParams().loadsAllData() && - !query.getQueryParams().isDefault()) { - // We treat queries that load all data as default queries - // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits - // from Query - return /** @type {!Query} */ query.getRef(); - } - else { - return query; - } - }; - /** - * For a given new listen, manage the de-duplication of outstanding subscriptions. - * - * @param {!Query} query - * @param {!View} view - * @return {!Array.} This method can return events to support synchronous data sources - * @private - */ - SyncTree.prototype.setupListener_ = function (query, view) { - var path = query.path; - var tag = this.tagForQuery_(query); - var listener = this.createListenerForView_(view); - var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete); - var subtree = this.syncPointTree_.subtree(path); - // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we - // may need to shadow other listens as well. - if (tag) { - util.assert(!subtree.value.hasCompleteView(), "If we're adding a query, it shouldn't be shadowed"); - } - else { - // Shadow everything at or below this location, this is a default listener. - var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) { - if (!relativePath.isEmpty() && - maybeChildSyncPoint && - maybeChildSyncPoint.hasCompleteView()) { - return [maybeChildSyncPoint.getCompleteView().getQuery()]; - } - else { - // No default listener here, flatten any deeper queries into an array - var queries_1 = []; - if (maybeChildSyncPoint) { - queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); })); - } - util.forEach(childMap, function (key, childQueries) { - queries_1 = queries_1.concat(childQueries); - }); - return queries_1; - } - }); - for (var i = 0; i < queriesToStop.length; ++i) { - var queryToStop = queriesToStop[i]; - this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop)); - } - } - return events; - }; - /** - * - * @param {!View} view - * @return {{hashFn: function(), onComplete: function(!string, *)}} - * @private - */ - SyncTree.prototype.createListenerForView_ = function (view) { - var _this = this; - var query = view.getQuery(); - var tag = this.tagForQuery_(query); - return { - hashFn: function () { - var cache = view.getServerCache() || ChildrenNode.EMPTY_NODE; - return cache.hash(); - }, - onComplete: function (status) { - if (status === 'ok') { - if (tag) { - return _this.applyTaggedListenComplete(query.path, tag); - } - else { - return _this.applyListenComplete(query.path); - } - } - else { - // If a listen failed, kill all of the listeners here, not just the one that triggered the error. - // Note that this may need to be scoped to just this listener if we change permissions on filtered children - var error$$1 = errorForServerCode(status, query); - return _this.removeEventRegistration(query, - /*eventRegistration*/ null, error$$1); - } - } - }; - }; - /** - * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. - * @private - * @param {!Query} query - * @return {string} - */ - SyncTree.makeQueryKey_ = function (query) { - return query.path.toString() + '$' + query.queryIdentifier(); - }; - /** - * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. - * @private - * @param {!string} queryKey - * @return {{queryId: !string, path: !Path}} - */ - SyncTree.parseQueryKey_ = function (queryKey) { - var splitIndex = queryKey.indexOf('$'); - util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.'); - return { - queryId: queryKey.substr(splitIndex + 1), - path: new Path(queryKey.substr(0, splitIndex)) - }; - }; - /** - * Return the query associated with the given tag, if we have one - * @param {!number} tag - * @return {?string} - * @private - */ - SyncTree.prototype.queryKeyForTag_ = function (tag) { - return this.tagToQueryMap_['_' + tag]; - }; - /** - * Return the tag associated with the given query. - * @param {!Query} query - * @return {?number} - * @private - */ - SyncTree.prototype.tagForQuery_ = function (query) { - var queryKey = SyncTree.makeQueryKey_(query); - return util.safeGet(this.queryToTagMap_, queryKey); - }; - /** - * Static accessor for query tags. - * @return {number} - * @private - */ - SyncTree.getNextQueryTag_ = function () { - return SyncTree.nextQueryTag_++; - }; - /** - * A helper method to apply tagged operations - * - * @param {!Path} queryPath - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) { - var syncPoint = this.syncPointTree_.get(queryPath); - util.assert(syncPoint, "Missing sync point for query tag that we're tracking"); - var writesCache = this.pendingWriteTree_.childWrites(queryPath); - return syncPoint.applyOperation(operation, writesCache, - /*serverCache=*/ null); - }; - /** - * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. - * - * NOTES: - * - Descendant SyncPoints will be visited first (since we raise events depth-first). - - * - We call applyOperation() on each SyncPoint passing three things: - * 1. A version of the Operation that has been made relative to the SyncPoint location. - * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. - * 3. A snapshot Node with cached server data, if we have it. - - * - We concatenate all of the events returned by each SyncPoint and return the result. - * - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) { - return this.applyOperationHelper_(operation, this.syncPointTree_, - /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path.Empty)); - }; - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) { - if (operation.path.isEmpty()) { - return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); - } - else { - var syncPoint = syncPointTree.get(Path.Empty); - // If we don't have cached server data, see if we can get it from this SyncPoint. - if (serverCache == null && syncPoint != null) { - serverCache = syncPoint.getCompleteServerCache(Path.Empty); - } - var events = []; - var childName = operation.path.getFront(); - var childOperation = operation.operationForChild(childName); - var childTree = syncPointTree.children.get(childName); - if (childTree && childOperation) { - var childServerCache = serverCache - ? serverCache.getImmediateChild(childName) - : null; - var childWritesCache = writesCache.child(childName); - events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache)); - } - if (syncPoint) { - events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache)); - } - return events; - } - }; - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) { - var _this = this; - var syncPoint = syncPointTree.get(Path.Empty); - // If we don't have cached server data, see if we can get it from this SyncPoint. - if (serverCache == null && syncPoint != null) { - serverCache = syncPoint.getCompleteServerCache(Path.Empty); - } - var events = []; - syncPointTree.children.inorderTraversal(function (childName, childTree) { - var childServerCache = serverCache - ? serverCache.getImmediateChild(childName) - : null; - var childWritesCache = writesCache.child(childName); - var childOperation = operation.operationForChild(childName); - if (childOperation) { - events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache)); - } - }); - if (syncPoint) { - events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache)); - } - return events; - }; - /** - * Static tracker for next query tag. - * @type {number} - * @private - */ - SyncTree.nextQueryTag_ = 1; - return SyncTree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Mutable object which basically just stores a reference to the "latest" immutable snapshot. - * - * @constructor - */ -var SnapshotHolder = /** @class */ (function () { - function SnapshotHolder() { - this.rootNode_ = ChildrenNode.EMPTY_NODE; - } - SnapshotHolder.prototype.getNode = function (path) { - return this.rootNode_.getChild(path); - }; - SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) { - this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode); - }; - return SnapshotHolder; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Abstraction around FirebaseApp's token fetching capabilities. - */ -var AuthTokenProvider = /** @class */ (function () { - /** - * @param {!FirebaseApp} app_ - */ - function AuthTokenProvider(app_) { - this.app_ = app_; - } - /** - * @param {boolean} forceRefresh - * @return {!Promise} - */ - AuthTokenProvider.prototype.getToken = function (forceRefresh) { - return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, - // .catch - function (error$$1) { - // TODO: Need to figure out all the cases this is raised and whether - // this makes sense. - if (error$$1 && error$$1.code === 'auth/token-not-initialized') { - log('Got auth/token-not-initialized error. Treating as null token.'); - return null; - } - else { - return Promise.reject(error$$1); - } - }); - }; - AuthTokenProvider.prototype.addTokenChangeListener = function (listener) { - // TODO: We might want to wrap the listener and call it with no args to - // avoid a leaky abstraction, but that makes removing the listener harder. - this.app_['INTERNAL']['addAuthTokenListener'](listener); - }; - AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) { - this.app_['INTERNAL']['removeAuthTokenListener'](listener); - }; - AuthTokenProvider.prototype.notifyForInvalidToken = function () { - var errorMessage = 'Provided authentication credentials for the app named "' + - this.app_.name + - '" are invalid. This usually indicates your app was not ' + - 'initialized correctly. '; - if ('credential' in this.app_.options) { - errorMessage += - 'Make sure the "credential" property provided to initializeApp() ' + - 'is authorized to access the specified "databaseURL" and is from the correct ' + - 'project.'; - } - else if ('serviceAccount' in this.app_.options) { - errorMessage += - 'Make sure the "serviceAccount" property provided to initializeApp() ' + - 'is authorized to access the specified "databaseURL" and is from the correct ' + - 'project.'; - } - else { - errorMessage += - 'Make sure the "apiKey" and "databaseURL" properties provided to ' + - 'initializeApp() match the values provided for your app at ' + - 'https://console.firebase.google.com/.'; - } - warn(errorMessage); - }; - return AuthTokenProvider; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Tracks a collection of stats. - * - * @constructor - */ -var StatsCollection = /** @class */ (function () { - function StatsCollection() { - this.counters_ = {}; - } - StatsCollection.prototype.incrementCounter = function (name, amount) { - if (amount === void 0) { amount = 1; } - if (!util.contains(this.counters_, name)) - this.counters_[name] = 0; - this.counters_[name] += amount; - }; - StatsCollection.prototype.get = function () { - return util.deepCopy(this.counters_); - }; - return StatsCollection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var StatsManager = /** @class */ (function () { - function StatsManager() { - } - StatsManager.getCollection = function (repoInfo) { - var hashString = repoInfo.toString(); - if (!this.collections_[hashString]) { - this.collections_[hashString] = new StatsCollection(); - } - return this.collections_[hashString]; - }; - StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) { - var hashString = repoInfo.toString(); - if (!this.reporters_[hashString]) { - this.reporters_[hashString] = creatorFunction(); - } - return this.reporters_[hashString]; - }; - StatsManager.collections_ = {}; - StatsManager.reporters_ = {}; - return StatsManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns the delta from the previous call to get stats. - * - * @param collection_ The collection to "listen" to. - * @constructor - */ -var StatsListener = /** @class */ (function () { - function StatsListener(collection_) { - this.collection_ = collection_; - this.last_ = null; - } - StatsListener.prototype.get = function () { - var newStats = this.collection_.get(); - var delta = util.clone(newStats); - if (this.last_) { - util.forEach(this.last_, function (stat, value) { - delta[stat] = delta[stat] - value; - }); - } - this.last_ = newStats; - return delta; - }; - return StatsListener; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably -// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10 -// seconds to try to ensure the Firebase connection is established / settled. -var FIRST_STATS_MIN_TIME = 10 * 1000; -var FIRST_STATS_MAX_TIME = 30 * 1000; -// We'll continue to report stats on average every 5 minutes. -var REPORT_STATS_INTERVAL = 5 * 60 * 1000; -/** - * @constructor - */ -var StatsReporter = /** @class */ (function () { - /** - * @param collection - * @param server_ - */ - function StatsReporter(collection, server_) { - this.server_ = server_; - this.statsToReport_ = {}; - this.statsListener_ = new StatsListener(collection); - var timeout = FIRST_STATS_MIN_TIME + - (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random(); - setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout)); - } - StatsReporter.prototype.includeStat = function (stat) { - this.statsToReport_[stat] = true; - }; - StatsReporter.prototype.reportStats_ = function () { - var _this = this; - var stats = this.statsListener_.get(); - var reportedStats = {}; - var haveStatsToReport = false; - util.forEach(stats, function (stat, value) { - if (value > 0 && util.contains(_this.statsToReport_, stat)) { - reportedStats[stat] = value; - haveStatsToReport = true; - } - }); - if (haveStatsToReport) { - this.server_.reportStats(reportedStats); - } - // queue our next run. - setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)); - }; - return StatsReporter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * The event queue serves a few purposes: - * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more - * events being queued. - * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, - * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call - * left off, ensuring that the events are still raised synchronously and in order. - * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued - * events are raised synchronously. - * - * NOTE: This can all go away if/when we move to async events. - * - * @constructor - */ -var EventQueue = /** @class */ (function () { - function EventQueue() { - /** - * @private - * @type {!Array.} - */ - this.eventLists_ = []; - /** - * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. - * @private - * @type {!number} - */ - this.recursionDepth_ = 0; - } - /** - * @param {!Array.} eventDataList The new events to queue. - */ - EventQueue.prototype.queueEvents = function (eventDataList) { - // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly. - var currList = null; - for (var i = 0; i < eventDataList.length; i++) { - var eventData = eventDataList[i]; - var eventPath = eventData.getPath(); - if (currList !== null && !eventPath.equals(currList.getPath())) { - this.eventLists_.push(currList); - currList = null; - } - if (currList === null) { - currList = new EventList(eventPath); - } - currList.add(eventData); - } - if (currList) { - this.eventLists_.push(currList); - } - }; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) - * for the specified path. - * - * It is assumed that the new events are all for the specified path. - * - * @param {!Path} path The path to raise events for. - * @param {!Array.} eventDataList The new events to raise. - */ - EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) { - this.queueEvents(eventDataList); - this.raiseQueuedEventsMatchingPredicate_(function (eventPath) { - return eventPath.equals(path); - }); - }; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) for - * locations related to the specified change path (i.e. all ancestors and descendants). - * - * It is assumed that the new events are all related (ancestor or descendant) to the specified path. - * - * @param {!Path} changedPath The path to raise events for. - * @param {!Array.} eventDataList The events to raise - */ - EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) { - this.queueEvents(eventDataList); - this.raiseQueuedEventsMatchingPredicate_(function (eventPath) { - return eventPath.contains(changedPath) || changedPath.contains(eventPath); - }); - }; - /** - * @param {!function(!Path):boolean} predicate - * @private - */ - EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) { - this.recursionDepth_++; - var sentAll = true; - for (var i = 0; i < this.eventLists_.length; i++) { - var eventList = this.eventLists_[i]; - if (eventList) { - var eventPath = eventList.getPath(); - if (predicate(eventPath)) { - this.eventLists_[i].raise(); - this.eventLists_[i] = null; - } - else { - sentAll = false; - } - } - } - if (sentAll) { - this.eventLists_ = []; - } - this.recursionDepth_--; - }; - return EventQueue; -}()); -/** - * @param {!Path} path - * @constructor - */ -var EventList = /** @class */ (function () { - function EventList(path_) { - this.path_ = path_; - /** - * @type {!Array.} - * @private - */ - this.events_ = []; - } - /** - * @param {!Event} eventData - */ - EventList.prototype.add = function (eventData) { - this.events_.push(eventData); - }; - /** - * Iterates through the list and raises each event - */ - EventList.prototype.raise = function () { - for (var i = 0; i < this.events_.length; i++) { - var eventData = this.events_[i]; - if (eventData !== null) { - this.events_[i] = null; - var eventFn = eventData.getEventRunner(); - if (logger$1) { - log('event: ' + eventData.toString()); - } - exceptionGuard(eventFn); - } - } - }; - /** - * @return {!Path} - */ - EventList.prototype.getPath = function () { - return this.path_; - }; - return EventList; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Base class to be used if you want to emit events. Call the constructor with - * the set of allowed event names. - */ -var EventEmitter = /** @class */ (function () { - /** - * @param {!Array.} allowedEvents_ - */ - function EventEmitter(allowedEvents_) { - this.allowedEvents_ = allowedEvents_; - this.listeners_ = {}; - util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); - } - /** - * To be called by derived classes to trigger events. - * @param {!string} eventType - * @param {...*} var_args - */ - EventEmitter.prototype.trigger = function (eventType) { - var var_args = []; - for (var _i = 1; _i < arguments.length; _i++) { - var_args[_i - 1] = arguments[_i]; - } - if (Array.isArray(this.listeners_[eventType])) { - // Clone the list, since callbacks could add/remove listeners. - var listeners = this.listeners_[eventType].slice(); - for (var i = 0; i < listeners.length; i++) { - listeners[i].callback.apply(listeners[i].context, var_args); - } - } - }; - EventEmitter.prototype.on = function (eventType, callback, context) { - this.validateEventType_(eventType); - this.listeners_[eventType] = this.listeners_[eventType] || []; - this.listeners_[eventType].push({ callback: callback, context: context }); - var eventData = this.getInitialEvent(eventType); - if (eventData) { - callback.apply(context, eventData); - } - }; - EventEmitter.prototype.off = function (eventType, callback, context) { - this.validateEventType_(eventType); - var listeners = this.listeners_[eventType] || []; - for (var i = 0; i < listeners.length; i++) { - if (listeners[i].callback === callback && - (!context || context === listeners[i].context)) { - listeners.splice(i, 1); - return; - } - } - }; - EventEmitter.prototype.validateEventType_ = function (eventType) { - util.assert(this.allowedEvents_.find(function (et) { - return et === eventType; - }), 'Unknown event: ' + eventType); - }; - return EventEmitter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @extends {EventEmitter} - */ -var VisibilityMonitor = /** @class */ (function (_super) { - tslib_1.__extends(VisibilityMonitor, _super); - function VisibilityMonitor() { - var _this = _super.call(this, ['visible']) || this; - var hidden; - var visibilityChange; - if (typeof document !== 'undefined' && - typeof document.addEventListener !== 'undefined') { - if (typeof document['hidden'] !== 'undefined') { - // Opera 12.10 and Firefox 18 and later support - visibilityChange = 'visibilitychange'; - hidden = 'hidden'; - } - else if (typeof document['mozHidden'] !== 'undefined') { - visibilityChange = 'mozvisibilitychange'; - hidden = 'mozHidden'; - } - else if (typeof document['msHidden'] !== 'undefined') { - visibilityChange = 'msvisibilitychange'; - hidden = 'msHidden'; - } - else if (typeof document['webkitHidden'] !== 'undefined') { - visibilityChange = 'webkitvisibilitychange'; - hidden = 'webkitHidden'; - } - } - // Initially, we always assume we are visible. This ensures that in browsers - // without page visibility support or in cases where we are never visible - // (e.g. chrome extension), we act as if we are visible, i.e. don't delay - // reconnects - _this.visible_ = true; - if (visibilityChange) { - document.addEventListener(visibilityChange, function () { - var visible = !document[hidden]; - if (visible !== _this.visible_) { - _this.visible_ = visible; - _this.trigger('visible', visible); - } - }, false); - } - return _this; - } - VisibilityMonitor.getInstance = function () { - return new VisibilityMonitor(); - }; - /** - * @param {!string} eventType - * @return {Array.} - */ - VisibilityMonitor.prototype.getInitialEvent = function (eventType) { - util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); - return [this.visible_]; - }; - return VisibilityMonitor; -}(EventEmitter)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Monitors online state (as reported by window.online/offline events). - * - * The expectation is that this could have many false positives (thinks we are online - * when we're not), but no false negatives. So we can safely use it to determine when - * we definitely cannot reach the internet. - * - * @extends {EventEmitter} - */ -var OnlineMonitor = /** @class */ (function (_super) { - tslib_1.__extends(OnlineMonitor, _super); - function OnlineMonitor() { - var _this = _super.call(this, ['online']) || this; - _this.online_ = true; - // We've had repeated complaints that Cordova apps can get stuck "offline", e.g. - // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810 - // It would seem that the 'online' event does not always fire consistently. So we disable it - // for Cordova. - if (typeof window !== 'undefined' && - typeof window.addEventListener !== 'undefined' && - !util.isMobileCordova()) { - window.addEventListener('online', function () { - if (!_this.online_) { - _this.online_ = true; - _this.trigger('online', true); - } - }, false); - window.addEventListener('offline', function () { - if (_this.online_) { - _this.online_ = false; - _this.trigger('online', false); - } - }, false); - } - return _this; - } - OnlineMonitor.getInstance = function () { - return new OnlineMonitor(); - }; - /** - * @param {!string} eventType - * @return {Array.} - */ - OnlineMonitor.prototype.getInitialEvent = function (eventType) { - util.assert(eventType === 'online', 'Unknown event type: ' + eventType); - return [this.online_]; - }; - /** - * @return {boolean} - */ - OnlineMonitor.prototype.currentlyOnline = function () { - return this.online_; - }; - return OnlineMonitor; -}(EventEmitter)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class ensures the packets from the server arrive in order - * This class takes data from the server and ensures it gets passed into the callbacks in order. - * @constructor - */ -var PacketReceiver = /** @class */ (function () { - /** - * @param onMessage_ - */ - function PacketReceiver(onMessage_) { - this.onMessage_ = onMessage_; - this.pendingResponses = []; - this.currentResponseNum = 0; - this.closeAfterResponse = -1; - this.onClose = null; - } - PacketReceiver.prototype.closeAfter = function (responseNum, callback) { - this.closeAfterResponse = responseNum; - this.onClose = callback; - if (this.closeAfterResponse < this.currentResponseNum) { - this.onClose(); - this.onClose = null; - } - }; - /** - * Each message from the server comes with a response number, and an array of data. The responseNumber - * allows us to ensure that we process them in the right order, since we can't be guaranteed that all - * browsers will respond in the same order as the requests we sent - * @param {number} requestNum - * @param {Array} data - */ - PacketReceiver.prototype.handleResponse = function (requestNum, data) { - var _this = this; - this.pendingResponses[requestNum] = data; - var _loop_1 = function () { - var toProcess = this_1.pendingResponses[this_1.currentResponseNum]; - delete this_1.pendingResponses[this_1.currentResponseNum]; - var _loop_2 = function (i) { - if (toProcess[i]) { - exceptionGuard(function () { - _this.onMessage_(toProcess[i]); - }); - } - }; - for (var i = 0; i < toProcess.length; ++i) { - _loop_2(i); - } - if (this_1.currentResponseNum === this_1.closeAfterResponse) { - if (this_1.onClose) { - this_1.onClose(); - this_1.onClose = null; - } - return "break"; - } - this_1.currentResponseNum++; - }; - var this_1 = this; - while (this.pendingResponses[this.currentResponseNum]) { - var state_1 = _loop_1(); - if (state_1 === "break") - break; - } - }; - return PacketReceiver; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// URL query parameters associated with longpolling -var FIREBASE_LONGPOLL_START_PARAM = 'start'; -var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close'; -var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand'; -var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB'; -var FIREBASE_LONGPOLL_ID_PARAM = 'id'; -var FIREBASE_LONGPOLL_PW_PARAM = 'pw'; -var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser'; -var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb'; -var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg'; -var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts'; -var FIREBASE_LONGPOLL_DATA_PARAM = 'd'; -var FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn'; -var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe'; -//Data size constants. -//TODO: Perf: the maximum length actually differs from browser to browser. -// We should check what browser we're on and set accordingly. -var MAX_URL_DATA_SIZE = 1870; -var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d= -var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; -/** - * Keepalive period - * send a fresh request at minimum every 25 seconds. Opera has a maximum request - * length of 30 seconds that we can't exceed. - * @const - * @type {number} - */ -var KEEPALIVE_REQUEST_INTERVAL = 25000; -/** - * How long to wait before aborting a long-polling connection attempt. - * @const - * @type {number} - */ -var LP_CONNECT_TIMEOUT = 30000; -/** - * This class manages a single long-polling connection. - * - * @constructor - * @implements {Transport} - */ -var BrowserPollConnection = /** @class */ (function () { - /** - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing - * transport session - * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a - * connection previously - */ - function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) { - this.connId = connId; - this.repoInfo = repoInfo; - this.transportSessionId = transportSessionId; - this.lastSessionId = lastSessionId; - this.bytesSent = 0; - this.bytesReceived = 0; - this.everConnected_ = false; - this.log_ = logWrapper(connId); - this.stats_ = StatsManager.getCollection(repoInfo); - this.urlFn = function (params) { - return repoInfo.connectionURL(LONG_POLLING, params); - }; - } - /** - * - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) { - var _this = this; - this.curSegmentNum = 0; - this.onDisconnect_ = onDisconnect; - this.myPacketOrderer = new PacketReceiver(onMessage); - this.isClosed_ = false; - this.connectTimeoutTimer_ = setTimeout(function () { - _this.log_('Timed out trying to connect.'); - // Make sure we clear the host cache - _this.onClosed_(); - _this.connectTimeoutTimer_ = null; - }, Math.floor(LP_CONNECT_TIMEOUT)); - // Ensure we delay the creation of the iframe until the DOM is loaded. - executeWhenDOMReady(function () { - if (_this.isClosed_) - return; - //Set up a callback that gets triggered once a connection is set up. - _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var command = args[0], arg1 = args[1], arg2 = args[2]; - _this.incrementIncomingBytes_(args); - if (!_this.scriptTagHolder) - return; // we closed the connection. - if (_this.connectTimeoutTimer_) { - clearTimeout(_this.connectTimeoutTimer_); - _this.connectTimeoutTimer_ = null; - } - _this.everConnected_ = true; - if (command == FIREBASE_LONGPOLL_START_PARAM) { - _this.id = arg1; - _this.password = arg2; - } - else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) { - // Don't clear the host cache. We got a response from the server, so we know it's reachable - if (arg1) { - // We aren't expecting any more data (other than what the server's already in the process of sending us - // through our already open polls), so don't send any more. - _this.scriptTagHolder.sendNewPolls = false; - // arg1 in this case is the last response number sent by the server. We should try to receive - // all of the responses up to this one before closing - _this.myPacketOrderer.closeAfter(arg1, function () { - _this.onClosed_(); - }); - } - else { - _this.onClosed_(); - } - } - else { - throw new Error('Unrecognized command received: ' + command); - } - }, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var pN = args[0], data = args[1]; - _this.incrementIncomingBytes_(args); - _this.myPacketOrderer.handleResponse(pN, data); - }, function () { - _this.onClosed_(); - }, _this.urlFn); - //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results - //from cache. - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000); - if (_this.scriptTagHolder.uniqueCallbackIdentifier) - urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier; - urlParams[VERSION_PARAM] = PROTOCOL_VERSION; - if (_this.transportSessionId) { - urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId; - } - if (_this.lastSessionId) { - urlParams[LAST_SESSION_PARAM] = _this.lastSessionId; - } - if (!util.isNodeSdk() && - typeof location !== 'undefined' && - location.href && - location.href.indexOf(FORGE_DOMAIN) !== -1) { - urlParams[REFERER_PARAM] = FORGE_REF; - } - var connectURL = _this.urlFn(urlParams); - _this.log_('Connecting via long-poll to ' + connectURL); - _this.scriptTagHolder.addTag(connectURL, function () { - /* do nothing */ - }); - }); - }; - /** - * Call this when a handshake has completed successfully and we want to consider the connection established - */ - BrowserPollConnection.prototype.start = function () { - this.scriptTagHolder.startLongPoll(this.id, this.password); - this.addDisconnectPingFrame(this.id, this.password); - }; - /** - * Forces long polling to be considered as a potential transport - */ - BrowserPollConnection.forceAllow = function () { - BrowserPollConnection.forceAllow_ = true; - }; - /** - * Forces longpolling to not be considered as a potential transport - */ - BrowserPollConnection.forceDisallow = function () { - BrowserPollConnection.forceDisallow_ = true; - }; - // Static method, use string literal so it can be accessed in a generic way - BrowserPollConnection.isAvailable = function () { - // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in - // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08). - return (BrowserPollConnection.forceAllow_ || - (!BrowserPollConnection.forceDisallow_ && - typeof document !== 'undefined' && - document.createElement != null && - !isChromeExtensionContentScript() && - !isWindowsStoreApp() && - !util.isNodeSdk())); - }; - /** - * No-op for polling - */ - BrowserPollConnection.prototype.markConnectionHealthy = function () { }; - /** - * Stops polling and cleans up the iframe - * @private - */ - BrowserPollConnection.prototype.shutdown_ = function () { - this.isClosed_ = true; - if (this.scriptTagHolder) { - this.scriptTagHolder.close(); - this.scriptTagHolder = null; - } - //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving. - if (this.myDisconnFrame) { - document.body.removeChild(this.myDisconnFrame); - this.myDisconnFrame = null; - } - if (this.connectTimeoutTimer_) { - clearTimeout(this.connectTimeoutTimer_); - this.connectTimeoutTimer_ = null; - } - }; - /** - * Triggered when this transport is closed - * @private - */ - BrowserPollConnection.prototype.onClosed_ = function () { - if (!this.isClosed_) { - this.log_('Longpoll is closing itself'); - this.shutdown_(); - if (this.onDisconnect_) { - this.onDisconnect_(this.everConnected_); - this.onDisconnect_ = null; - } - } - }; - /** - * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server - * that we've left. - */ - BrowserPollConnection.prototype.close = function () { - if (!this.isClosed_) { - this.log_('Longpoll is being closed.'); - this.shutdown_(); - } - }; - /** - * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then - * broken into chunks (since URLs have a small maximum length). - * @param {!Object} data The JSON data to transmit. - */ - BrowserPollConnection.prototype.send = function (data) { - var dataStr = util.stringify(data); - this.bytesSent += dataStr.length; - this.stats_.incrementCounter('bytes_sent', dataStr.length); - //first, lets get the base64-encoded data - var base64data = util.base64Encode(dataStr); - //We can only fit a certain amount in each URL, so we need to split this request - //up into multiple pieces if it doesn't fit in one request. - var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE); - //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number - //of segments so that we can reassemble the packet on the server. - for (var i = 0; i < dataSegs.length; i++) { - this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]); - this.curSegmentNum++; - } - }; - /** - * This is how we notify the server that we're leaving. - * We aren't able to send requests with DHTML on a window close event, but we can - * trigger XHR requests in some browsers (everything but Opera basically). - * @param {!string} id - * @param {!string} pw - */ - BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) { - if (util.isNodeSdk()) - return; - this.myDisconnFrame = document.createElement('iframe'); - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw; - this.myDisconnFrame.src = this.urlFn(urlParams); - this.myDisconnFrame.style.display = 'none'; - document.body.appendChild(this.myDisconnFrame); - }; - /** - * Used to track the bytes received by this client - * @param {*} args - * @private - */ - BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) { - // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in. - var bytesReceived = util.stringify(args).length; - this.bytesReceived += bytesReceived; - this.stats_.incrementCounter('bytes_received', bytesReceived); - }; - return BrowserPollConnection; -}()); -/********************************************************************************************* - * A wrapper around an iframe that is used as a long-polling script holder. - * @constructor - *********************************************************************************************/ -var FirebaseIFrameScriptHolder = /** @class */ (function () { - /** - * @param commandCB - The callback to be called when control commands are recevied from the server. - * @param onMessageCB - The callback to be triggered when responses arrive from the server. - * @param onDisconnect - The callback to be triggered when this tag holder is closed - * @param urlFn - A function that provides the URL of the endpoint to send data to. - */ - function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) { - this.onDisconnect = onDisconnect; - this.urlFn = urlFn; - //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause - //problems in some browsers. - /** - * @type {CountedSet.} - */ - this.outstandingRequests = new CountedSet(); - //A queue of the pending segments waiting for transmission to the server. - this.pendingSegs = []; - //A serial number. We use this for two things: - // 1) A way to ensure the browser doesn't cache responses to polls - // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The - // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute - // JSONP code in the order it was added to the iframe. - this.currentSerial = Math.floor(Math.random() * 100000000); - // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still - // incoming data from the server that we're waiting for). - this.sendNewPolls = true; - if (!util.isNodeSdk()) { - //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the - //iframes where we put the long-polling script tags. We have two callbacks: - // 1) Command Callback - Triggered for control issues, like starting a connection. - // 2) Message Callback - Triggered when new data arrives. - this.uniqueCallbackIdentifier = LUIDGenerator(); - window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB; - window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB; - //Create an iframe for us to add script tags to. - this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_(); - // Set the iframe's contents. - var script = ''; - // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient - // for ie9, but ie8 needs to do it again in the document itself. - if (this.myIFrame.src && - this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') { - var currentDomain = document.domain; - script = ''; - } - var iframeContents = '' + script + ''; - try { - this.myIFrame.doc.open(); - this.myIFrame.doc.write(iframeContents); - this.myIFrame.doc.close(); - } - catch (e) { - log('frame writing exception'); - if (e.stack) { - log(e.stack); - } - log(e); - } - } - else { - this.commandCB = commandCB; - this.onMessageCB = onMessageCB; - } - } - /** - * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can - * actually use. - * @private - * @return {Element} - */ - FirebaseIFrameScriptHolder.createIFrame_ = function () { - var iframe = document.createElement('iframe'); - iframe.style.display = 'none'; - // This is necessary in order to initialize the document inside the iframe - if (document.body) { - document.body.appendChild(iframe); - try { - // If document.domain has been modified in IE, this will throw an error, and we need to set the - // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute - // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work. - var a = iframe.contentWindow.document; - if (!a) { - // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above. - log('No IE domain setting required'); - } - } - catch (e) { - var domain = document.domain; - iframe.src = - "javascript:void((function(){document.open();document.domain='" + - domain + - "';document.close();})())"; - } - } - else { - // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this - // never gets hit. - throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.'; - } - // Get the document of the iframe in a browser-specific way. - if (iframe.contentDocument) { - iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari - } - else if (iframe.contentWindow) { - iframe.doc = iframe.contentWindow.document; // Internet Explorer - } - else if (iframe.document) { - iframe.doc = iframe.document; //others? - } - return iframe; - }; - /** - * Cancel all outstanding queries and remove the frame. - */ - FirebaseIFrameScriptHolder.prototype.close = function () { - var _this = this; - //Mark this iframe as dead, so no new requests are sent. - this.alive = false; - if (this.myIFrame) { - //We have to actually remove all of the html inside this iframe before removing it from the - //window, or IE will continue loading and executing the script tags we've already added, which - //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this. - this.myIFrame.doc.body.innerHTML = ''; - setTimeout(function () { - if (_this.myIFrame !== null) { - document.body.removeChild(_this.myIFrame); - _this.myIFrame = null; - } - }, Math.floor(0)); - } - if (util.isNodeSdk() && this.myID) { - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't'; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; - var theURL = this.urlFn(urlParams); - FirebaseIFrameScriptHolder.nodeRestRequest(theURL); - } - // Protect from being called recursively. - var onDisconnect = this.onDisconnect; - if (onDisconnect) { - this.onDisconnect = null; - onDisconnect(); - } - }; - /** - * Actually start the long-polling session by adding the first script tag(s) to the iframe. - * @param {!string} id - The ID of this connection - * @param {!string} pw - The password for this connection - */ - FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) { - this.myID = id; - this.myPW = pw; - this.alive = true; - //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to. - while (this.newRequest_()) { } - }; - /** - * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't - * too many outstanding requests and we are still alive. - * - * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if - * needed. - */ - FirebaseIFrameScriptHolder.prototype.newRequest_ = function () { - // We keep one outstanding request open all the time to receive data, but if we need to send data - // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically - // close the old request. - if (this.alive && - this.sendNewPolls && - this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) { - //construct our url - this.currentSerial++; - var urlParams = {}; - urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID; - urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW; - urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial; - var theURL = this.urlFn(urlParams); - //Now add as much data as we can. - var curDataString = ''; - var i = 0; - while (this.pendingSegs.length > 0) { - //first, lets see if the next segment will fit. - var nextSeg = this.pendingSegs[0]; - if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <= - MAX_URL_DATA_SIZE) { - //great, the segment will fit. Lets append it. - var theSeg = this.pendingSegs.shift(); - curDataString = - curDataString + - '&' + - FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + - i + - '=' + - theSeg.seg + - '&' + - FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + - i + - '=' + - theSeg.ts + - '&' + - FIREBASE_LONGPOLL_DATA_PARAM + - i + - '=' + - theSeg.d; - i++; - } - else { - break; - } - } - theURL = theURL + curDataString; - this.addLongPollTag_(theURL, this.currentSerial); - return true; - } - else { - return false; - } - }; - /** - * Queue a packet for transmission to the server. - * @param segnum - A sequential id for this packet segment used for reassembly - * @param totalsegs - The total number of segments in this packet - * @param data - The data for this segment. - */ - FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) { - //add this to the queue of segments to send. - this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data }); - //send the data immediately if there isn't already data being transmitted, unless - //startLongPoll hasn't been called yet. - if (this.alive) { - this.newRequest_(); - } - }; - /** - * Add a script tag for a regular long-poll request. - * @param {!string} url - The URL of the script tag. - * @param {!number} serial - The serial number of the request. - * @private - */ - FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) { - var _this = this; - //remember that we sent this request. - this.outstandingRequests.add(serial, 1); - var doNewRequest = function () { - _this.outstandingRequests.remove(serial); - _this.newRequest_(); - }; - // If this request doesn't return on its own accord (by the server sending us some data), we'll - // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open. - var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL)); - var readyStateCB = function () { - // Request completed. Cancel the keepalive. - clearTimeout(keepaliveTimeout); - // Trigger a new request so we can continue receiving data. - doNewRequest(); - }; - this.addTag(url, readyStateCB); - }; - /** - * Add an arbitrary script tag to the iframe. - * @param {!string} url - The URL for the script tag source. - * @param {!function()} loadCB - A callback to be triggered once the script has loaded. - */ - FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) { - var _this = this; - if (util.isNodeSdk()) { - this.doNodeLongPoll(url, loadCB); - } - else { - setTimeout(function () { - try { - // if we're already closed, don't add this poll - if (!_this.sendNewPolls) - return; - var newScript_1 = _this.myIFrame.doc.createElement('script'); - newScript_1.type = 'text/javascript'; - newScript_1.async = true; - newScript_1.src = url; - newScript_1.onload = newScript_1.onreadystatechange = function () { - var rstate = newScript_1.readyState; - if (!rstate || rstate === 'loaded' || rstate === 'complete') { - newScript_1.onload = newScript_1.onreadystatechange = null; - if (newScript_1.parentNode) { - newScript_1.parentNode.removeChild(newScript_1); - } - loadCB(); - } - }; - newScript_1.onerror = function () { - log('Long-poll script failed to load: ' + url); - _this.sendNewPolls = false; - _this.close(); - }; - _this.myIFrame.doc.body.appendChild(newScript_1); - } - catch (e) { - // TODO: we should make this error visible somehow - } - }, Math.floor(1)); - } - }; - return FirebaseIFrameScriptHolder; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var WEBSOCKET_MAX_FRAME_SIZE = 16384; -var WEBSOCKET_KEEPALIVE_INTERVAL = 45000; -var WebSocketImpl = null; -if (typeof MozWebSocket !== 'undefined') { - WebSocketImpl = MozWebSocket; -} -else if (typeof WebSocket !== 'undefined') { - WebSocketImpl = WebSocket; -} -function setWebSocketImpl(impl) { - WebSocketImpl = impl; -} -/** - * Create a new websocket connection with the given callbacks. - * @constructor - * @implements {Transport} - */ -var WebSocketConnection = /** @class */ (function () { - /** - * @param {string} connId identifier for this transport - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - */ - function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) { - this.connId = connId; - this.keepaliveTimer = null; - this.frames = null; - this.totalFrames = 0; - this.bytesSent = 0; - this.bytesReceived = 0; - this.log_ = logWrapper(this.connId); - this.stats_ = StatsManager.getCollection(repoInfo); - this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId); - } - /** - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @return {string} connection url - * @private - */ - WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) { - var urlParams = {}; - urlParams[VERSION_PARAM] = PROTOCOL_VERSION; - if (!util.isNodeSdk() && - typeof location !== 'undefined' && - location.href && - location.href.indexOf(FORGE_DOMAIN) !== -1) { - urlParams[REFERER_PARAM] = FORGE_REF; - } - if (transportSessionId) { - urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId; - } - if (lastSessionId) { - urlParams[LAST_SESSION_PARAM] = lastSessionId; - } - return repoInfo.connectionURL(WEBSOCKET, urlParams); - }; - /** - * - * @param onMessage Callback when messages arrive - * @param onDisconnect Callback with connection lost. - */ - WebSocketConnection.prototype.open = function (onMessage, onDisconnect) { - var _this = this; - this.onDisconnect = onDisconnect; - this.onMessage = onMessage; - this.log_('Websocket connecting to ' + this.connURL); - this.everConnected_ = false; - // Assume failure until proven otherwise. - PersistentStorage.set('previous_websocket_failure', true); - try { - if (util.isNodeSdk()) { - var device = util.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node'; - // UA Format: Firebase//// - var options = { - headers: { - 'User-Agent': "Firebase/" + PROTOCOL_VERSION + "/" + firebase.SDK_VERSION + "/" + process.platform + "/" + device - } - }; - // Plumb appropriate http_proxy environment variable into faye-websocket if it exists. - var env = process['env']; - var proxy = this.connURL.indexOf('wss://') == 0 - ? env['HTTPS_PROXY'] || env['https_proxy'] - : env['HTTP_PROXY'] || env['http_proxy']; - if (proxy) { - options['proxy'] = { origin: proxy }; - } - this.mySock = new WebSocketImpl(this.connURL, [], options); - } - else { - this.mySock = new WebSocketImpl(this.connURL); - } - } - catch (e) { - this.log_('Error instantiating WebSocket.'); - var error$$1 = e.message || e.data; - if (error$$1) { - this.log_(error$$1); - } - this.onClosed_(); - return; - } - this.mySock.onopen = function () { - _this.log_('Websocket connected.'); - _this.everConnected_ = true; - }; - this.mySock.onclose = function () { - _this.log_('Websocket connection was disconnected.'); - _this.mySock = null; - _this.onClosed_(); - }; - this.mySock.onmessage = function (m) { - _this.handleIncomingFrame(m); - }; - this.mySock.onerror = function (e) { - _this.log_('WebSocket error. Closing connection.'); - var error$$1 = e.message || e.data; - if (error$$1) { - _this.log_(error$$1); - } - _this.onClosed_(); - }; - }; - /** - * No-op for websockets, we don't need to do anything once the connection is confirmed as open - */ - WebSocketConnection.prototype.start = function () { }; - WebSocketConnection.forceDisallow = function () { - WebSocketConnection.forceDisallow_ = true; - }; - WebSocketConnection.isAvailable = function () { - var isOldAndroid = false; - if (typeof navigator !== 'undefined' && navigator.userAgent) { - var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/; - var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex); - if (oldAndroidMatch && oldAndroidMatch.length > 1) { - if (parseFloat(oldAndroidMatch[1]) < 4.4) { - isOldAndroid = true; - } - } - } - return (!isOldAndroid && - WebSocketImpl !== null && - !WebSocketConnection.forceDisallow_); - }; - /** - * Returns true if we previously failed to connect with this transport. - * @return {boolean} - */ - WebSocketConnection.previouslyFailed = function () { - // If our persistent storage is actually only in-memory storage, - // we default to assuming that it previously failed to be safe. - return (PersistentStorage.isInMemoryStorage || - PersistentStorage.get('previous_websocket_failure') === true); - }; - WebSocketConnection.prototype.markConnectionHealthy = function () { - PersistentStorage.remove('previous_websocket_failure'); - }; - WebSocketConnection.prototype.appendFrame_ = function (data) { - this.frames.push(data); - if (this.frames.length == this.totalFrames) { - var fullMess = this.frames.join(''); - this.frames = null; - var jsonMess = util.jsonEval(fullMess); - //handle the message - this.onMessage(jsonMess); - } - }; - /** - * @param {number} frameCount The number of frames we are expecting from the server - * @private - */ - WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) { - this.totalFrames = frameCount; - this.frames = []; - }; - /** - * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 - * @param {!String} data - * @return {?String} Any remaining data to be process, or null if there is none - * @private - */ - WebSocketConnection.prototype.extractFrameCount_ = function (data) { - util.assert(this.frames === null, 'We already have a frame buffer'); - // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced - // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508 - if (data.length <= 6) { - var frameCount = Number(data); - if (!isNaN(frameCount)) { - this.handleNewFrameCount_(frameCount); - return null; - } - } - this.handleNewFrameCount_(1); - return data; - }; - /** - * Process a websocket frame that has arrived from the server. - * @param mess The frame data - */ - WebSocketConnection.prototype.handleIncomingFrame = function (mess) { - if (this.mySock === null) - return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes. - var data = mess['data']; - this.bytesReceived += data.length; - this.stats_.incrementCounter('bytes_received', data.length); - this.resetKeepAlive(); - if (this.frames !== null) { - // we're buffering - this.appendFrame_(data); - } - else { - // try to parse out a frame count, otherwise, assume 1 and process it - var remainingData = this.extractFrameCount_(data); - if (remainingData !== null) { - this.appendFrame_(remainingData); - } - } - }; - /** - * Send a message to the server - * @param {Object} data The JSON object to transmit - */ - WebSocketConnection.prototype.send = function (data) { - this.resetKeepAlive(); - var dataStr = util.stringify(data); - this.bytesSent += dataStr.length; - this.stats_.incrementCounter('bytes_sent', dataStr.length); - //We can only fit a certain amount in each websocket frame, so we need to split this request - //up into multiple pieces if it doesn't fit in one request. - var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); - //Send the length header - if (dataSegs.length > 1) { - this.sendString_(String(dataSegs.length)); - } - //Send the actual data in segments. - for (var i = 0; i < dataSegs.length; i++) { - this.sendString_(dataSegs[i]); - } - }; - WebSocketConnection.prototype.shutdown_ = function () { - this.isClosed_ = true; - if (this.keepaliveTimer) { - clearInterval(this.keepaliveTimer); - this.keepaliveTimer = null; - } - if (this.mySock) { - this.mySock.close(); - this.mySock = null; - } - }; - WebSocketConnection.prototype.onClosed_ = function () { - if (!this.isClosed_) { - this.log_('WebSocket is closing itself'); - this.shutdown_(); - // since this is an internal close, trigger the close listener - if (this.onDisconnect) { - this.onDisconnect(this.everConnected_); - this.onDisconnect = null; - } - } - }; - /** - * External-facing close handler. - * Close the websocket and kill the connection. - */ - WebSocketConnection.prototype.close = function () { - if (!this.isClosed_) { - this.log_('WebSocket is being closed'); - this.shutdown_(); - } - }; - /** - * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after - * the last activity. - */ - WebSocketConnection.prototype.resetKeepAlive = function () { - var _this = this; - clearInterval(this.keepaliveTimer); - this.keepaliveTimer = setInterval(function () { - //If there has been no websocket activity for a while, send a no-op - if (_this.mySock) { - _this.sendString_('0'); - } - _this.resetKeepAlive(); - }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL)); - }; - /** - * Send a string over the websocket. - * - * @param {string} str String to send. - * @private - */ - WebSocketConnection.prototype.sendString_ = function (str) { - // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send() - // calls for some unknown reason. We treat these as an error and disconnect. - // See https://app.asana.com/0/58926111402292/68021340250410 - try { - this.mySock.send(str); - } - catch (e) { - this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.'); - setTimeout(this.onClosed_.bind(this), 0); - } - }; - /** - * Number of response before we consider the connection "healthy." - * @type {number} - */ - WebSocketConnection.responsesRequiredToBeHealthy = 2; - /** - * Time to wait for the connection te become healthy before giving up. - * @type {number} - */ - WebSocketConnection.healthyTimeout = 30000; - return WebSocketConnection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Currently simplistic, this class manages what transport a Connection should use at various stages of its - * lifecycle. - * - * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if - * they are available. - * @constructor - */ -var TransportManager = /** @class */ (function () { - /** - * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to - */ - function TransportManager(repoInfo) { - this.initTransports_(repoInfo); - } - Object.defineProperty(TransportManager, "ALL_TRANSPORTS", { - /** - * @const - * @type {!Array.} - */ - get: function () { - return [BrowserPollConnection, WebSocketConnection]; - }, - enumerable: true, - configurable: true - }); - /** - * @param {!RepoInfo} repoInfo - * @private - */ - TransportManager.prototype.initTransports_ = function (repoInfo) { - var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable'](); - var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed(); - if (repoInfo.webSocketOnly) { - if (!isWebSocketsAvailable) - warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."); - isSkipPollConnection = true; - } - if (isSkipPollConnection) { - this.transports_ = [WebSocketConnection]; - } - else { - var transports_1 = (this.transports_ = []); - each(TransportManager.ALL_TRANSPORTS, function (i, transport) { - if (transport && transport['isAvailable']()) { - transports_1.push(transport); - } - }); - } - }; - /** - * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the - * initial transport to use - */ - TransportManager.prototype.initialTransport = function () { - if (this.transports_.length > 0) { - return this.transports_[0]; - } - else { - throw new Error('No transports available'); - } - }; - /** - * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next - * transport, or null - */ - TransportManager.prototype.upgradeTransport = function () { - if (this.transports_.length > 1) { - return this.transports_[1]; - } - else { - return null; - } - }; - return TransportManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Abort upgrade attempt if it takes longer than 60s. -var UPGRADE_TIMEOUT = 60000; -// For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses. -// If we haven't sent enough requests within 5s, we'll start sending noop ping requests. -var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; -// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data) -// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout -// but we've sent/received enough bytes, we don't cancel the connection. -var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024; -var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024; -var MESSAGE_TYPE = 't'; -var MESSAGE_DATA = 'd'; -var CONTROL_SHUTDOWN = 's'; -var CONTROL_RESET = 'r'; -var CONTROL_ERROR = 'e'; -var CONTROL_PONG = 'o'; -var SWITCH_ACK = 'a'; -var END_TRANSMISSION = 'n'; -var PING = 'p'; -var SERVER_HELLO = 'h'; -/** - * Creates a new real-time connection to the server using whichever method works - * best in the current browser. - * - * @constructor - */ -var Connection = /** @class */ (function () { - /** - * @param {!string} id - an id for this connection - * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to - * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives - * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages. - * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost - * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down. - * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server - */ - function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) { - this.id = id; - this.repoInfo_ = repoInfo_; - this.onMessage_ = onMessage_; - this.onReady_ = onReady_; - this.onDisconnect_ = onDisconnect_; - this.onKill_ = onKill_; - this.lastSessionId = lastSessionId; - this.connectionCount = 0; - this.pendingDataMessages = []; - this.state_ = 0 /* CONNECTING */; - this.log_ = logWrapper('c:' + this.id + ':'); - this.transportManager_ = new TransportManager(repoInfo_); - this.log_('Connection created'); - this.start_(); - } - /** - * Starts a connection attempt - * @private - */ - Connection.prototype.start_ = function () { - var _this = this; - var conn = this.transportManager_.initialTransport(); - this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId); - // For certain transports (WebSockets), we need to send and receive several messages back and forth before we - // can consider the transport healthy. - this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0; - var onMessageReceived = this.connReceiver_(this.conn_); - var onConnectionLost = this.disconnReceiver_(this.conn_); - this.tx_ = this.conn_; - this.rx_ = this.conn_; - this.secondaryConn_ = null; - this.isHealthy_ = false; - /* - * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame. - * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset. - * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should - * still have the context of your originating frame. - */ - setTimeout(function () { - // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it - _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost); - }, Math.floor(0)); - var healthyTimeout_ms = conn['healthyTimeout'] || 0; - if (healthyTimeout_ms > 0) { - this.healthyTimeout_ = setTimeoutNonBlocking(function () { - _this.healthyTimeout_ = null; - if (!_this.isHealthy_) { - if (_this.conn_ && - _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) { - _this.log_('Connection exceeded healthy timeout but has received ' + - _this.conn_.bytesReceived + - ' bytes. Marking connection healthy.'); - _this.isHealthy_ = true; - _this.conn_.markConnectionHealthy(); - } - else if (_this.conn_ && - _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) { - _this.log_('Connection exceeded healthy timeout but has sent ' + - _this.conn_.bytesSent + - ' bytes. Leaving connection alive.'); - // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to - // the server. - } - else { - _this.log_('Closing unhealthy connection after timeout.'); - _this.close(); - } - } - }, Math.floor(healthyTimeout_ms)); - } - }; - /** - * @return {!string} - * @private - */ - Connection.prototype.nextTransportId_ = function () { - return 'c:' + this.id + ':' + this.connectionCount++; - }; - Connection.prototype.disconnReceiver_ = function (conn) { - var _this = this; - return function (everConnected) { - if (conn === _this.conn_) { - _this.onConnectionLost_(everConnected); - } - else if (conn === _this.secondaryConn_) { - _this.log_('Secondary connection lost.'); - _this.onSecondaryConnectionLost_(); - } - else { - _this.log_('closing an old connection'); - } - }; - }; - Connection.prototype.connReceiver_ = function (conn) { - var _this = this; - return function (message) { - if (_this.state_ != 2 /* DISCONNECTED */) { - if (conn === _this.rx_) { - _this.onPrimaryMessageReceived_(message); - } - else if (conn === _this.secondaryConn_) { - _this.onSecondaryMessageReceived_(message); - } - else { - _this.log_('message on old connection'); - } - } - }; - }; - /** - * - * @param {Object} dataMsg An arbitrary data message to be sent to the server - */ - Connection.prototype.sendRequest = function (dataMsg) { - // wrap in a data message envelope and send it on - var msg = { t: 'd', d: dataMsg }; - this.sendData_(msg); - }; - Connection.prototype.tryCleanupConnection = function () { - if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) { - this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId); - this.conn_ = this.secondaryConn_; - this.secondaryConn_ = null; - // the server will shutdown the old connection - } - }; - Connection.prototype.onSecondaryControl_ = function (controlData) { - if (MESSAGE_TYPE in controlData) { - var cmd = controlData[MESSAGE_TYPE]; - if (cmd === SWITCH_ACK) { - this.upgradeIfSecondaryHealthy_(); - } - else if (cmd === CONTROL_RESET) { - // Most likely the session wasn't valid. Abandon the switch attempt - this.log_('Got a reset on secondary, closing it'); - this.secondaryConn_.close(); - // If we were already using this connection for something, than we need to fully close - if (this.tx_ === this.secondaryConn_ || - this.rx_ === this.secondaryConn_) { - this.close(); - } - } - else if (cmd === CONTROL_PONG) { - this.log_('got pong on secondary.'); - this.secondaryResponsesRequired_--; - this.upgradeIfSecondaryHealthy_(); - } - } - }; - Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) { - var layer = requireKey('t', parsedData); - var data = requireKey('d', parsedData); - if (layer == 'c') { - this.onSecondaryControl_(data); - } - else if (layer == 'd') { - // got a data message, but we're still second connection. Need to buffer it up - this.pendingDataMessages.push(data); - } - else { - throw new Error('Unknown protocol layer: ' + layer); - } - }; - Connection.prototype.upgradeIfSecondaryHealthy_ = function () { - if (this.secondaryResponsesRequired_ <= 0) { - this.log_('Secondary connection is healthy.'); - this.isHealthy_ = true; - this.secondaryConn_.markConnectionHealthy(); - this.proceedWithUpgrade_(); - } - else { - // Send a ping to make sure the connection is healthy. - this.log_('sending ping on secondary.'); - this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } }); - } - }; - Connection.prototype.proceedWithUpgrade_ = function () { - // tell this connection to consider itself open - this.secondaryConn_.start(); - // send ack - this.log_('sending client ack on secondary'); - this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } }); - // send end packet on primary transport, switch to sending on this one - // can receive on this one, buffer responses until end received on primary transport - this.log_('Ending transmission on primary'); - this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } }); - this.tx_ = this.secondaryConn_; - this.tryCleanupConnection(); - }; - Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) { - // Must refer to parsedData properties in quotes, so closure doesn't touch them. - var layer = requireKey('t', parsedData); - var data = requireKey('d', parsedData); - if (layer == 'c') { - this.onControl_(data); - } - else if (layer == 'd') { - this.onDataMessage_(data); - } - }; - Connection.prototype.onDataMessage_ = function (message) { - this.onPrimaryResponse_(); - // We don't do anything with data messages, just kick them up a level - this.onMessage_(message); - }; - Connection.prototype.onPrimaryResponse_ = function () { - if (!this.isHealthy_) { - this.primaryResponsesRequired_--; - if (this.primaryResponsesRequired_ <= 0) { - this.log_('Primary connection is healthy.'); - this.isHealthy_ = true; - this.conn_.markConnectionHealthy(); - } - } - }; - Connection.prototype.onControl_ = function (controlData) { - var cmd = requireKey(MESSAGE_TYPE, controlData); - if (MESSAGE_DATA in controlData) { - var payload = controlData[MESSAGE_DATA]; - if (cmd === SERVER_HELLO) { - this.onHandshake_(payload); - } - else if (cmd === END_TRANSMISSION) { - this.log_('recvd end transmission on primary'); - this.rx_ = this.secondaryConn_; - for (var i = 0; i < this.pendingDataMessages.length; ++i) { - this.onDataMessage_(this.pendingDataMessages[i]); - } - this.pendingDataMessages = []; - this.tryCleanupConnection(); - } - else if (cmd === CONTROL_SHUTDOWN) { - // This was previously the 'onKill' callback passed to the lower-level connection - // payload in this case is the reason for the shutdown. Generally a human-readable error - this.onConnectionShutdown_(payload); - } - else if (cmd === CONTROL_RESET) { - // payload in this case is the host we should contact - this.onReset_(payload); - } - else if (cmd === CONTROL_ERROR) { - error('Server Error: ' + payload); - } - else if (cmd === CONTROL_PONG) { - this.log_('got pong on primary.'); - this.onPrimaryResponse_(); - this.sendPingOnPrimaryIfNecessary_(); - } - else { - error('Unknown control packet command: ' + cmd); - } - } - }; - /** - * - * @param {Object} handshake The handshake data returned from the server - * @private - */ - Connection.prototype.onHandshake_ = function (handshake) { - var timestamp = handshake.ts; - var version = handshake.v; - var host = handshake.h; - this.sessionId = handshake.s; - this.repoInfo_.updateHost(host); - // if we've already closed the connection, then don't bother trying to progress further - if (this.state_ == 0 /* CONNECTING */) { - this.conn_.start(); - this.onConnectionEstablished_(this.conn_, timestamp); - if (PROTOCOL_VERSION !== version) { - warn('Protocol version mismatch detected'); - } - // TODO: do we want to upgrade? when? maybe a delay? - this.tryStartUpgrade_(); - } - }; - Connection.prototype.tryStartUpgrade_ = function () { - var conn = this.transportManager_.upgradeTransport(); - if (conn) { - this.startUpgrade_(conn); - } - }; - Connection.prototype.startUpgrade_ = function (conn) { - var _this = this; - this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId); - // For certain transports (WebSockets), we need to send and receive several messages back and forth before we - // can consider the transport healthy. - this.secondaryResponsesRequired_ = - conn['responsesRequiredToBeHealthy'] || 0; - var onMessage = this.connReceiver_(this.secondaryConn_); - var onDisconnect = this.disconnReceiver_(this.secondaryConn_); - this.secondaryConn_.open(onMessage, onDisconnect); - // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary. - setTimeoutNonBlocking(function () { - if (_this.secondaryConn_) { - _this.log_('Timed out trying to upgrade.'); - _this.secondaryConn_.close(); - } - }, Math.floor(UPGRADE_TIMEOUT)); - }; - Connection.prototype.onReset_ = function (host) { - this.log_('Reset packet received. New host: ' + host); - this.repoInfo_.updateHost(host); - // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up. - // We don't currently support resets after the connection has already been established - if (this.state_ === 1 /* CONNECTED */) { - this.close(); - } - else { - // Close whatever connections we have open and start again. - this.closeConnections_(); - this.start_(); - } - }; - Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) { - var _this = this; - this.log_('Realtime connection established.'); - this.conn_ = conn; - this.state_ = 1 /* CONNECTED */; - if (this.onReady_) { - this.onReady_(timestamp, this.sessionId); - this.onReady_ = null; - } - // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy, - // send some pings. - if (this.primaryResponsesRequired_ === 0) { - this.log_('Primary connection is healthy.'); - this.isHealthy_ = true; - } - else { - setTimeoutNonBlocking(function () { - _this.sendPingOnPrimaryIfNecessary_(); - }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); - } - }; - Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () { - // If the connection isn't considered healthy yet, we'll send a noop ping packet request. - if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) { - this.log_('sending ping on primary.'); - this.sendData_({ t: 'c', d: { t: PING, d: {} } }); - } - }; - Connection.prototype.onSecondaryConnectionLost_ = function () { - var conn = this.secondaryConn_; - this.secondaryConn_ = null; - if (this.tx_ === conn || this.rx_ === conn) { - // we are relying on this connection already in some capacity. Therefore, a failure is real - this.close(); - } - }; - /** - * - * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if - * we should flush the host cache - * @private - */ - Connection.prototype.onConnectionLost_ = function (everConnected) { - this.conn_ = null; - // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting - // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess. - if (!everConnected && this.state_ === 0 /* CONNECTING */) { - this.log_('Realtime connection failed.'); - // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away - if (this.repoInfo_.isCacheableHost()) { - PersistentStorage.remove('host:' + this.repoInfo_.host); - // reset the internal host to what we would show the user, i.e. .firebaseio.com - this.repoInfo_.internalHost = this.repoInfo_.host; - } - } - else if (this.state_ === 1 /* CONNECTED */) { - this.log_('Realtime connection lost.'); - } - this.close(); - }; - /** - * - * @param {string} reason - * @private - */ - Connection.prototype.onConnectionShutdown_ = function (reason) { - this.log_('Connection shutdown command received. Shutting down...'); - if (this.onKill_) { - this.onKill_(reason); - this.onKill_ = null; - } - // We intentionally don't want to fire onDisconnect (kill is a different case), - // so clear the callback. - this.onDisconnect_ = null; - this.close(); - }; - Connection.prototype.sendData_ = function (data) { - if (this.state_ !== 1 /* CONNECTED */) { - throw 'Connection is not connected'; - } - else { - this.tx_.send(data); - } - }; - /** - * Cleans up this connection, calling the appropriate callbacks - */ - Connection.prototype.close = function () { - if (this.state_ !== 2 /* DISCONNECTED */) { - this.log_('Closing realtime connection.'); - this.state_ = 2 /* DISCONNECTED */; - this.closeConnections_(); - if (this.onDisconnect_) { - this.onDisconnect_(); - this.onDisconnect_ = null; - } - } - }; - /** - * - * @private - */ - Connection.prototype.closeConnections_ = function () { - this.log_('Shutting down all connections'); - if (this.conn_) { - this.conn_.close(); - this.conn_ = null; - } - if (this.secondaryConn_) { - this.secondaryConn_.close(); - this.secondaryConn_ = null; - } - if (this.healthyTimeout_) { - clearTimeout(this.healthyTimeout_); - this.healthyTimeout_ = null; - } - }; - return Connection; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Interface defining the set of actions that can be performed against the Firebase server - * (basically corresponds to our wire protocol). - * - * @interface - */ -var ServerActions = /** @class */ (function () { - function ServerActions() { - } - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - * @param {string=} hash - */ - ServerActions.prototype.put = function (pathString, data, onComplete, hash) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, ?string)} onComplete - * @param {string=} hash - */ - ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { }; - /** - * Refreshes the auth token for the current connection. - * @param {string} token The authentication token - */ - ServerActions.prototype.refreshAuthToken = function (token) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { }; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { }; - /** - * @param {string} pathString - * @param {function(string, string)=} onComplete - */ - ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { }; - /** - * @param {Object.} stats - */ - ServerActions.prototype.reportStats = function (stats) { }; - return ServerActions; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var RECONNECT_MIN_DELAY = 1000; -var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858) -var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server) -var RECONNECT_DELAY_MULTIPLIER = 1.3; -var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec. -var SERVER_KILL_INTERRUPT_REASON = 'server_kill'; -// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off. -var INVALID_AUTH_TOKEN_THRESHOLD = 3; -/** - * Firebase connection. Abstracts wire protocol and handles reconnecting. - * - * NOTE: All JSON objects sent to the realtime connection must have property names enclosed - * in quotes to make sure the closure compiler does not minify them. - */ -var PersistentConnection = /** @class */ (function (_super) { - tslib_1.__extends(PersistentConnection, _super); - /** - * @implements {ServerActions} - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param onConnectStatus_ - * @param onServerInfoUpdate_ - * @param authTokenProvider_ - * @param authOverride_ - */ - function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) { - var _this = _super.call(this) || this; - _this.repoInfo_ = repoInfo_; - _this.onDataUpdate_ = onDataUpdate_; - _this.onConnectStatus_ = onConnectStatus_; - _this.onServerInfoUpdate_ = onServerInfoUpdate_; - _this.authTokenProvider_ = authTokenProvider_; - _this.authOverride_ = authOverride_; - // Used for diagnostic logging. - _this.id = PersistentConnection.nextPersistentConnectionId_++; - _this.log_ = logWrapper('p:' + _this.id + ':'); - /** @private {Object} */ - _this.interruptReasons_ = {}; - _this.listens_ = {}; - _this.outstandingPuts_ = []; - _this.outstandingPutCount_ = 0; - _this.onDisconnectRequestQueue_ = []; - _this.connected_ = false; - _this.reconnectDelay_ = RECONNECT_MIN_DELAY; - _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; - _this.securityDebugCallback_ = null; - _this.lastSessionId = null; - /** @private {number|null} */ - _this.establishConnectionTimer_ = null; - /** @private {boolean} */ - _this.visible_ = false; - // Before we get connected, we keep a queue of pending messages to send. - _this.requestCBHash_ = {}; - _this.requestNumber_ = 0; - /** @private {?{ - * sendRequest(Object), - * close() - * }} */ - _this.realtime_ = null; - /** @private {string|null} */ - _this.authToken_ = null; - _this.forceTokenRefresh_ = false; - _this.invalidAuthTokenCount_ = 0; - _this.firstConnection_ = true; - _this.lastConnectionAttemptTime_ = null; - _this.lastConnectionEstablishedTime_ = null; - if (authOverride_ && !util.isNodeSdk()) { - throw new Error('Auth override specified in options, but not supported on non Node.js platforms'); - } - _this.scheduleConnect_(0); - VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this); - if (repoInfo_.host.indexOf('fblocal') === -1) { - OnlineMonitor.getInstance().on('online', _this.onOnline_, _this); - } - return _this; - } - /** - * @param {!string} action - * @param {*} body - * @param {function(*)=} onResponse - * @protected - */ - PersistentConnection.prototype.sendRequest = function (action, body, onResponse) { - var curReqNum = ++this.requestNumber_; - var msg = { r: curReqNum, a: action, b: body }; - this.log_(util.stringify(msg)); - util.assert(this.connected_, "sendRequest call when we're not connected not allowed."); - this.realtime_.sendRequest(msg); - if (onResponse) { - this.requestCBHash_[curReqNum] = onResponse; - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) { - var queryId = query.queryIdentifier(); - var pathString = query.path.toString(); - this.log_('Listen called for ' + pathString + ' ' + queryId); - this.listens_[pathString] = this.listens_[pathString] || {}; - util.assert(query.getQueryParams().isDefault() || - !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query'); - util.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.'); - var listenSpec = { - onComplete: onComplete, - hashFn: currentHashFn, - query: query, - tag: tag - }; - this.listens_[pathString][queryId] = listenSpec; - if (this.connected_) { - this.sendListen_(listenSpec); - } - }; - /** - * @param {!{onComplete(), - * hashFn():!string, - * query: !Query, - * tag: ?number}} listenSpec - * @private - */ - PersistentConnection.prototype.sendListen_ = function (listenSpec) { - var _this = this; - var query = listenSpec.query; - var pathString = query.path.toString(); - var queryId = query.queryIdentifier(); - this.log_('Listen on ' + pathString + ' for ' + queryId); - var req = { /*path*/ p: pathString }; - var action = 'q'; - // Only bother to send query if it's non-default. - if (listenSpec.tag) { - req['q'] = query.queryObject(); - req['t'] = listenSpec.tag; - } - req[ /*hash*/'h'] = listenSpec.hashFn(); - this.sendRequest(action, req, function (message) { - var payload = message[ /*data*/'d']; - var status = message[ /*status*/'s']; - // print warnings in any case... - PersistentConnection.warnOnListenWarnings_(payload, query); - var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId]; - // only trigger actions if the listen hasn't been removed and readded - if (currentListenSpec === listenSpec) { - _this.log_('listen response', message); - if (status !== 'ok') { - _this.removeListen_(pathString, queryId); - } - if (listenSpec.onComplete) { - listenSpec.onComplete(status, payload); - } - } - }); - }; - /** - * @param {*} payload - * @param {!Query} query - * @private - */ - PersistentConnection.warnOnListenWarnings_ = function (payload, query) { - if (payload && typeof payload === 'object' && util.contains(payload, 'w')) { - var warnings = util.safeGet(payload, 'w'); - if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) { - var indexSpec = '".indexOn": "' + - query - .getQueryParams() - .getIndex() - .toString() + - '"'; - var indexPath = query.path.toString(); - warn("Using an unspecified index. Your data will be downloaded and " + - ("filtered on the client. Consider adding " + indexSpec + " at ") + - (indexPath + " to your security rules for better performance.")); - } - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.refreshAuthToken = function (token) { - this.authToken_ = token; - this.log_('Auth token refreshed'); - if (this.authToken_) { - this.tryAuth(); - } - else { - //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete - //the credential so we dont become authenticated next time we connect. - if (this.connected_) { - this.sendRequest('unauth', {}, function () { }); - } - } - this.reduceReconnectDelayIfAdminCredential_(token); - }; - /** - * @param {!string} credential - * @private - */ - PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) { - // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client). - // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires. - var isFirebaseSecret = credential && credential.length === 40; - if (isFirebaseSecret || util.isAdmin(credential)) { - this.log_('Admin auth credential detected. Reducing max reconnect time.'); - this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; - } - }; - /** - * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like - * a auth revoked (the connection is closed). - */ - PersistentConnection.prototype.tryAuth = function () { - var _this = this; - if (this.connected_ && this.authToken_) { - var token_1 = this.authToken_; - var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth'; - var requestData = { cred: token_1 }; - if (this.authOverride_ === null) { - requestData['noauth'] = true; - } - else if (typeof this.authOverride_ === 'object') { - requestData['authvar'] = this.authOverride_; - } - this.sendRequest(authMethod, requestData, function (res) { - var status = res[ /*status*/'s']; - var data = res[ /*data*/'d'] || 'error'; - if (_this.authToken_ === token_1) { - if (status === 'ok') { - _this.invalidAuthTokenCount_ = 0; - } - else { - // Triggers reconnect and force refresh for auth token - _this.onAuthRevoked_(status, data); - } - } - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.unlisten = function (query, tag) { - var pathString = query.path.toString(); - var queryId = query.queryIdentifier(); - this.log_('Unlisten called for ' + pathString + ' ' + queryId); - util.assert(query.getQueryParams().isDefault() || - !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query'); - var listen = this.removeListen_(pathString, queryId); - if (listen && this.connected_) { - this.sendUnlisten_(pathString, queryId, query.queryObject(), tag); - } - }; - PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) { - this.log_('Unlisten on ' + pathString + ' for ' + queryId); - var req = { /*path*/ p: pathString }; - var action = 'n'; - // Only bother sending queryId if it's non-default. - if (tag) { - req['q'] = queryObj; - req['t'] = tag; - } - this.sendRequest(action, req); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('o', pathString, data, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'o', - data: data, - onComplete: onComplete - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('om', pathString, data, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'om', - data: data, - onComplete: onComplete - }); - } - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) { - if (this.connected_) { - this.sendOnDisconnect_('oc', pathString, null, onComplete); - } - else { - this.onDisconnectRequestQueue_.push({ - pathString: pathString, - action: 'oc', - data: null, - onComplete: onComplete - }); - } - }; - PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) { - var request = { /*path*/ p: pathString, /*data*/ d: data }; - this.log_('onDisconnect ' + action, request); - this.sendRequest(action, request, function (response) { - if (onComplete) { - setTimeout(function () { - onComplete(response[ /*status*/'s'], response[ /* data */'d']); - }, Math.floor(0)); - } - }); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) { - this.putInternal('p', pathString, data, onComplete, hash); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) { - this.putInternal('m', pathString, data, onComplete, hash); - }; - PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) { - var request = { - /*path*/ p: pathString, - /*data*/ d: data - }; - if (hash !== undefined) - request[ /*hash*/'h'] = hash; - // TODO: Only keep track of the most recent put for a given path? - this.outstandingPuts_.push({ - action: action, - request: request, - onComplete: onComplete - }); - this.outstandingPutCount_++; - var index = this.outstandingPuts_.length - 1; - if (this.connected_) { - this.sendPut_(index); - } - else { - this.log_('Buffering put: ' + pathString); - } - }; - PersistentConnection.prototype.sendPut_ = function (index) { - var _this = this; - var action = this.outstandingPuts_[index].action; - var request = this.outstandingPuts_[index].request; - var onComplete = this.outstandingPuts_[index].onComplete; - this.outstandingPuts_[index].queued = this.connected_; - this.sendRequest(action, request, function (message) { - _this.log_(action + ' response', message); - delete _this.outstandingPuts_[index]; - _this.outstandingPutCount_--; - // Clean up array occasionally. - if (_this.outstandingPutCount_ === 0) { - _this.outstandingPuts_ = []; - } - if (onComplete) - onComplete(message[ /*status*/'s'], message[ /* data */'d']); - }); - }; - /** - * @inheritDoc - */ - PersistentConnection.prototype.reportStats = function (stats) { - var _this = this; - // If we're not connected, we just drop the stats. - if (this.connected_) { - var request = { /*counters*/ c: stats }; - this.log_('reportStats', request); - this.sendRequest(/*stats*/ 's', request, function (result) { - var status = result[ /*status*/'s']; - if (status !== 'ok') { - var errorReason = result[ /* data */'d']; - _this.log_('reportStats', 'Error sending stats: ' + errorReason); - } - }); - } - }; - /** - * @param {*} message - * @private - */ - PersistentConnection.prototype.onDataMessage_ = function (message) { - if ('r' in message) { - // this is a response - this.log_('from server: ' + util.stringify(message)); - var reqNum = message['r']; - var onResponse = this.requestCBHash_[reqNum]; - if (onResponse) { - delete this.requestCBHash_[reqNum]; - onResponse(message[ /*body*/'b']); - } - } - else if ('error' in message) { - throw 'A server-side error has occurred: ' + message['error']; - } - else if ('a' in message) { - // a and b are action and body, respectively - this.onDataPush_(message['a'], message['b']); - } - }; - PersistentConnection.prototype.onDataPush_ = function (action, body) { - this.log_('handleServerMessage', action, body); - if (action === 'd') - this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], - /*isMerge*/ false, body['t']); - else if (action === 'm') - this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], - /*isMerge=*/ true, body['t']); - else if (action === 'c') - this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']); - else if (action === 'ac') - this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']); - else if (action === 'sd') - this.onSecurityDebugPacket_(body); - else - error('Unrecognized action received from server: ' + - util.stringify(action) + - '\nAre you using the latest client?'); - }; - PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) { - this.log_('connection ready'); - this.connected_ = true; - this.lastConnectionEstablishedTime_ = new Date().getTime(); - this.handleTimestamp_(timestamp); - this.lastSessionId = sessionId; - if (this.firstConnection_) { - this.sendConnectStats_(); - } - this.restoreState_(); - this.firstConnection_ = false; - this.onConnectStatus_(true); - }; - PersistentConnection.prototype.scheduleConnect_ = function (timeout) { - var _this = this; - util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); - if (this.establishConnectionTimer_) { - clearTimeout(this.establishConnectionTimer_); - } - // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in - // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests). - this.establishConnectionTimer_ = setTimeout(function () { - _this.establishConnectionTimer_ = null; - _this.establishConnection_(); - }, Math.floor(timeout)); - }; - /** - * @param {boolean} visible - * @private - */ - PersistentConnection.prototype.onVisible_ = function (visible) { - // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine. - if (visible && - !this.visible_ && - this.reconnectDelay_ === this.maxReconnectDelay_) { - this.log_('Window became visible. Reducing delay.'); - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - this.visible_ = visible; - }; - PersistentConnection.prototype.onOnline_ = function (online) { - if (online) { - this.log_('Browser went online.'); - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - else { - this.log_('Browser went offline. Killing connection.'); - if (this.realtime_) { - this.realtime_.close(); - } - } - }; - PersistentConnection.prototype.onRealtimeDisconnect_ = function () { - this.log_('data client disconnected'); - this.connected_ = false; - this.realtime_ = null; - // Since we don't know if our sent transactions succeeded or not, we need to cancel them. - this.cancelSentTransactions_(); - // Clear out the pending requests. - this.requestCBHash_ = {}; - if (this.shouldReconnect_()) { - if (!this.visible_) { - this.log_("Window isn't visible. Delaying reconnect."); - this.reconnectDelay_ = this.maxReconnectDelay_; - this.lastConnectionAttemptTime_ = new Date().getTime(); - } - else if (this.lastConnectionEstablishedTime_) { - // If we've been connected long enough, reset reconnect delay to minimum. - var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_; - if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - this.lastConnectionEstablishedTime_ = null; - } - var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_; - var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt); - reconnectDelay = Math.random() * reconnectDelay; - this.log_('Trying to reconnect in ' + reconnectDelay + 'ms'); - this.scheduleConnect_(reconnectDelay); - // Adjust reconnect delay for next time. - this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER); - } - this.onConnectStatus_(false); - }; - PersistentConnection.prototype.establishConnection_ = function () { - if (this.shouldReconnect_()) { - this.log_('Making a connection attempt'); - this.lastConnectionAttemptTime_ = new Date().getTime(); - this.lastConnectionEstablishedTime_ = null; - var onDataMessage_1 = this.onDataMessage_.bind(this); - var onReady_1 = this.onReady_.bind(this); - var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this); - var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++; - var self_1 = this; - var lastSessionId_1 = this.lastSessionId; - var canceled_1 = false; - var connection_1 = null; - var closeFn_1 = function () { - if (connection_1) { - connection_1.close(); - } - else { - canceled_1 = true; - onDisconnect_1(); - } - }; - var sendRequestFn = function (msg) { - util.assert(connection_1, "sendRequest call when we're not connected not allowed."); - connection_1.sendRequest(msg); - }; - this.realtime_ = { - close: closeFn_1, - sendRequest: sendRequestFn - }; - var forceRefresh = this.forceTokenRefresh_; - this.forceTokenRefresh_ = false; - // First fetch auth token, and establish connection after fetching the token was successful - this.authTokenProvider_ - .getToken(forceRefresh) - .then(function (result) { - if (!canceled_1) { - log('getToken() completed. Creating connection.'); - self_1.authToken_ = result && result.accessToken; - connection_1 = new Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, - /* onKill= */ function (reason) { - warn(reason + ' (' + self_1.repoInfo_.toString() + ')'); - self_1.interrupt(SERVER_KILL_INTERRUPT_REASON); - }, lastSessionId_1); - } - else { - log('getToken() completed but was canceled'); - } - }) - .then(null, function (error$$1) { - self_1.log_('Failed to get token: ' + error$$1); - if (!canceled_1) { - if (util.CONSTANTS.NODE_ADMIN) { - // This may be a critical error for the Admin Node.js SDK, so log a warning. - // But getToken() may also just have temporarily failed, so we still want to - // continue retrying. - warn(error$$1); - } - closeFn_1(); - } - }); - } - }; - /** - * @param {string} reason - */ - PersistentConnection.prototype.interrupt = function (reason) { - log('Interrupting connection for reason: ' + reason); - this.interruptReasons_[reason] = true; - if (this.realtime_) { - this.realtime_.close(); - } - else { - if (this.establishConnectionTimer_) { - clearTimeout(this.establishConnectionTimer_); - this.establishConnectionTimer_ = null; - } - if (this.connected_) { - this.onRealtimeDisconnect_(); - } - } - }; - /** - * @param {string} reason - */ - PersistentConnection.prototype.resume = function (reason) { - log('Resuming connection for reason: ' + reason); - delete this.interruptReasons_[reason]; - if (util.isEmpty(this.interruptReasons_)) { - this.reconnectDelay_ = RECONNECT_MIN_DELAY; - if (!this.realtime_) { - this.scheduleConnect_(0); - } - } - }; - PersistentConnection.prototype.handleTimestamp_ = function (timestamp) { - var delta = timestamp - new Date().getTime(); - this.onServerInfoUpdate_({ serverTimeOffset: delta }); - }; - PersistentConnection.prototype.cancelSentTransactions_ = function () { - for (var i = 0; i < this.outstandingPuts_.length; i++) { - var put = this.outstandingPuts_[i]; - if (put && /*hash*/ 'h' in put.request && put.queued) { - if (put.onComplete) - put.onComplete('disconnect'); - delete this.outstandingPuts_[i]; - this.outstandingPutCount_--; - } - } - // Clean up array occasionally. - if (this.outstandingPutCount_ === 0) - this.outstandingPuts_ = []; - }; - /** - * @param {!string} pathString - * @param {Array.<*>=} query - * @private - */ - PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) { - // Remove the listen and manufacture a "permission_denied" error for the failed listen. - var queryId; - if (!query) { - queryId = 'default'; - } - else { - queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$'); - } - var listen = this.removeListen_(pathString, queryId); - if (listen && listen.onComplete) - listen.onComplete('permission_denied'); - }; - /** - * @param {!string} pathString - * @param {!string} queryId - * @return {{queries:Array., onComplete:function(string)}} - * @private - */ - PersistentConnection.prototype.removeListen_ = function (pathString, queryId) { - var normalizedPathString = new Path(pathString).toString(); // normalize path. - var listen; - if (this.listens_[normalizedPathString] !== undefined) { - listen = this.listens_[normalizedPathString][queryId]; - delete this.listens_[normalizedPathString][queryId]; - if (util.getCount(this.listens_[normalizedPathString]) === 0) { - delete this.listens_[normalizedPathString]; - } - } - else { - // all listens for this path has already been removed - listen = undefined; - } - return listen; - }; - PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) { - log('Auth token revoked: ' + statusCode + '/' + explanation); - this.authToken_ = null; - this.forceTokenRefresh_ = true; - this.realtime_.close(); - if (statusCode === 'invalid_token' || statusCode === 'permission_denied') { - // We'll wait a couple times before logging the warning / increasing the - // retry period since oauth tokens will report as "invalid" if they're - // just expired. Plus there may be transient issues that resolve themselves. - this.invalidAuthTokenCount_++; - if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) { - // Set a long reconnect delay because recovery is unlikely - this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; - // Notify the auth token provider that the token is invalid, which will log - // a warning - this.authTokenProvider_.notifyForInvalidToken(); - } - } - }; - PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) { - if (this.securityDebugCallback_) { - this.securityDebugCallback_(body); - } - else { - if ('msg' in body) { - console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: ')); - } - } - }; - PersistentConnection.prototype.restoreState_ = function () { - var _this = this; - //Re-authenticate ourselves if we have a credential stored. - this.tryAuth(); - // Puts depend on having received the corresponding data update from the server before they complete, so we must - // make sure to send listens before puts. - util.forEach(this.listens_, function (pathString, queries) { - util.forEach(queries, function (key, listenSpec) { - _this.sendListen_(listenSpec); - }); - }); - for (var i = 0; i < this.outstandingPuts_.length; i++) { - if (this.outstandingPuts_[i]) - this.sendPut_(i); - } - while (this.onDisconnectRequestQueue_.length) { - var request = this.onDisconnectRequestQueue_.shift(); - this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete); - } - }; - /** - * Sends client stats for first connection - * @private - */ - PersistentConnection.prototype.sendConnectStats_ = function () { - var stats = {}; - var clientName = 'js'; - if (util.CONSTANTS.NODE_ADMIN) { - clientName = 'admin_node'; - } - else if (util.CONSTANTS.NODE_CLIENT) { - clientName = 'node'; - } - stats['sdk.' + clientName + '.' + firebase.SDK_VERSION.replace(/\./g, '-')] = 1; - if (util.isMobileCordova()) { - stats['framework.cordova'] = 1; - } - else if (util.isReactNative()) { - stats['framework.reactnative'] = 1; - } - this.reportStats(stats); - }; - /** - * @return {boolean} - * @private - */ - PersistentConnection.prototype.shouldReconnect_ = function () { - var online = OnlineMonitor.getInstance().currentlyOnline(); - return util.isEmpty(this.interruptReasons_) && online; - }; - /** - * @private - */ - PersistentConnection.nextPersistentConnectionId_ = 0; - /** - * Counter for number of connections created. Mainly used for tagging in the logs - * @type {number} - * @private - */ - PersistentConnection.nextConnectionId_ = 0; - return PersistentConnection; -}(ServerActions)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * An implementation of ServerActions that communicates with the server via REST requests. - * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full - * persistent connection (using WebSockets or long-polling) - */ -var ReadonlyRestClient = /** @class */ (function (_super) { - tslib_1.__extends(ReadonlyRestClient, _super); - /** - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param {AuthTokenProvider} authTokenProvider_ - * @implements {ServerActions} - */ - function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) { - var _this = _super.call(this) || this; - _this.repoInfo_ = repoInfo_; - _this.onDataUpdate_ = onDataUpdate_; - _this.authTokenProvider_ = authTokenProvider_; - /** @private {function(...[*])} */ - _this.log_ = logWrapper('p:rest:'); - /** - * We don't actually need to track listens, except to prevent us calling an onComplete for a listen - * that's been removed. :-/ - * - * @private {!Object.} - */ - _this.listens_ = {}; - return _this; - } - ReadonlyRestClient.prototype.reportStats = function (stats) { - throw new Error('Method not implemented.'); - }; - /** - * @param {!Query} query - * @param {?number=} tag - * @return {string} - * @private - */ - ReadonlyRestClient.getListenId_ = function (query, tag) { - if (tag !== undefined) { - return 'tag$' + tag; - } - else { - util.assert(query.getQueryParams().isDefault(), "should have a tag if it's not a default query."); - return query.path.toString(); - } - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) { - var _this = this; - var pathString = query.path.toString(); - this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier()); - // Mark this listener so we can tell if it's removed. - var listenId = ReadonlyRestClient.getListenId_(query, tag); - var thisListen = {}; - this.listens_[listenId] = thisListen; - var queryStringParameters = query - .getQueryParams() - .toRestQueryStringParameters(); - this.restRequest_(pathString + '.json', queryStringParameters, function (error$$1, result) { - var data = result; - if (error$$1 === 404) { - data = null; - error$$1 = null; - } - if (error$$1 === null) { - _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag); - } - if (util.safeGet(_this.listens_, listenId) === thisListen) { - var status_1; - if (!error$$1) { - status_1 = 'ok'; - } - else if (error$$1 == 401) { - status_1 = 'permission_denied'; - } - else { - status_1 = 'rest_error:' + error$$1; - } - onComplete(status_1, null); - } - }); - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.unlisten = function (query, tag) { - var listenId = ReadonlyRestClient.getListenId_(query, tag); - delete this.listens_[listenId]; - }; - /** @inheritDoc */ - ReadonlyRestClient.prototype.refreshAuthToken = function (token) { - // no-op since we just always call getToken. - }; - /** - * Performs a REST request to the given path, with the provided query string parameters, - * and any auth credentials we have. - * - * @param {!string} pathString - * @param {!Object.} queryStringParameters - * @param {?function(?number, *=)} callback - * @private - */ - ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) { - var _this = this; - if (queryStringParameters === void 0) { queryStringParameters = {}; } - queryStringParameters['format'] = 'export'; - this.authTokenProvider_ - .getToken(/*forceRefresh=*/ false) - .then(function (authTokenData) { - var authToken = authTokenData && authTokenData.accessToken; - if (authToken) { - queryStringParameters['auth'] = authToken; - } - var url = (_this.repoInfo_.secure ? 'https://' : 'http://') + - _this.repoInfo_.host + - pathString + - '?' + - 'ns=' + - _this.repoInfo_.namespace + - util.querystring(queryStringParameters); - _this.log_('Sending REST request for ' + url); - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function () { - if (callback && xhr.readyState === 4) { - _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText); - var res = null; - if (xhr.status >= 200 && xhr.status < 300) { - try { - res = util.jsonEval(xhr.responseText); - } - catch (e) { - warn('Failed to parse JSON response for ' + - url + - ': ' + - xhr.responseText); - } - callback(null, res); - } - else { - // 401 and 404 are expected. - if (xhr.status !== 401 && xhr.status !== 404) { - warn('Got unsuccessful REST response for ' + - url + - ' Status: ' + - xhr.status); - } - callback(xhr.status); - } - callback = null; - } - }; - xhr.open('GET', url, /*asynchronous=*/ true); - xhr.send(); - }); - }; - return ReadonlyRestClient; -}(ServerActions)); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var INTERRUPT_REASON = 'repo_interrupt'; -/** - * A connection to a single data repository. - */ -var Repo = /** @class */ (function () { - /** - * @param {!RepoInfo} repoInfo_ - * @param {boolean} forceRestClient - * @param {!FirebaseApp} app - */ - function Repo(repoInfo_, forceRestClient, app) { - var _this = this; - this.repoInfo_ = repoInfo_; - this.app = app; - this.dataUpdateCount = 0; - this.statsListener_ = null; - this.eventQueue_ = new EventQueue(); - this.nextWriteId_ = 1; - this.interceptServerDataCallback_ = null; - // A list of data pieces and paths to be set when this client disconnects. - this.onDisconnect_ = new SparseSnapshotTree(); - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @type {?PersistentConnection} - */ - this.persistentConnection_ = null; - /** @type {!AuthTokenProvider} */ - var authTokenProvider = new AuthTokenProvider(app); - this.stats_ = StatsManager.getCollection(repoInfo_); - if (forceRestClient || beingCrawled()) { - this.server_ = new ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider); - // Minor hack: Fire onConnect immediately, since there's no actual connection. - setTimeout(this.onConnectStatus_.bind(this, true), 0); - } - else { - var authOverride = app.options['databaseAuthVariableOverride']; - // Validate authOverride - if (typeof authOverride !== 'undefined' && authOverride !== null) { - if (typeof authOverride !== 'object') { - throw new Error('Only objects are supported for option databaseAuthVariableOverride'); - } - try { - util.stringify(authOverride); - } - catch (e) { - throw new Error('Invalid authOverride provided: ' + e); - } - } - this.persistentConnection_ = new PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride); - this.server_ = this.persistentConnection_; - } - authTokenProvider.addTokenChangeListener(function (token) { - _this.server_.refreshAuthToken(token); - }); - // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used), - // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created. - this.statsReporter_ = StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter(_this.stats_, _this.server_); }); - this.transactions_init_(); - // Used for .info. - this.infoData_ = new SnapshotHolder(); - this.infoSyncTree_ = new SyncTree({ - startListening: function (query, tag, currentHashFn, onComplete) { - var infoEvents = []; - var node = _this.infoData_.getNode(query.path); - // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events - // on initial data... - if (!node.isEmpty()) { - infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node); - setTimeout(function () { - onComplete('ok'); - }, 0); - } - return infoEvents; - }, - stopListening: function () { } - }); - this.updateInfo_('connected', false); - this.serverSyncTree_ = new SyncTree({ - startListening: function (query, tag, currentHashFn, onComplete) { - _this.server_.listen(query, currentHashFn, tag, function (status, data) { - var events = onComplete(status, data); - _this.eventQueue_.raiseEventsForChangedPath(query.path, events); - }); - // No synchronous events for network-backed sync trees - return []; - }, - stopListening: function (query, tag) { - _this.server_.unlisten(query, tag); - } - }); - } - /** - * @return {string} The URL corresponding to the root of this Firebase. - */ - Repo.prototype.toString = function () { - return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host); - }; - /** - * @return {!string} The namespace represented by the repo. - */ - Repo.prototype.name = function () { - return this.repoInfo_.namespace; - }; - /** - * @return {!number} The time in milliseconds, taking the server offset into account if we have one. - */ - Repo.prototype.serverTime = function () { - var offsetNode = this.infoData_.getNode(new Path('.info/serverTimeOffset')); - var offset = offsetNode.val() || 0; - return new Date().getTime() + offset; - }; - /** - * Generate ServerValues using some variables from the repo object. - * @return {!Object} - */ - Repo.prototype.generateServerValues = function () { - return generateWithValues({ - timestamp: this.serverTime() - }); - }; - /** - * Called by realtime when we get new messages from the server. - * - * @private - * @param {string} pathString - * @param {*} data - * @param {boolean} isMerge - * @param {?number} tag - */ - Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) { - // For testing. - this.dataUpdateCount++; - var path = new Path(pathString); - data = this.interceptServerDataCallback_ - ? this.interceptServerDataCallback_(pathString, data) - : data; - var events = []; - if (tag) { - if (isMerge) { - var taggedChildren = util.map(data, function (raw) { - return nodeFromJSON$1(raw); - }); - events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag); - } - else { - var taggedSnap = nodeFromJSON$1(data); - events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag); - } - } - else if (isMerge) { - var changedChildren = util.map(data, function (raw) { - return nodeFromJSON$1(raw); - }); - events = this.serverSyncTree_.applyServerMerge(path, changedChildren); - } - else { - var snap = nodeFromJSON$1(data); - events = this.serverSyncTree_.applyServerOverwrite(path, snap); - } - var affectedPath = path; - if (events.length > 0) { - // Since we have a listener outstanding for each transaction, receiving any events - // is a proxy for some change having occurred. - affectedPath = this.rerunTransactions_(path); - } - this.eventQueue_.raiseEventsForChangedPath(affectedPath, events); - }; - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @param {?function(!string, *):*} callback - * @private - */ - Repo.prototype.interceptServerData_ = function (callback) { - this.interceptServerDataCallback_ = callback; - }; - /** - * @param {!boolean} connectStatus - * @private - */ - Repo.prototype.onConnectStatus_ = function (connectStatus) { - this.updateInfo_('connected', connectStatus); - if (connectStatus === false) { - this.runOnDisconnectEvents_(); - } - }; - /** - * @param {!Object} updates - * @private - */ - Repo.prototype.onServerInfoUpdate_ = function (updates) { - var _this = this; - each(updates, function (value, key) { - _this.updateInfo_(key, value); - }); - }; - /** - * - * @param {!string} pathString - * @param {*} value - * @private - */ - Repo.prototype.updateInfo_ = function (pathString, value) { - var path = new Path('/.info/' + pathString); - var newNode = nodeFromJSON$1(value); - this.infoData_.updateSnapshot(path, newNode); - var events = this.infoSyncTree_.applyServerOverwrite(path, newNode); - this.eventQueue_.raiseEventsForChangedPath(path, events); - }; - /** - * @return {!number} - * @private - */ - Repo.prototype.getNextWriteId_ = function () { - return this.nextWriteId_++; - }; - /** - * @param {!Path} path - * @param {*} newVal - * @param {number|string|null} newPriority - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) { - var _this = this; - this.log_('set', { - path: path.toString(), - value: newVal, - priority: newPriority - }); - // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or - // (b) store unresolved paths on JSON parse - var serverValues = this.generateServerValues(); - var newNodeUnresolved = nodeFromJSON$1(newVal, newPriority); - var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - var writeId = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true); - this.eventQueue_.queueEvents(events); - this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) { - var success = status === 'ok'; - if (!success) { - warn('set at ' + path + ' failed: ' + status); - } - var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success); - _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents); - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - var affectedPath = this.abortTransactions_(path); - this.rerunTransactions_(affectedPath); - // We queued the events above, so just flush the queue here - this.eventQueue_.raiseEventsForChangedPath(affectedPath, []); - }; - /** - * @param {!Path} path - * @param {!Object} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.update = function (path, childrenToMerge, onComplete) { - var _this = this; - this.log_('update', { path: path.toString(), value: childrenToMerge }); - // Start with our existing data and merge each child into it. - var empty = true; - var serverValues = this.generateServerValues(); - var changedChildren = {}; - util.forEach(childrenToMerge, function (changedKey, changedValue) { - empty = false; - var newNodeUnresolved = nodeFromJSON$1(changedValue); - changedChildren[changedKey] = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - }); - if (!empty) { - var writeId_1 = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1); - this.eventQueue_.queueEvents(events); - this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) { - var success = status === 'ok'; - if (!success) { - warn('update at ' + path + ' failed: ' + status); - } - var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success); - var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path; - _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents); - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - util.forEach(childrenToMerge, function (changedPath) { - var affectedPath = _this.abortTransactions_(path.child(changedPath)); - _this.rerunTransactions_(affectedPath); - }); - // We queued the events above, so just flush the queue here - this.eventQueue_.raiseEventsForChangedPath(path, []); - } - else { - log("update() called with empty data. Don't do anything."); - this.callOnCompleteCallback(onComplete, 'ok'); - } - }; - /** - * Applies all of the changes stored up in the onDisconnect_ tree. - * @private - */ - Repo.prototype.runOnDisconnectEvents_ = function () { - var _this = this; - this.log_('onDisconnectEvents'); - var serverValues = this.generateServerValues(); - var resolvedOnDisconnectTree = resolveDeferredValueTree(this.onDisconnect_, serverValues); - var events = []; - resolvedOnDisconnectTree.forEachTree(Path.Empty, function (path, snap) { - events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap)); - var affectedPath = _this.abortTransactions_(path); - _this.rerunTransactions_(affectedPath); - }); - this.onDisconnect_ = new SparseSnapshotTree(); - this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events); - }; - /** - * @param {!Path} path - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectCancel = function (path, onComplete) { - var _this = this; - this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.forget(path); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} value - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectSet = function (path, value, onComplete) { - var _this = this; - var newNode = nodeFromJSON$1(value); - this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.remember(path, newNode); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} value - * @param {*} priority - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) { - var _this = this; - var newNode = nodeFromJSON$1(value, priority); - this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) { - if (status === 'ok') { - _this.onDisconnect_.remember(path, newNode); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Path} path - * @param {*} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) { - var _this = this; - if (util.isEmpty(childrenToMerge)) { - log("onDisconnect().update() called with empty data. Don't do anything."); - this.callOnCompleteCallback(onComplete, 'ok'); - return; - } - this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) { - if (status === 'ok') { - util.forEach(childrenToMerge, function (childName, childNode) { - var newChildNode = nodeFromJSON$1(childNode); - _this.onDisconnect_.remember(path.child(childName), newChildNode); - }); - } - _this.callOnCompleteCallback(onComplete, status, errorReason); - }); - }; - /** - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - */ - Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) { - var events; - if (query.path.getFront() === '.info') { - events = this.infoSyncTree_.addEventRegistration(query, eventRegistration); - } - else { - events = this.serverSyncTree_.addEventRegistration(query, eventRegistration); - } - this.eventQueue_.raiseEventsAtPath(query.path, events); - }; - /** - * @param {!Query} query - * @param {?EventRegistration} eventRegistration - */ - Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) { - // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof - // a little bit by handling the return values anyways. - var events; - if (query.path.getFront() === '.info') { - events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration); - } - else { - events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration); - } - this.eventQueue_.raiseEventsAtPath(query.path, events); - }; - Repo.prototype.interrupt = function () { - if (this.persistentConnection_) { - this.persistentConnection_.interrupt(INTERRUPT_REASON); - } - }; - Repo.prototype.resume = function () { - if (this.persistentConnection_) { - this.persistentConnection_.resume(INTERRUPT_REASON); - } - }; - Repo.prototype.stats = function (showDelta) { - if (showDelta === void 0) { showDelta = false; } - if (typeof console === 'undefined') - return; - var stats; - if (showDelta) { - if (!this.statsListener_) - this.statsListener_ = new StatsListener(this.stats_); - stats = this.statsListener_.get(); - } - else { - stats = this.stats_.get(); - } - var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) { - return Math.max(currentValue.length, previousValue); - }, 0); - util.forEach(stats, function (stat, value) { - // pad stat names to be the same length (plus 2 extra spaces). - for (var i = stat.length; i < longestName + 2; i++) - stat += ' '; - console.log(stat + value); - }); - }; - Repo.prototype.statsIncrementCounter = function (metric) { - this.stats_.incrementCounter(metric); - this.statsReporter_.includeStat(metric); - }; - /** - * @param {...*} var_args - * @private - */ - Repo.prototype.log_ = function () { - var var_args = []; - for (var _i = 0; _i < arguments.length; _i++) { - var_args[_i] = arguments[_i]; - } - var prefix = ''; - if (this.persistentConnection_) { - prefix = this.persistentConnection_.id + ':'; - } - log.apply(void 0, [prefix].concat(var_args)); - }; - /** - * @param {?function(?Error, *=)} callback - * @param {!string} status - * @param {?string=} errorReason - */ - Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) { - if (callback) { - exceptionGuard(function () { - if (status == 'ok') { - callback(null); - } - else { - var code = (status || 'error').toUpperCase(); - var message = code; - if (errorReason) - message += ': ' + errorReason; - var error$$1 = new Error(message); - error$$1.code = code; - callback(error$$1); - } - }); - } - }; - Object.defineProperty(Repo.prototype, "database", { - get: function () { - return this.__database || (this.__database = new Database(this)); - }, - enumerable: true, - configurable: true - }); - return Repo; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node - * - * @constructor - * @implements {NodeFilter} - */ -var RangedFilter = /** @class */ (function () { - /** - * @param {!QueryParams} params - */ - function RangedFilter(params) { - this.indexedFilter_ = new IndexedFilter(params.getIndex()); - this.index_ = params.getIndex(); - this.startPost_ = RangedFilter.getStartPost_(params); - this.endPost_ = RangedFilter.getEndPost_(params); - } - /** - * @return {!NamedNode} - */ - RangedFilter.prototype.getStartPost = function () { - return this.startPost_; - }; - /** - * @return {!NamedNode} - */ - RangedFilter.prototype.getEndPost = function () { - return this.endPost_; - }; - /** - * @param {!NamedNode} node - * @return {boolean} - */ - RangedFilter.prototype.matches = function (node) { - return (this.index_.compare(this.getStartPost(), node) <= 0 && - this.index_.compare(node, this.getEndPost()) <= 0); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - if (!this.matches(new NamedNode(key, newChild))) { - newChild = ChildrenNode.EMPTY_NODE; - } - return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - if (newSnap.isLeafNode()) { - // Make sure we have a children node with the correct index, not a leaf node; - newSnap = ChildrenNode.EMPTY_NODE; - } - var filtered = newSnap.withIndex(this.index_); - // Don't support priorities on queries - filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); - var self = this; - newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) { - if (!self.matches(new NamedNode(key, childNode))) { - filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE); - } - }); - return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - // Don't support priorities on queries - return oldSnap; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.filtersNodes = function () { - return true; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.getIndexedFilter = function () { - return this.indexedFilter_; - }; - /** - * @inheritDoc - */ - RangedFilter.prototype.getIndex = function () { - return this.index_; - }; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - RangedFilter.getStartPost_ = function (params) { - if (params.hasStart()) { - var startName = params.getIndexStartName(); - return params.getIndex().makePost(params.getIndexStartValue(), startName); - } - else { - return params.getIndex().minPost(); - } - }; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - RangedFilter.getEndPost_ = function (params) { - if (params.hasEnd()) { - var endName = params.getIndexEndName(); - return params.getIndex().makePost(params.getIndexEndValue(), endName); - } - else { - return params.getIndex().maxPost(); - } - }; - return RangedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible - * - * @constructor - * @implements {NodeFilter} - */ -var LimitedFilter = /** @class */ (function () { - /** - * @param {!QueryParams} params - */ - function LimitedFilter(params) { - this.rangedFilter_ = new RangedFilter(params); - this.index_ = params.getIndex(); - this.limit_ = params.getLimit(); - this.reverse_ = !params.isViewFromLeft(); - } - /** - * @inheritDoc - */ - LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) { - if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) { - newChild = ChildrenNode.EMPTY_NODE; - } - if (snap.getImmediateChild(key).equals(newChild)) { - // No change - return snap; - } - else if (snap.numChildren() < this.limit_) { - return this.rangedFilter_ - .getIndexedFilter() - .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator); - } - else { - return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator); - } - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) { - var filtered; - if (newSnap.isLeafNode() || newSnap.isEmpty()) { - // Make sure we have a children node with the correct index, not a leaf node; - filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); - } - else { - if (this.limit_ * 2 < newSnap.numChildren() && - newSnap.isIndexed(this.index_)) { - // Easier to build up a snapshot, since what we're given has more than twice the elements we want - filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); - // anchor to the startPost, endPost, or last element as appropriate - var iterator = void 0; - if (this.reverse_) { - iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_); - } - else { - iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_); - } - var count = 0; - while (iterator.hasNext() && count < this.limit_) { - var next = iterator.getNext(); - var inRange = void 0; - if (this.reverse_) { - inRange = - this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0; - } - else { - inRange = - this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0; - } - if (inRange) { - filtered = filtered.updateImmediateChild(next.name, next.node); - count++; - } - else { - // if we have reached the end post, we cannot keep adding elemments - break; - } - } - } - else { - // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one - filtered = newSnap.withIndex(this.index_); - // Don't support priorities on queries - filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE); - var startPost = void 0; - var endPost = void 0; - var cmp = void 0; - var iterator = void 0; - if (this.reverse_) { - iterator = filtered.getReverseIterator(this.index_); - startPost = this.rangedFilter_.getEndPost(); - endPost = this.rangedFilter_.getStartPost(); - var indexCompare_1 = this.index_.getCompare(); - cmp = function (a, b) { return indexCompare_1(b, a); }; - } - else { - iterator = filtered.getIterator(this.index_); - startPost = this.rangedFilter_.getStartPost(); - endPost = this.rangedFilter_.getEndPost(); - cmp = this.index_.getCompare(); - } - var count = 0; - var foundStartPost = false; - while (iterator.hasNext()) { - var next = iterator.getNext(); - if (!foundStartPost && cmp(startPost, next) <= 0) { - // start adding - foundStartPost = true; - } - var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0; - if (inRange) { - count++; - } - else { - filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE); - } - } - } - } - return this.rangedFilter_ - .getIndexedFilter() - .updateFullNode(oldSnap, filtered, optChangeAccumulator); - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) { - // Don't support priorities on queries - return oldSnap; - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.filtersNodes = function () { - return true; - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.getIndexedFilter = function () { - return this.rangedFilter_.getIndexedFilter(); - }; - /** - * @inheritDoc - */ - LimitedFilter.prototype.getIndex = function () { - return this.index_; - }; - /** - * @param {!Node} snap - * @param {string} childKey - * @param {!Node} childSnap - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} changeAccumulator - * @return {!Node} - * @private - */ - LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) { - // TODO: rename all cache stuff etc to general snap terminology - var cmp; - if (this.reverse_) { - var indexCmp_1 = this.index_.getCompare(); - cmp = function (a, b) { return indexCmp_1(b, a); }; - } - else { - cmp = this.index_.getCompare(); - } - var oldEventCache = snap; - util.assert(oldEventCache.numChildren() == this.limit_, ''); - var newChildNamedNode = new NamedNode(childKey, childSnap); - var windowBoundary = this.reverse_ - ? oldEventCache.getFirstChild(this.index_) - : oldEventCache.getLastChild(this.index_); - var inRange = this.rangedFilter_.matches(newChildNamedNode); - if (oldEventCache.hasChild(childKey)) { - var oldChildSnap = oldEventCache.getImmediateChild(childKey); - var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_); - while (nextChild != null && - (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) { - // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't - // been applied to the limited filter yet. Ignore this next child which will be updated later in - // the limited filter... - nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_); - } - var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode); - var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0; - if (remainsInWindow) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childChangedChange(childKey, childSnap, oldChildSnap)); - } - return oldEventCache.updateImmediateChild(childKey, childSnap); - } - else { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childRemovedChange(childKey, oldChildSnap)); - } - var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE); - var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild); - if (nextChildInRange) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childAddedChange(nextChild.name, nextChild.node)); - } - return newEventCache.updateImmediateChild(nextChild.name, nextChild.node); - } - else { - return newEventCache; - } - } - } - else if (childSnap.isEmpty()) { - // we're deleting a node, but it was not in the window, so ignore it - return snap; - } - else if (inRange) { - if (cmp(windowBoundary, newChildNamedNode) >= 0) { - if (changeAccumulator != null) { - changeAccumulator.trackChildChange(Change.childRemovedChange(windowBoundary.name, windowBoundary.node)); - changeAccumulator.trackChildChange(Change.childAddedChange(childKey, childSnap)); - } - return oldEventCache - .updateImmediateChild(childKey, childSnap) - .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE); - } - else { - return snap; - } - } - else { - return snap; - } - }; - return LimitedFilter; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a - * range to be returned for a particular location. It is assumed that validation of parameters is done at the - * user-facing API level, so it is not done here. - * @constructor - */ -var QueryParams = /** @class */ (function () { - function QueryParams() { - this.limitSet_ = false; - this.startSet_ = false; - this.startNameSet_ = false; - this.endSet_ = false; - this.endNameSet_ = false; - this.limit_ = 0; - this.viewFrom_ = ''; - this.indexStartValue_ = null; - this.indexStartName_ = ''; - this.indexEndValue_ = null; - this.indexEndName_ = ''; - this.index_ = PRIORITY_INDEX; - } - /** - * @return {boolean} - */ - QueryParams.prototype.hasStart = function () { - return this.startSet_; - }; - /** - * @return {boolean} True if it would return from left. - */ - QueryParams.prototype.isViewFromLeft = function () { - if (this.viewFrom_ === '') { - // limit(), rather than limitToFirst or limitToLast was called. - // This means that only one of startSet_ and endSet_ is true. Use them - // to calculate which side of the view to anchor to. If neither is set, - // anchor to the end. - return this.startSet_; - } - else { - return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT); - } - }; - /** - * Only valid to call if hasStart() returns true - * @return {*} - */ - QueryParams.prototype.getIndexStartValue = function () { - util.assert(this.startSet_, 'Only valid if start has been set'); - return this.indexStartValue_; - }; - /** - * Only valid to call if hasStart() returns true. - * Returns the starting key name for the range defined by these query parameters - * @return {!string} - */ - QueryParams.prototype.getIndexStartName = function () { - util.assert(this.startSet_, 'Only valid if start has been set'); - if (this.startNameSet_) { - return this.indexStartName_; - } - else { - return MIN_NAME; - } - }; - /** - * @return {boolean} - */ - QueryParams.prototype.hasEnd = function () { - return this.endSet_; - }; - /** - * Only valid to call if hasEnd() returns true. - * @return {*} - */ - QueryParams.prototype.getIndexEndValue = function () { - util.assert(this.endSet_, 'Only valid if end has been set'); - return this.indexEndValue_; - }; - /** - * Only valid to call if hasEnd() returns true. - * Returns the end key name for the range defined by these query parameters - * @return {!string} - */ - QueryParams.prototype.getIndexEndName = function () { - util.assert(this.endSet_, 'Only valid if end has been set'); - if (this.endNameSet_) { - return this.indexEndName_; - } - else { - return MAX_NAME; - } - }; - /** - * @return {boolean} - */ - QueryParams.prototype.hasLimit = function () { - return this.limitSet_; - }; - /** - * @return {boolean} True if a limit has been set and it has been explicitly anchored - */ - QueryParams.prototype.hasAnchoredLimit = function () { - return this.limitSet_ && this.viewFrom_ !== ''; - }; - /** - * Only valid to call if hasLimit() returns true - * @return {!number} - */ - QueryParams.prototype.getLimit = function () { - util.assert(this.limitSet_, 'Only valid if limit has been set'); - return this.limit_; - }; - /** - * @return {!Index} - */ - QueryParams.prototype.getIndex = function () { - return this.index_; - }; - /** - * @return {!QueryParams} - * @private - */ - QueryParams.prototype.copy_ = function () { - var copy = new QueryParams(); - copy.limitSet_ = this.limitSet_; - copy.limit_ = this.limit_; - copy.startSet_ = this.startSet_; - copy.indexStartValue_ = this.indexStartValue_; - copy.startNameSet_ = this.startNameSet_; - copy.indexStartName_ = this.indexStartName_; - copy.endSet_ = this.endSet_; - copy.indexEndValue_ = this.indexEndValue_; - copy.endNameSet_ = this.endNameSet_; - copy.indexEndName_ = this.indexEndName_; - copy.index_ = this.index_; - copy.viewFrom_ = this.viewFrom_; - return copy; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limit = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = ''; - return newParams; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limitToFirst = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT; - return newParams; - }; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - QueryParams.prototype.limitToLast = function (newLimit) { - var newParams = this.copy_(); - newParams.limitSet_ = true; - newParams.limit_ = newLimit; - newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT; - return newParams; - }; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - QueryParams.prototype.startAt = function (indexValue, key) { - var newParams = this.copy_(); - newParams.startSet_ = true; - if (!(indexValue !== undefined)) { - indexValue = null; - } - newParams.indexStartValue_ = indexValue; - if (key != null) { - newParams.startNameSet_ = true; - newParams.indexStartName_ = key; - } - else { - newParams.startNameSet_ = false; - newParams.indexStartName_ = ''; - } - return newParams; - }; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - QueryParams.prototype.endAt = function (indexValue, key) { - var newParams = this.copy_(); - newParams.endSet_ = true; - if (!(indexValue !== undefined)) { - indexValue = null; - } - newParams.indexEndValue_ = indexValue; - if (key !== undefined) { - newParams.endNameSet_ = true; - newParams.indexEndName_ = key; - } - else { - newParams.endNameSet_ = false; - newParams.indexEndName_ = ''; - } - return newParams; - }; - /** - * @param {!Index} index - * @return {!QueryParams} - */ - QueryParams.prototype.orderBy = function (index) { - var newParams = this.copy_(); - newParams.index_ = index; - return newParams; - }; - /** - * @return {!Object} - */ - QueryParams.prototype.getQueryObject = function () { - var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_; - var obj = {}; - if (this.startSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_; - if (this.startNameSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_; - } - } - if (this.endSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_; - if (this.endNameSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_; - } - } - if (this.limitSet_) { - obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_; - var viewFrom = this.viewFrom_; - if (viewFrom === '') { - if (this.isViewFromLeft()) { - viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT; - } - else { - viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT; - } - } - obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom; - } - // For now, priority index is the default, so we only specify if it's some other index - if (this.index_ !== PRIORITY_INDEX) { - obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString(); - } - return obj; - }; - /** - * @return {boolean} - */ - QueryParams.prototype.loadsAllData = function () { - return !(this.startSet_ || this.endSet_ || this.limitSet_); - }; - /** - * @return {boolean} - */ - QueryParams.prototype.isDefault = function () { - return this.loadsAllData() && this.index_ == PRIORITY_INDEX; - }; - /** - * @return {!NodeFilter} - */ - QueryParams.prototype.getNodeFilter = function () { - if (this.loadsAllData()) { - return new IndexedFilter(this.getIndex()); - } - else if (this.hasLimit()) { - return new LimitedFilter(this); - } - else { - return new RangedFilter(this); - } - }; - /** - * Returns a set of REST query string parameters representing this query. - * - * @return {!Object.} query string parameters - */ - QueryParams.prototype.toRestQueryStringParameters = function () { - var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_; - var qs = {}; - if (this.isDefault()) { - return qs; - } - var orderBy; - if (this.index_ === PRIORITY_INDEX) { - orderBy = REST_CONSTANTS.PRIORITY_INDEX; - } - else if (this.index_ === VALUE_INDEX) { - orderBy = REST_CONSTANTS.VALUE_INDEX; - } - else if (this.index_ === KEY_INDEX) { - orderBy = REST_CONSTANTS.KEY_INDEX; - } - else { - util.assert(this.index_ instanceof PathIndex, 'Unrecognized index type!'); - orderBy = this.index_.toString(); - } - qs[REST_CONSTANTS.ORDER_BY] = util.stringify(orderBy); - if (this.startSet_) { - qs[REST_CONSTANTS.START_AT] = util.stringify(this.indexStartValue_); - if (this.startNameSet_) { - qs[REST_CONSTANTS.START_AT] += ',' + util.stringify(this.indexStartName_); - } - } - if (this.endSet_) { - qs[REST_CONSTANTS.END_AT] = util.stringify(this.indexEndValue_); - if (this.endNameSet_) { - qs[REST_CONSTANTS.END_AT] += ',' + util.stringify(this.indexEndName_); - } - } - if (this.limitSet_) { - if (this.isViewFromLeft()) { - qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_; - } - else { - qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_; - } - } - return qs; - }; - /** - * Wire Protocol Constants - * @const - * @enum {string} - * @private - */ - QueryParams.WIRE_PROTOCOL_CONSTANTS_ = { - INDEX_START_VALUE: 'sp', - INDEX_START_NAME: 'sn', - INDEX_END_VALUE: 'ep', - INDEX_END_NAME: 'en', - LIMIT: 'l', - VIEW_FROM: 'vf', - VIEW_FROM_LEFT: 'l', - VIEW_FROM_RIGHT: 'r', - INDEX: 'i' - }; - /** - * REST Query Constants - * @const - * @enum {string} - * @private - */ - QueryParams.REST_QUERY_CONSTANTS_ = { - ORDER_BY: 'orderBy', - PRIORITY_INDEX: '$priority', - VALUE_INDEX: '$value', - KEY_INDEX: '$key', - START_AT: 'startAt', - END_AT: 'endAt', - LIMIT_TO_FIRST: 'limitToFirst', - LIMIT_TO_LAST: 'limitToLast' - }; - /** - * Default, empty query parameters - * @type {!QueryParams} - * @const - */ - QueryParams.DEFAULT = new QueryParams(); - return QueryParams; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Reference = /** @class */ (function (_super) { - tslib_1.__extends(Reference, _super); - /** - * Call options: - * new Reference(Repo, Path) or - * new Reference(url: string, string|RepoManager) - * - * Externally - this is the firebase.database.Reference type. - * - * @param {!Repo} repo - * @param {(!Path)} path - * @extends {Query} - */ - function Reference(repo, path) { - var _this = this; - if (!(repo instanceof Repo)) { - throw new Error('new Reference() no longer supported - use app.database().'); - } - // call Query's constructor, passing in the repo and path. - _this = _super.call(this, repo, path, QueryParams.DEFAULT, false) || this; - return _this; - } - /** @return {?string} */ - Reference.prototype.getKey = function () { - util.validateArgCount('Reference.key', 0, 0, arguments.length); - if (this.path.isEmpty()) - return null; - else - return this.path.getBack(); - }; - /** - * @param {!(string|Path)} pathString - * @return {!Reference} - */ - Reference.prototype.child = function (pathString) { - util.validateArgCount('Reference.child', 1, 1, arguments.length); - if (typeof pathString === 'number') { - pathString = String(pathString); - } - else if (!(pathString instanceof Path)) { - if (this.path.getFront() === null) - validateRootPathString('Reference.child', 1, pathString, false); - else - validatePathString('Reference.child', 1, pathString, false); - } - return new Reference(this.repo, this.path.child(pathString)); - }; - /** @return {?Reference} */ - Reference.prototype.getParent = function () { - util.validateArgCount('Reference.parent', 0, 0, arguments.length); - var parentPath = this.path.parent(); - return parentPath === null ? null : new Reference(this.repo, parentPath); - }; - /** @return {!Reference} */ - Reference.prototype.getRoot = function () { - util.validateArgCount('Reference.root', 0, 0, arguments.length); - var ref = this; - while (ref.getParent() !== null) { - ref = ref.getParent(); - } - return ref; - }; - /** @return {!Database} */ - Reference.prototype.databaseProp = function () { - return this.repo.database; - }; - /** - * @param {*} newVal - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.set = function (newVal, onComplete) { - util.validateArgCount('Reference.set', 1, 2, arguments.length); - validateWritablePath('Reference.set', this.path); - validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false); - util.validateCallback('Reference.set', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo.setWithPriority(this.path, newVal, - /*priority=*/ null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.update = function (objectToMerge, onComplete) { - util.validateArgCount('Reference.update', 1, 2, arguments.length); - validateWritablePath('Reference.update', this.path); - if (Array.isArray(objectToMerge)) { - var newObjectToMerge = {}; - for (var i = 0; i < objectToMerge.length; ++i) { - newObjectToMerge['' + i] = objectToMerge[i]; - } - objectToMerge = newObjectToMerge; - warn('Passing an Array to Firebase.update() is deprecated. ' + - 'Use set() if you want to overwrite the existing data, or ' + - 'an Object with integer keys if you really do want to ' + - 'only update some of the children.'); - } - validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false); - util.validateCallback('Reference.update', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*} newVal - * @param {string|number|null} newPriority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) { - util.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length); - validateWritablePath('Reference.setWithPriority', this.path); - validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false); - validatePriority('Reference.setWithPriority', 2, newPriority, false); - util.validateCallback('Reference.setWithPriority', 3, onComplete, true); - if (this.getKey() === '.length' || this.getKey() === '.keys') - throw 'Reference.setWithPriority failed: ' + - this.getKey() + - ' is a read-only object.'; - var deferred = new util.Deferred(); - this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.remove = function (onComplete) { - util.validateArgCount('Reference.remove', 0, 1, arguments.length); - validateWritablePath('Reference.remove', this.path); - util.validateCallback('Reference.remove', 1, onComplete, true); - return this.set(null, onComplete); - }; - /** - * @param {function(*):*} transactionUpdate - * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete - * @param {boolean=} applyLocally - * @return {!Promise} - */ - Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) { - util.validateArgCount('Reference.transaction', 1, 3, arguments.length); - validateWritablePath('Reference.transaction', this.path); - util.validateCallback('Reference.transaction', 1, transactionUpdate, false); - util.validateCallback('Reference.transaction', 2, onComplete, true); - // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how - // to expose it. - validateBoolean('Reference.transaction', 3, applyLocally, true); - if (this.getKey() === '.length' || this.getKey() === '.keys') - throw 'Reference.transaction failed: ' + - this.getKey() + - ' is a read-only object.'; - if (applyLocally === undefined) - applyLocally = true; - var deferred = new util.Deferred(); - if (typeof onComplete === 'function') { - deferred.promise.catch(function () { }); - } - var promiseComplete = function (error$$1, committed, snapshot) { - if (error$$1) { - deferred.reject(error$$1); - } - else { - deferred.resolve(new TransactionResult(committed, snapshot)); - } - if (typeof onComplete === 'function') { - onComplete(error$$1, committed, snapshot); - } - }; - this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally); - return deferred.promise; - }; - /** - * @param {string|number|null} priority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - Reference.prototype.setPriority = function (priority, onComplete) { - util.validateArgCount('Reference.setPriority', 1, 2, arguments.length); - validateWritablePath('Reference.setPriority', this.path); - validatePriority('Reference.setPriority', 1, priority, false); - util.validateCallback('Reference.setPriority', 2, onComplete, true); - var deferred = new util.Deferred(); - this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete)); - return deferred.promise; - }; - /** - * @param {*=} value - * @param {function(?Error)=} onComplete - * @return {!Reference} - */ - Reference.prototype.push = function (value, onComplete) { - util.validateArgCount('Reference.push', 0, 2, arguments.length); - validateWritablePath('Reference.push', this.path); - validateFirebaseDataArg('Reference.push', 1, value, this.path, true); - util.validateCallback('Reference.push', 2, onComplete, true); - var now = this.repo.serverTime(); - var name = nextPushId(now); - // push() returns a ThennableReference whose promise is fulfilled with a regular Reference. - // We use child() to create handles to two different references. The first is turned into a - // ThennableReference below by adding then() and catch() methods and is used as the - // return value of push(). The second remains a regular Reference and is used as the fulfilled - // value of the first ThennableReference. - var thennablePushRef = this.child(name); - var pushRef = this.child(name); - var promise; - if (value != null) { - promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; }); - } - else { - promise = Promise.resolve(pushRef); - } - thennablePushRef.then = promise.then.bind(promise); - thennablePushRef.catch = promise.then.bind(promise, undefined); - if (typeof onComplete === 'function') { - promise.catch(function () { }); - } - return thennablePushRef; - }; - /** - * @return {!OnDisconnect} - */ - Reference.prototype.onDisconnect = function () { - validateWritablePath('Reference.onDisconnect', this.path); - return new OnDisconnect(this.repo, this.path); - }; - Object.defineProperty(Reference.prototype, "database", { - get: function () { - return this.databaseProp(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "key", { - get: function () { - return this.getKey(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "parent", { - get: function () { - return this.getParent(); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Reference.prototype, "root", { - get: function () { - return this.getRoot(); - }, - enumerable: true, - configurable: true - }); - return Reference; -}(Query)); -/** - * Define reference constructor in various modules - * - * We are doing this here to avoid several circular - * dependency issues - */ -Query.__referenceConstructor = Reference; -SyncPoint.__referenceConstructor = Reference; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Node in a Tree. - */ -var TreeNode = /** @class */ (function () { - function TreeNode() { - // TODO: Consider making accessors that create children and value lazily or - // separate Internal / Leaf 'types'. - this.children = {}; - this.childCount = 0; - this.value = null; - } - return TreeNode; -}()); -/** - * A light-weight tree, traversable by path. Nodes can have both values and children. - * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty - * children. - */ -var Tree = /** @class */ (function () { - /** - * @template T - * @param {string=} name_ Optional name of the node. - * @param {Tree=} parent_ Optional parent node. - * @param {TreeNode=} node_ Optional node to wrap. - */ - function Tree(name_, parent_, node_) { - if (name_ === void 0) { name_ = ''; } - if (parent_ === void 0) { parent_ = null; } - if (node_ === void 0) { node_ = new TreeNode(); } - this.name_ = name_; - this.parent_ = parent_; - this.node_ = node_; - } - /** - * Returns a sub-Tree for the given path. - * - * @param {!(string|Path)} pathObj Path to look up. - * @return {!Tree.} Tree for path. - */ - Tree.prototype.subTree = function (pathObj) { - // TODO: Require pathObj to be Path? - var path = pathObj instanceof Path ? pathObj : new Path(pathObj); - var child = this, next; - while ((next = path.getFront()) !== null) { - var childNode = util.safeGet(child.node_.children, next) || new TreeNode(); - child = new Tree(next, child, childNode); - path = path.popFront(); - } - return child; - }; - /** - * Returns the data associated with this tree node. - * - * @return {?T} The data or null if no data exists. - */ - Tree.prototype.getValue = function () { - return this.node_.value; - }; - /** - * Sets data to this tree node. - * - * @param {!T} value Value to set. - */ - Tree.prototype.setValue = function (value) { - util.assert(typeof value !== 'undefined', 'Cannot set value to undefined'); - this.node_.value = value; - this.updateParents_(); - }; - /** - * Clears the contents of the tree node (its value and all children). - */ - Tree.prototype.clear = function () { - this.node_.value = null; - this.node_.children = {}; - this.node_.childCount = 0; - this.updateParents_(); - }; - /** - * @return {boolean} Whether the tree has any children. - */ - Tree.prototype.hasChildren = function () { - return this.node_.childCount > 0; - }; - /** - * @return {boolean} Whether the tree is empty (no value or children). - */ - Tree.prototype.isEmpty = function () { - return this.getValue() === null && !this.hasChildren(); - }; - /** - * Calls action for each child of this tree node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - Tree.prototype.forEachChild = function (action) { - var _this = this; - util.forEach(this.node_.children, function (child, childTree) { - action(new Tree(child, _this, childTree)); - }); - }; - /** - * Does a depth-first traversal of this node's descendants, calling action for each one. - * - * @param {function(!Tree.)} action Action to be called for each child. - * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to - * false. - * @param {boolean=} childrenFirst Whether to call action on children before calling it on - * parent. - */ - Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) { - if (includeSelf && !childrenFirst) - action(this); - this.forEachChild(function (child) { - child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst); - }); - if (includeSelf && childrenFirst) - action(this); - }; - /** - * Calls action on each ancestor node. - * - * @param {function(!Tree.)} action Action to be called on each parent; return - * true to abort. - * @param {boolean=} includeSelf Whether to call action on this node as well. - * @return {boolean} true if the action callback returned true. - */ - Tree.prototype.forEachAncestor = function (action, includeSelf) { - var node = includeSelf ? this : this.parent(); - while (node !== null) { - if (action(node)) { - return true; - } - node = node.parent(); - } - return false; - }; - /** - * Does a depth-first traversal of this node's descendants. When a descendant with a value - * is found, action is called on it and traversal does not continue inside the node. - * Action is *not* called on this node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - Tree.prototype.forEachImmediateDescendantWithValue = function (action) { - this.forEachChild(function (child) { - if (child.getValue() !== null) - action(child); - else - child.forEachImmediateDescendantWithValue(action); - }); - }; - /** - * @return {!Path} The path of this tree node, as a Path. - */ - Tree.prototype.path = function () { - return new Path(this.parent_ === null - ? this.name_ - : this.parent_.path() + '/' + this.name_); - }; - /** - * @return {string} The name of the tree node. - */ - Tree.prototype.name = function () { - return this.name_; - }; - /** - * @return {?Tree} The parent tree node, or null if this is the root of the tree. - */ - Tree.prototype.parent = function () { - return this.parent_; - }; - /** - * Adds or removes this child from its parent based on whether it's empty or not. - * - * @private - */ - Tree.prototype.updateParents_ = function () { - if (this.parent_ !== null) - this.parent_.updateChild_(this.name_, this); - }; - /** - * Adds or removes the passed child to this tree node, depending on whether it's empty. - * - * @param {string} childName The name of the child to update. - * @param {!Tree.} child The child to update. - * @private - */ - Tree.prototype.updateChild_ = function (childName, child) { - var childEmpty = child.isEmpty(); - var childExists = util.contains(this.node_.children, childName); - if (childEmpty && childExists) { - delete this.node_.children[childName]; - this.node_.childCount--; - this.updateParents_(); - } - else if (!childEmpty && !childExists) { - this.node_.children[childName] = child.node_; - this.node_.childCount++; - this.updateParents_(); - } - }; - return Tree; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific -// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well -// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first. -// For now it's part of Repo, but in its own file. -/** - * @enum {number} - */ -var TransactionStatus; -(function (TransactionStatus) { - // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the - // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to - // mismatched hash. - TransactionStatus[TransactionStatus["RUN"] = 0] = "RUN"; - // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted - // or rejected yet). - TransactionStatus[TransactionStatus["SENT"] = 1] = "SENT"; - // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be - // removed when we get a chance to prune completed ones. - TransactionStatus[TransactionStatus["COMPLETED"] = 2] = "COMPLETED"; - // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made). - // If it comes back as unsuccessful, we'll abort it. - TransactionStatus[TransactionStatus["SENT_NEEDS_ABORT"] = 3] = "SENT_NEEDS_ABORT"; - // Temporary state used to mark transactions that need to be aborted. - TransactionStatus[TransactionStatus["NEEDS_ABORT"] = 4] = "NEEDS_ABORT"; -})(TransactionStatus || (TransactionStatus = {})); -/** - * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's - * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely. - * @type {number} - * @const - * @private - */ -Repo.MAX_TRANSACTION_RETRIES_ = 25; -/** - * Setup the transaction data structures - * @private - */ -Repo.prototype.transactions_init_ = function () { - /** - * Stores queues of outstanding transactions for Firebase locations. - * - * @type {!Tree.>} - * @private - */ - this.transactionQueueTree_ = new Tree(); -}; -/** - * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible. - * - * @param {!Path} path Path at which to do transaction. - * @param {function(*):*} transactionUpdate Update callback. - * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback. - * @param {boolean} applyLocally Whether or not to make intermediate results visible - */ -Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) { - this.log_('transaction on ' + path); - // Add a watch to make sure we get server updates. - var valueCallback = function () { }; - var watchRef = new Reference(this, path); - watchRef.on('value', valueCallback); - var unwatcher = function () { - watchRef.off('value', valueCallback); - }; - // Initialize transaction. - var transaction = { - path: path, - update: transactionUpdate, - onComplete: onComplete, - // One of TransactionStatus enums. - status: null, - // Used when combining transactions at different locations to figure out which one goes first. - order: LUIDGenerator(), - // Whether to raise local events for this transaction. - applyLocally: applyLocally, - // Count of how many times we've retried the transaction. - retryCount: 0, - // Function to call to clean up our .on() listener. - unwatcher: unwatcher, - // Stores why a transaction was aborted. - abortReason: null, - currentWriteId: null, - currentInputSnapshot: null, - currentOutputSnapshotRaw: null, - currentOutputSnapshotResolved: null - }; - // Run transaction initially. - var currentState = this.getLatestState_(path); - transaction.currentInputSnapshot = currentState; - var newVal = transaction.update(currentState.val()); - if (newVal === undefined) { - // Abort transaction. - transaction.unwatcher(); - transaction.currentOutputSnapshotRaw = null; - transaction.currentOutputSnapshotResolved = null; - if (transaction.onComplete) { - // We just set the input snapshot, so this cast should be safe - var snapshot = new DataSnapshot(transaction.currentInputSnapshot, new Reference(this, transaction.path), PRIORITY_INDEX); - transaction.onComplete(null, false, snapshot); - } - } - else { - validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); - // Mark as run and add to our queue. - transaction.status = TransactionStatus.RUN; - var queueNode = this.transactionQueueTree_.subTree(path); - var nodeQueue = queueNode.getValue() || []; - nodeQueue.push(transaction); - queueNode.setValue(nodeQueue); - // Update visibleData and raise events - // Note: We intentionally raise events after updating all of our transaction state, since the user could - // start new transactions from the event callbacks. - var priorityForNode = void 0; - if (typeof newVal === 'object' && - newVal !== null && - util.contains(newVal, '.priority')) { - priorityForNode = util.safeGet(newVal, '.priority'); - util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + - 'Priority must be a valid string, finite number, server value, or null.'); - } - else { - var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) || - ChildrenNode.EMPTY_NODE; - priorityForNode = currentNode.getPriority().val(); - } - priorityForNode /** @type {null|number|string} */ = priorityForNode; - var serverValues = this.generateServerValues(); - var newNodeUnresolved = nodeFromJSON$1(newVal, priorityForNode); - var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues); - transaction.currentOutputSnapshotRaw = newNodeUnresolved; - transaction.currentOutputSnapshotResolved = newNode; - transaction.currentWriteId = this.getNextWriteId_(); - var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally); - this.eventQueue_.raiseEventsForChangedPath(path, events); - this.sendReadyTransactions_(); - } -}; -/** - * @param {!Path} path - * @param {Array.=} excludeSets A specific set to exclude - * @return {Node} - * @private - */ -Repo.prototype.getLatestState_ = function (path, excludeSets) { - return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) || - ChildrenNode.EMPTY_NODE); -}; -/** - * Sends any already-run transactions that aren't waiting for outstanding transactions to - * complete. - * - * Externally it's called with no arguments, but it calls itself recursively with a particular - * transactionQueueTree node to recurse through the tree. - * - * @param {Tree.>=} node transactionQueueTree node to start at. - * @private - */ -Repo.prototype.sendReadyTransactions_ = function (node) { - var _this = this; - if (node === void 0) { node = this.transactionQueueTree_; } - // Before recursing, make sure any completed transactions are removed. - if (!node) { - this.pruneCompletedTransactionsBelowNode_(node); - } - if (node.getValue() !== null) { - var queue = this.buildTransactionQueue_(node); - util.assert(queue.length > 0, 'Sending zero length transaction queue'); - var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; }); - // If they're all run (and not sent), we can send them. Else, we must wait. - if (allRun) { - this.sendTransactionQueue_(node.path(), queue); - } - } - else if (node.hasChildren()) { - node.forEachChild(function (childNode) { - _this.sendReadyTransactions_(childNode); - }); - } -}; -/** - * Given a list of run transactions, send them to the server and then handle the result (success or failure). - * - * @param {!Path} path The location of the queue. - * @param {!Array.} queue Queue of transactions under the specified location. - * @private - */ -Repo.prototype.sendTransactionQueue_ = function (path, queue) { - var _this = this; - // Mark transactions as sent and increment retry count! - var setsToIgnore = queue.map(function (txn) { - return txn.currentWriteId; - }); - var latestState = this.getLatestState_(path, setsToIgnore); - var snapToSend = latestState; - var latestHash = latestState.hash(); - for (var i = 0; i < queue.length; i++) { - var txn = queue[i]; - util.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.'); - txn.status = TransactionStatus.SENT; - txn.retryCount++; - var relativePath = Path.relativePath(path, txn.path); - // If we've gotten to this point, the output snapshot must be defined. - snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw); - } - var dataToSend = snapToSend.val(true); - var pathToSend = path; - // Send the put. - this.server_.put(pathToSend.toString(), dataToSend, function (status) { - _this.log_('transaction put response', { - path: pathToSend.toString(), - status: status - }); - var events = []; - if (status === 'ok') { - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - for (var i = 0; i < queue.length; i++) { - queue[i].status = TransactionStatus.COMPLETED; - events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId)); - if (queue[i].onComplete) { - // We never unset the output snapshot, and given that this transaction is complete, it should be set - var node = queue[i].currentOutputSnapshotResolved; - var ref = new Reference(_this, queue[i].path); - var snapshot = new DataSnapshot(node, ref, PRIORITY_INDEX); - callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot)); - } - queue[i].unwatcher(); - } - // Now remove the completed transactions. - _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path)); - // There may be pending transactions that we can now send. - _this.sendReadyTransactions_(); - _this.eventQueue_.raiseEventsForChangedPath(path, events); - // Finally, trigger onComplete callbacks. - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - } - else { - // transactions are no longer sent. Update their status appropriately. - if (status === 'datastale') { - for (var i = 0; i < queue.length; i++) { - if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) - queue[i].status = TransactionStatus.NEEDS_ABORT; - else - queue[i].status = TransactionStatus.RUN; - } - } - else { - warn('transaction at ' + pathToSend.toString() + ' failed: ' + status); - for (var i = 0; i < queue.length; i++) { - queue[i].status = TransactionStatus.NEEDS_ABORT; - queue[i].abortReason = status; - } - } - _this.rerunTransactions_(path); - } - }, latestHash); -}; -/** - * Finds all transactions dependent on the data at changedPath and reruns them. - * - * Should be called any time cached data changes. - * - * Return the highest path that was affected by rerunning transactions. This is the path at which events need to - * be raised for. - * - * @param {!Path} changedPath The path in mergedData that changed. - * @return {!Path} The rootmost path that was affected by rerunning transactions. - * @private - */ -Repo.prototype.rerunTransactions_ = function (changedPath) { - var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath); - var path = rootMostTransactionNode.path(); - var queue = this.buildTransactionQueue_(rootMostTransactionNode); - this.rerunTransactionQueue_(queue, path); - return path; -}; -/** - * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot). - * - * @param {Array.} queue The queue of transactions to run. - * @param {!Path} path The path the queue is for. - * @private - */ -Repo.prototype.rerunTransactionQueue_ = function (queue, path) { - if (queue.length === 0) { - return; // Nothing to do! - } - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - var events = []; - // Ignore all of the sets we're going to re-run. - var txnsToRerun = queue.filter(function (q) { - return q.status === TransactionStatus.RUN; - }); - var setsToIgnore = txnsToRerun.map(function (q) { - return q.currentWriteId; - }); - for (var i = 0; i < queue.length; i++) { - var transaction = queue[i]; - var relativePath = Path.relativePath(path, transaction.path); - var abortTransaction = false, abortReason = void 0; - util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.'); - if (transaction.status === TransactionStatus.NEEDS_ABORT) { - abortTransaction = true; - abortReason = transaction.abortReason; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - else if (transaction.status === TransactionStatus.RUN) { - if (transaction.retryCount >= Repo.MAX_TRANSACTION_RETRIES_) { - abortTransaction = true; - abortReason = 'maxretry'; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - else { - // This code reruns a transaction - var currentNode = this.getLatestState_(transaction.path, setsToIgnore); - transaction.currentInputSnapshot = currentNode; - var newData = queue[i].update(currentNode.val()); - if (newData !== undefined) { - validateFirebaseData('transaction failed: Data returned ', newData, transaction.path); - var newDataNode = nodeFromJSON$1(newData); - var hasExplicitPriority = typeof newData === 'object' && - newData != null && - util.contains(newData, '.priority'); - if (!hasExplicitPriority) { - // Keep the old priority if there wasn't a priority explicitly specified. - newDataNode = newDataNode.updatePriority(currentNode.getPriority()); - } - var oldWriteId = transaction.currentWriteId; - var serverValues = this.generateServerValues(); - var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, serverValues); - transaction.currentOutputSnapshotRaw = newDataNode; - transaction.currentOutputSnapshotResolved = newNodeResolved; - transaction.currentWriteId = this.getNextWriteId_(); - // Mutates setsToIgnore in place - setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1); - events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally)); - events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true)); - } - else { - abortTransaction = true; - abortReason = 'nodata'; - events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)); - } - } - } - this.eventQueue_.raiseEventsForChangedPath(path, events); - events = []; - if (abortTransaction) { - // Abort. - queue[i].status = TransactionStatus.COMPLETED; - // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data). - // So defer the unwatcher until we're done. - (function (unwatcher) { - setTimeout(unwatcher, Math.floor(0)); - })(queue[i].unwatcher); - if (queue[i].onComplete) { - if (abortReason === 'nodata') { - var ref = new Reference(this, queue[i].path); - // We set this field immediately, so it's safe to cast to an actual snapshot - var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot; - var snapshot = new DataSnapshot(lastInput, ref, PRIORITY_INDEX); - callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot)); - } - else { - callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null)); - } - } - } - } - // Clean up completed transactions. - this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_); - // Now fire callbacks, now that we're in a good, known state. - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - // Try to send the transaction result to the server. - this.sendReadyTransactions_(); -}; -/** - * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns - * the node for the given path if there are no pending transactions on any ancestor. - * - * @param {!Path} path The location to start at. - * @return {!Tree.>} The rootmost node with a transaction. - * @private - */ -Repo.prototype.getAncestorTransactionNode_ = function (path) { - var front; - // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions. - var transactionNode = this.transactionQueueTree_; - while ((front = path.getFront()) !== null && - transactionNode.getValue() === null) { - transactionNode = transactionNode.subTree(front); - path = path.popFront(); - } - return transactionNode; -}; -/** - * Builds the queue of all transactions at or below the specified transactionNode. - * - * @param {!Tree.>} transactionNode - * @return {Array.} The generated queue. - * @private - */ -Repo.prototype.buildTransactionQueue_ = function (transactionNode) { - // Walk any child transaction queues and aggregate them into a single queue. - var transactionQueue = []; - this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue); - // Sort them by the order the transactions were created. - transactionQueue.sort(function (a, b) { - return a.order - b.order; - }); - return transactionQueue; -}; -/** - * @param {!Tree.>} node - * @param {Array.} queue - * @private - */ -Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) { - var _this = this; - var nodeQueue = node.getValue(); - if (nodeQueue !== null) { - for (var i = 0; i < nodeQueue.length; i++) { - queue.push(nodeQueue[i]); - } - } - node.forEachChild(function (child) { - _this.aggregateTransactionQueuesForNode_(child, queue); - }); -}; -/** - * Remove COMPLETED transactions at or below this node in the transactionQueueTree_. - * - * @param {!Tree.>} node - * @private - */ -Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) { - var _this = this; - var queue = node.getValue(); - if (queue) { - var to = 0; - for (var from = 0; from < queue.length; from++) { - if (queue[from].status !== TransactionStatus.COMPLETED) { - queue[to] = queue[from]; - to++; - } - } - queue.length = to; - node.setValue(queue.length > 0 ? queue : null); - } - node.forEachChild(function (childNode) { - _this.pruneCompletedTransactionsBelowNode_(childNode); - }); -}; -/** - * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update() - * since we consider them incompatible with transactions. - * - * @param {!Path} path Path for which we want to abort related transactions. - * @return {!Path} - * @private - */ -Repo.prototype.abortTransactions_ = function (path) { - var _this = this; - var affectedPath = this.getAncestorTransactionNode_(path).path(); - var transactionNode = this.transactionQueueTree_.subTree(path); - transactionNode.forEachAncestor(function (node) { - _this.abortTransactionsOnNode_(node); - }); - this.abortTransactionsOnNode_(transactionNode); - transactionNode.forEachDescendant(function (node) { - _this.abortTransactionsOnNode_(node); - }); - return affectedPath; -}; -/** - * Abort transactions stored in this transaction queue node. - * - * @param {!Tree.>} node Node to abort transactions for. - * @private - */ -Repo.prototype.abortTransactionsOnNode_ = function (node) { - var queue = node.getValue(); - if (queue !== null) { - // Queue up the callbacks and fire them after cleaning up all of our transaction state, since - // the callback could trigger more transactions or sets. - var callbacks = []; - // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones - // can be immediately aborted and removed. - var events = []; - var lastSent = -1; - for (var i = 0; i < queue.length; i++) { - if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) { - // Already marked. No action needed. - } - else if (queue[i].status === TransactionStatus.SENT) { - util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.'); - lastSent = i; - // Mark transaction for abort when it comes back. - queue[i].status = TransactionStatus.SENT_NEEDS_ABORT; - queue[i].abortReason = 'set'; - } - else { - util.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort'); - // We can abort it immediately. - queue[i].unwatcher(); - events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true)); - if (queue[i].onComplete) { - var snapshot = null; - callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot)); - } - } - } - if (lastSent === -1) { - // We're not waiting for any sent transactions. We can clear the queue. - node.setValue(null); - } - else { - // Remove the transactions we aborted. - queue.length = lastSent + 1; - } - // Now fire the callbacks. - this.eventQueue_.raiseEventsForChangedPath(node.path(), events); - for (var i = 0; i < callbacks.length; i++) { - exceptionGuard(callbacks[i]); - } - } -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** @const {string} */ -var DATABASE_URL_OPTION = 'databaseURL'; -var _staticInstance; -/** - * Creates and caches Repo instances. - */ -var RepoManager = /** @class */ (function () { - function RepoManager() { - /** - * @private {!Object.>} - */ - this.repos_ = {}; - /** - * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes). - * @private {boolean} - */ - this.useRestClient_ = false; - } - RepoManager.getInstance = function () { - if (!_staticInstance) { - _staticInstance = new RepoManager(); - } - return _staticInstance; - }; - // TODO(koss): Remove these functions unless used in tests? - RepoManager.prototype.interrupt = function () { - for (var appName in this.repos_) { - for (var dbUrl in this.repos_[appName]) { - this.repos_[appName][dbUrl].interrupt(); - } - } - }; - RepoManager.prototype.resume = function () { - for (var appName in this.repos_) { - for (var dbUrl in this.repos_[appName]) { - this.repos_[appName][dbUrl].resume(); - } - } - }; - /** - * This function should only ever be called to CREATE a new database instance. - * - * @param {!FirebaseApp} app - * @return {!Database} - */ - RepoManager.prototype.databaseFromApp = function (app, url) { - var dbUrl = url || app.options[DATABASE_URL_OPTION]; - if (dbUrl === undefined) { - fatal("Can't determine Firebase Database URL. Be sure to include " + - DATABASE_URL_OPTION + - ' option when calling firebase.initializeApp().'); - } - var parsedUrl = parseRepoInfo(dbUrl); - var repoInfo = parsedUrl.repoInfo; - validateUrl('Invalid Firebase Database URL', 1, parsedUrl); - if (!parsedUrl.path.isEmpty()) { - fatal('Database URL must point to the root of a Firebase Database ' + - '(not including a child path).'); - } - var repo = this.createRepo(repoInfo, app); - return repo.database; - }; - /** - * Remove the repo and make sure it is disconnected. - * - * @param {!Repo} repo - */ - RepoManager.prototype.deleteRepo = function (repo) { - var appRepos = util.safeGet(this.repos_, repo.app.name); - // This should never happen... - if (!appRepos || util.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) { - fatal("Database " + repo.app.name + "(" + repo.repoInfo_ + ") has already been deleted."); - } - repo.interrupt(); - delete appRepos[repo.repoInfo_.toURLString()]; - }; - /** - * Ensures a repo doesn't already exist and then creates one using the - * provided app. - * - * @param {!RepoInfo} repoInfo The metadata about the Repo - * @param {!FirebaseApp} app - * @return {!Repo} The Repo object for the specified server / repoName. - */ - RepoManager.prototype.createRepo = function (repoInfo, app) { - var appRepos = util.safeGet(this.repos_, app.name); - if (!appRepos) { - appRepos = {}; - this.repos_[app.name] = appRepos; - } - var repo = util.safeGet(appRepos, repoInfo.toURLString()); - if (repo) { - fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); - } - repo = new Repo(repoInfo, this.useRestClient_, app); - appRepos[repoInfo.toURLString()] = repo; - return repo; - }; - /** - * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. - * @param {boolean} forceRestClient - */ - RepoManager.prototype.forceRestClient = function (forceRestClient) { - this.useRestClient_ = forceRestClient; - }; - return RepoManager; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class representing a firebase database. - * @implements {FirebaseService} - */ -var Database = /** @class */ (function () { - /** - * The constructor should not be called by users of our public API. - * @param {!Repo} repo_ - */ - function Database(repo_) { - this.repo_ = repo_; - if (!(repo_ instanceof Repo)) { - fatal("Don't call new Database() directly - please use firebase.database()."); - } - /** @type {Reference} */ - this.root_ = new Reference(repo_, Path.Empty); - this.INTERNAL = new DatabaseInternals(this); - } - Object.defineProperty(Database.prototype, "app", { - get: function () { - return this.repo_.app; - }, - enumerable: true, - configurable: true - }); - Database.prototype.ref = function (path) { - this.checkDeleted_('ref'); - util.validateArgCount('database.ref', 0, 1, arguments.length); - if (path instanceof Reference) { - return this.refFromURL(path.toString()); - } - return path !== undefined ? this.root_.child(path) : this.root_; - }; - /** - * Returns a reference to the root or the path specified in url. - * We throw a exception if the url is not in the same domain as the - * current repo. - * @param {string} url - * @return {!Reference} Firebase reference. - */ - Database.prototype.refFromURL = function (url) { - /** @const {string} */ - var apiName = 'database.refFromURL'; - this.checkDeleted_(apiName); - util.validateArgCount(apiName, 1, 1, arguments.length); - var parsedURL = parseRepoInfo(url); - validateUrl(apiName, 1, parsedURL); - var repoInfo = parsedURL.repoInfo; - if (repoInfo.host !== this.repo_.repoInfo_.host) { - fatal(apiName + - ': Host name does not match the current database: ' + - '(found ' + - repoInfo.host + - ' but expected ' + - this.repo_.repoInfo_.host + - ')'); - } - return this.ref(parsedURL.path.toString()); - }; - /** - * @param {string} apiName - */ - Database.prototype.checkDeleted_ = function (apiName) { - if (this.repo_ === null) { - fatal('Cannot call ' + apiName + ' on a deleted database.'); - } - }; - // Make individual repo go offline. - Database.prototype.goOffline = function () { - util.validateArgCount('database.goOffline', 0, 0, arguments.length); - this.checkDeleted_('goOffline'); - this.repo_.interrupt(); - }; - Database.prototype.goOnline = function () { - util.validateArgCount('database.goOnline', 0, 0, arguments.length); - this.checkDeleted_('goOnline'); - this.repo_.resume(); - }; - Database.ServerValue = { - TIMESTAMP: { - '.sv': 'timestamp' - } - }; - return Database; -}()); -var DatabaseInternals = /** @class */ (function () { - /** @param {!Database} database */ - function DatabaseInternals(database) { - this.database = database; - } - /** @return {Promise} */ - DatabaseInternals.prototype.delete = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - return tslib_1.__generator(this, function (_a) { - this.database.checkDeleted_('delete'); - RepoManager.getInstance().deleteRepo(this.database.repo_); - this.database.repo_ = null; - this.database.root_ = null; - this.database.INTERNAL = null; - this.database = null; - return [2 /*return*/]; - }); - }); - }; - return DatabaseInternals; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * INTERNAL methods for internal-use only (tests, etc.). - * - * Customers shouldn't use these or else should be aware that they could break at any time. - * - * @const - */ -var forceLongPolling = function () { - WebSocketConnection.forceDisallow(); - BrowserPollConnection.forceAllow(); -}; -var forceWebSockets = function () { - BrowserPollConnection.forceDisallow(); -}; -/* Used by App Manager */ -var isWebSocketsAvailable = function () { - return WebSocketConnection['isAvailable'](); -}; -var setSecurityDebugCallback = function (ref, callback) { - ref.repo.persistentConnection_.securityDebugCallback_ = callback; -}; -var stats = function (ref, showDelta) { - ref.repo.stats(showDelta); -}; -var statsIncrementCounter = function (ref, metric) { - ref.repo.statsIncrementCounter(metric); -}; -var dataUpdateCount = function (ref) { - return ref.repo.dataUpdateCount; -}; -var interceptServerData = function (ref, callback) { - return ref.repo.interceptServerData_(callback); -}; - -var INTERNAL = /*#__PURE__*/Object.freeze({ - forceLongPolling: forceLongPolling, - forceWebSockets: forceWebSockets, - isWebSocketsAvailable: isWebSocketsAvailable, - setSecurityDebugCallback: setSecurityDebugCallback, - stats: stats, - statsIncrementCounter: statsIncrementCounter, - dataUpdateCount: dataUpdateCount, - interceptServerData: interceptServerData -}); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DataConnection = PersistentConnection; -/** - * @param {!string} pathString - * @param {function(*)} onComplete - */ -PersistentConnection.prototype.simpleListen = function (pathString, onComplete) { - this.sendRequest('q', { p: pathString }, onComplete); -}; -/** - * @param {*} data - * @param {function(*)} onEcho - */ -PersistentConnection.prototype.echo = function (data, onEcho) { - this.sendRequest('echo', { d: data }, onEcho); -}; -// RealTimeConnection properties that we use in tests. -var RealTimeConnection = Connection; -/** - * @param {function(): string} newHash - * @return {function()} - */ -var hijackHash = function (newHash) { - var oldPut = PersistentConnection.prototype.put; - PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) { - if (opt_hash !== undefined) { - opt_hash = newHash(); - } - oldPut.call(this, pathString, data, opt_onComplete, opt_hash); - }; - return function () { - PersistentConnection.prototype.put = oldPut; - }; -}; -/** - * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined} - */ -var ConnectionTarget = RepoInfo; -/** - * @param {!Query} query - * @return {!string} - */ -var queryIdentifier = function (query) { - return query.queryIdentifier(); -}; -/** - * @param {!Query} firebaseRef - * @return {!Object} - */ -var listens = function (firebaseRef) { - return firebaseRef.repo.persistentConnection_.listens_; -}; -/** - * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. - * - * @param {boolean} forceRestClient - */ -var forceRestClient = function (forceRestClient) { - RepoManager.getInstance().forceRestClient(forceRestClient); -}; - -var TEST_ACCESS = /*#__PURE__*/Object.freeze({ - DataConnection: DataConnection, - RealTimeConnection: RealTimeConnection, - hijackHash: hijackHash, - ConnectionTarget: ConnectionTarget, - queryIdentifier: queryIdentifier, - listens: listens, - forceRestClient: forceRestClient -}); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -setWebSocketImpl(fayeWebsocket.Client); -/** - * @suppress {es5Strict} - */ -(function () { - var version = process['version']; - if (version !== 'v0.10.22' && - version !== 'v0.10.23' && - version !== 'v0.10.24') - return; - /** - * The following duplicates much of `/lib/_stream_writable.js` at - * b922b5e90d2c14dd332b95827c2533e083df7e55, applying the fix for - * https://github.com/joyent/node/issues/6506. Note that this fix also - * needs to be applied to `Duplex.prototype.write()` (in - * `/lib/_stream_duplex.js`) as well. - */ - var Writable = require('_stream_writable'); - Writable['prototype']['write'] = function (chunk, encoding, cb) { - var state = this['_writableState']; - var ret = false; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - if (Buffer['isBuffer'](chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state['defaultEncoding']; - if (typeof cb !== 'function') - cb = function () { }; - if (state['ended']) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - return ret; - }; - function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream['emit']('error', er); - process['nextTick'](function () { - cb(er); - }); - } - function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer['isBuffer'](chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state['objectMode']) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream['emit']('error', er); - process['nextTick'](function () { - cb(er); - }); - valid = false; - } - return valid; - } - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer['isBuffer'](chunk)) - encoding = 'buffer'; - var len = state['objectMode'] ? 1 : chunk['length']; - state['length'] += len; - var ret = state['length'] < state['highWaterMark']; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state['needDrain'] = true; - if (state['writing']) - state['buffer']['push'](new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - return ret; - } - function decodeChunk(state, chunk, encoding) { - if (!state['objectMode'] && - state['decodeStrings'] !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; - } - /** - * @constructor - */ - function WriteReq(chunk, encoding, cb) { - this['chunk'] = chunk; - this['encoding'] = encoding; - this['callback'] = cb; - } - function doWrite(stream, state, len, chunk, encoding, cb) { - state['writelen'] = len; - state['writecb'] = cb; - state['writing'] = true; - state['sync'] = true; - stream['_write'](chunk, encoding, state['onwrite']); - state['sync'] = false; - } - var Duplex = require('_stream_duplex'); - Duplex['prototype']['write'] = Writable['prototype']['write']; -})(); -/** - * @type {?function({url: string, forever: boolean}, function(Error, number, string))} - */ -FirebaseIFrameScriptHolder.request = null; -/** - * @param {{url: string, forever: boolean}} req - * @param {function(string)=} onComplete - */ -FirebaseIFrameScriptHolder.nodeRestRequest = function (req, onComplete) { - if (!FirebaseIFrameScriptHolder.request) - FirebaseIFrameScriptHolder.request = /** @type {function({url: string, forever: boolean}, function(Error, number, string))} */ require('request'); - FirebaseIFrameScriptHolder.request(req, function (error, response, body) { - if (error) - throw 'Rest request for ' + req.url + ' failed.'; - if (onComplete) - onComplete(body); - }); -}; -/** - * @param {!string} url - * @param {function()} loadCB - */ -FirebaseIFrameScriptHolder.prototype.doNodeLongPoll = function (url, loadCB) { - var self = this; - FirebaseIFrameScriptHolder.nodeRestRequest({ url: url, forever: true }, function (body) { - self.evalBody(body); - loadCB(); - }); -}; -/** - * Evaluates the string contents of a jsonp response. - * @param {!string} body - */ -FirebaseIFrameScriptHolder.prototype.evalBody = function (body) { - var jsonpCB; - //jsonpCB is externed in firebase-extern.js - eval('jsonpCB = function(' + - FIREBASE_LONGPOLL_COMMAND_CB_NAME + - ', ' + - FIREBASE_LONGPOLL_DATA_CB_NAME + - ') {' + - body + - '}'); - jsonpCB(this.commandCB, this.onMessageCB); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A one off register function which returns a database based on the app and - * passed database URL. - * - * @param app A valid FirebaseApp-like object - * @param url A valid Firebase databaseURL - */ -var ServerValue = Database.ServerValue; -function initStandalone(app, url, version) { - /** - * This should allow the firebase-admin package to provide a custom version - * to the backend - */ - util.CONSTANTS.NODE_ADMIN = true; - if (version) { - firebase.SDK_VERSION = version; - } - return { - instance: RepoManager.getInstance().databaseFromApp(app, url), - namespace: { - Reference: Reference, - Query: Query, - Database: Database, - enableLogging: enableLogging, - INTERNAL: INTERNAL, - ServerValue: ServerValue, - TEST_ACCESS: TEST_ACCESS - } - }; -} -function registerDatabase(instance) { - // Register the Database Service with the 'firebase' namespace. - var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager.getInstance().databaseFromApp(app, url); }, - // firebase.database namespace properties - { - Reference: Reference, - Query: Query, - Database: Database, - enableLogging: enableLogging, - INTERNAL: INTERNAL, - ServerValue: ServerValue, - TEST_ACCESS: TEST_ACCESS - }, null, true); - if (util.isNodeSdk()) { - module.exports = Object.assign({}, namespace, { initStandalone: initStandalone }); - } -} -registerDatabase(firebase); - -exports.initStandalone = initStandalone; -exports.registerDatabase = registerDatabase; -exports.Database = Database; -exports.Query = Query; -exports.Reference = Reference; -exports.enableLogging = enableLogging; -exports.ServerValue = ServerValue; -exports.DataSnapshot = DataSnapshot; -exports.OnDisconnect = OnDisconnect; diff --git a/functions/node_modules/@firebase/database/dist/index.node.d.ts b/functions/node_modules/@firebase/database/dist/index.node.d.ts deleted file mode 100644 index d840814e..00000000 --- a/functions/node_modules/@firebase/database/dist/index.node.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { FirebaseNamespace } from '@firebase/app-types'; -import { Database } from './src/api/Database'; -import { Query } from './src/api/Query'; -import { Reference } from './src/api/Reference'; -import { enableLogging } from './src/core/util/util'; -import * as INTERNAL from './src/api/internal'; -import * as TEST_ACCESS from './src/api/test_access'; -import './src/nodePatches'; -import * as types from '@firebase/database-types'; -/** - * A one off register function which returns a database based on the app and - * passed database URL. - * - * @param app A valid FirebaseApp-like object - * @param url A valid Firebase databaseURL - */ -declare const ServerValue: { - TIMESTAMP: { - '.sv': string; - }; -}; -export declare function initStandalone(app: any, url: any, version?: string): { - instance: Database; - namespace: { - Reference: typeof Reference; - Query: typeof Query; - Database: typeof Database; - enableLogging: (logger_?: boolean | ((a: string) => void), persistent?: boolean) => void; - INTERNAL: typeof INTERNAL; - ServerValue: { - TIMESTAMP: { - '.sv': string; - }; - }; - TEST_ACCESS: typeof TEST_ACCESS; - }; -}; -export declare function registerDatabase(instance: FirebaseNamespace): void; -export { Database, Query, Reference, enableLogging, ServerValue }; -export { DataSnapshot } from './src/api/DataSnapshot'; -export { OnDisconnect } from './src/api/onDisconnect'; -declare module '@firebase/app-types' { - interface FirebaseNamespace { - database?: { - (app?: FirebaseApp): types.FirebaseDatabase; - enableLogging: typeof types.enableLogging; - ServerValue: types.ServerValue; - Database: typeof types.FirebaseDatabase; - }; - } - interface FirebaseApp { - database?(): types.FirebaseDatabase; - } -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/index.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/index.d.ts deleted file mode 100644 index abc5dc3d..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/index.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { FirebaseNamespace } from '@firebase/app-types'; -import { Database } from './src/api/Database'; -import { Query } from './src/api/Query'; -import { Reference } from './src/api/Reference'; -import { enableLogging } from './src/core/util/util'; -import * as types from '@firebase/database-types'; -declare const ServerValue: { - TIMESTAMP: { - '.sv': string; - }; -}; -export declare function registerDatabase(instance: FirebaseNamespace): void; -export { Database, Query, Reference, enableLogging, ServerValue }; -export { DataSnapshot } from './src/api/DataSnapshot'; -export { OnDisconnect } from './src/api/onDisconnect'; -declare module '@firebase/app-types' { - interface FirebaseNamespace { - database?: { - (app?: FirebaseApp): types.FirebaseDatabase; - enableLogging: typeof types.enableLogging; - ServerValue: types.ServerValue; - Database: typeof types.FirebaseDatabase; - }; - } - interface FirebaseApp { - database?(databaseURL?: string): types.FirebaseDatabase; - } -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/api/internal.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/api/internal.d.ts deleted file mode 100644 index 1d7f9d92..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/api/internal.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Reference } from './Reference'; -/** - * INTERNAL methods for internal-use only (tests, etc.). - * - * Customers shouldn't use these or else should be aware that they could break at any time. - * - * @const - */ -export declare const forceLongPolling: () => void; -export declare const forceWebSockets: () => void; -export declare const isWebSocketsAvailable: () => boolean; -export declare const setSecurityDebugCallback: (ref: Reference, callback: (a: Object) => void) => void; -export declare const stats: (ref: Reference, showDelta?: boolean) => void; -export declare const statsIncrementCounter: (ref: Reference, metric: string) => void; -export declare const dataUpdateCount: (ref: Reference) => number; -export declare const interceptServerData: (ref: Reference, callback: (a: string, b: any) => void) => void; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/api/test_access.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/api/test_access.d.ts deleted file mode 100644 index 347e6203..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/api/test_access.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { RepoInfo } from '../core/RepoInfo'; -import { PersistentConnection } from '../core/PersistentConnection'; -import { Connection } from '../realtime/Connection'; -import { Query } from './Query'; -export declare const DataConnection: typeof PersistentConnection; -export declare const RealTimeConnection: typeof Connection; -/** - * @param {function(): string} newHash - * @return {function()} - */ -export declare const hijackHash: (newHash: () => string) => () => void; -/** - * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined} - */ -export declare const ConnectionTarget: typeof RepoInfo; -/** - * @param {!Query} query - * @return {!string} - */ -export declare const queryIdentifier: (query: Query) => string; -/** - * @param {!Query} firebaseRef - * @return {!Object} - */ -export declare const listens: (firebaseRef: Query) => any; -/** - * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. - * - * @param {boolean} forceRestClient - */ -export declare const forceRestClient: (forceRestClient: boolean) => void; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/PersistentConnection.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/PersistentConnection.d.ts deleted file mode 100644 index ecd1dd3e..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/PersistentConnection.d.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { ServerActions } from './ServerActions'; -import { AuthTokenProvider } from './AuthTokenProvider'; -import { RepoInfo } from './RepoInfo'; -import { Query } from '../api/Query'; -/** - * Firebase connection. Abstracts wire protocol and handles reconnecting. - * - * NOTE: All JSON objects sent to the realtime connection must have property names enclosed - * in quotes to make sure the closure compiler does not minify them. - */ -export declare class PersistentConnection extends ServerActions { - private repoInfo_; - private onDataUpdate_; - private onConnectStatus_; - private onServerInfoUpdate_; - private authTokenProvider_; - private authOverride_; - id: number; - private log_; - /** @private {Object} */ - private interruptReasons_; - private listens_; - private outstandingPuts_; - private outstandingPutCount_; - private onDisconnectRequestQueue_; - private connected_; - private reconnectDelay_; - private maxReconnectDelay_; - private securityDebugCallback_; - lastSessionId: string | null; - /** @private {number|null} */ - private establishConnectionTimer_; - /** @private {boolean} */ - private visible_; - private requestCBHash_; - private requestNumber_; - /** @private {?{ - * sendRequest(Object), - * close() - * }} */ - private realtime_; - /** @private {string|null} */ - private authToken_; - private forceTokenRefresh_; - private invalidAuthTokenCount_; - private firstConnection_; - private lastConnectionAttemptTime_; - private lastConnectionEstablishedTime_; - /** - * @private - */ - private static nextPersistentConnectionId_; - /** - * Counter for number of connections created. Mainly used for tagging in the logs - * @type {number} - * @private - */ - private static nextConnectionId_; - /** - * @implements {ServerActions} - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param onConnectStatus_ - * @param onServerInfoUpdate_ - * @param authTokenProvider_ - * @param authOverride_ - */ - constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: any, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: any) => void, authTokenProvider_: AuthTokenProvider, authOverride_?: Object | null); - /** - * @param {!string} action - * @param {*} body - * @param {function(*)=} onResponse - * @protected - */ - protected sendRequest(action: string, body: any, onResponse?: (a: any) => void): void; - /** - * @inheritDoc - */ - listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void; - /** - * @param {!{onComplete(), - * hashFn():!string, - * query: !Query, - * tag: ?number}} listenSpec - * @private - */ - private sendListen_(listenSpec); - /** - * @param {*} payload - * @param {!Query} query - * @private - */ - private static warnOnListenWarnings_(payload, query); - /** - * @inheritDoc - */ - refreshAuthToken(token: string): void; - /** - * @param {!string} credential - * @private - */ - private reduceReconnectDelayIfAdminCredential_(credential); - /** - * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like - * a auth revoked (the connection is closed). - */ - tryAuth(): void; - /** - * @inheritDoc - */ - unlisten(query: Query, tag: number | null): void; - private sendUnlisten_(pathString, queryId, queryObj, tag); - /** - * @inheritDoc - */ - onDisconnectPut(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @inheritDoc - */ - onDisconnectMerge(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @inheritDoc - */ - onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; - private sendOnDisconnect_(action, pathString, data, onComplete); - /** - * @inheritDoc - */ - put(pathString: string, data: any, onComplete?: (a: string, b: string) => void, hash?: string): void; - /** - * @inheritDoc - */ - merge(pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void; - putInternal(action: string, pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void; - private sendPut_(index); - /** - * @inheritDoc - */ - reportStats(stats: { - [k: string]: any; - }): void; - /** - * @param {*} message - * @private - */ - private onDataMessage_(message); - private onDataPush_(action, body); - private onReady_(timestamp, sessionId); - private scheduleConnect_(timeout); - /** - * @param {boolean} visible - * @private - */ - private onVisible_(visible); - private onOnline_(online); - private onRealtimeDisconnect_(); - private establishConnection_(); - /** - * @param {string} reason - */ - interrupt(reason: string): void; - /** - * @param {string} reason - */ - resume(reason: string): void; - private handleTimestamp_(timestamp); - private cancelSentTransactions_(); - /** - * @param {!string} pathString - * @param {Array.<*>=} query - * @private - */ - private onListenRevoked_(pathString, query?); - /** - * @param {!string} pathString - * @param {!string} queryId - * @return {{queries:Array., onComplete:function(string)}} - * @private - */ - private removeListen_(pathString, queryId); - private onAuthRevoked_(statusCode, explanation); - private onSecurityDebugPacket_(body); - private restoreState_(); - /** - * Sends client stats for first connection - * @private - */ - private sendConnectStats_(); - /** - * @return {boolean} - * @private - */ - private shouldReconnect_(); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/ReadonlyRestClient.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/ReadonlyRestClient.d.ts deleted file mode 100644 index 7db79f1c..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/ReadonlyRestClient.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { ServerActions } from './ServerActions'; -import { RepoInfo } from './RepoInfo'; -import { AuthTokenProvider } from './AuthTokenProvider'; -import { Query } from '../api/Query'; -/** - * An implementation of ServerActions that communicates with the server via REST requests. - * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full - * persistent connection (using WebSockets or long-polling) - */ -export declare class ReadonlyRestClient extends ServerActions { - private repoInfo_; - private onDataUpdate_; - private authTokenProvider_; - reportStats(stats: { - [k: string]: any; - }): void; - /** @private {function(...[*])} */ - private log_; - /** - * We don't actually need to track listens, except to prevent us calling an onComplete for a listen - * that's been removed. :-/ - * - * @private {!Object.} - */ - private listens_; - /** - * @param {!Query} query - * @param {?number=} tag - * @return {string} - * @private - */ - static getListenId_(query: Query, tag?: number | null): string; - /** - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param {AuthTokenProvider} authTokenProvider_ - * @implements {ServerActions} - */ - constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: any, c: boolean, d: number | null) => void, authTokenProvider_: AuthTokenProvider); - /** @inheritDoc */ - listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void; - /** @inheritDoc */ - unlisten(query: Query, tag: number | null): void; - /** @inheritDoc */ - refreshAuthToken(token: string): void; - /** - * Performs a REST request to the given path, with the provided query string parameters, - * and any auth credentials we have. - * - * @param {!string} pathString - * @param {!Object.} queryStringParameters - * @param {?function(?number, *=)} callback - * @private - */ - private restRequest_(pathString, queryStringParameters, callback); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/RepoManager.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/RepoManager.d.ts deleted file mode 100644 index a5084fdc..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/RepoManager.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseApp } from '@firebase/app-types'; -import { Repo } from './Repo'; -import './Repo_transaction'; -import { Database } from '../api/Database'; -import { RepoInfo } from './RepoInfo'; -/** - * Creates and caches Repo instances. - */ -export declare class RepoManager { - /** - * @private {!Object.>} - */ - private repos_; - /** - * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes). - * @private {boolean} - */ - private useRestClient_; - static getInstance(): RepoManager; - interrupt(): void; - resume(): void; - /** - * This function should only ever be called to CREATE a new database instance. - * - * @param {!FirebaseApp} app - * @return {!Database} - */ - databaseFromApp(app: FirebaseApp, url?: string): Database; - /** - * Remove the repo and make sure it is disconnected. - * - * @param {!Repo} repo - */ - deleteRepo(repo: Repo): void; - /** - * Ensures a repo doesn't already exist and then creates one using the - * provided app. - * - * @param {!RepoInfo} repoInfo The metadata about the Repo - * @param {!FirebaseApp} app - * @return {!Repo} The Repo object for the specified server / repoName. - */ - createRepo(repoInfo: RepoInfo, app: FirebaseApp): Repo; - /** - * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. - * @param {boolean} forceRestClient - */ - forceRestClient(forceRestClient: boolean): void; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/Repo_transaction.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/Repo_transaction.d.ts deleted file mode 100644 index adfdfdd6..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/Repo_transaction.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { DataSnapshot } from '../api/DataSnapshot'; -import { Path } from './util/Path'; -/** - * @enum {number} - */ -export declare enum TransactionStatus { - RUN = 0, - SENT = 1, - COMPLETED = 2, - SENT_NEEDS_ABORT = 3, - NEEDS_ABORT = 4, -} -declare module './Repo' { - interface Repo { - startTransaction(path: Path, transactionUpdate: (a: any) => void, onComplete: ((a: Error, b: boolean, c: DataSnapshot) => void) | null, applyLocally: boolean): void; - } -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/ServerActions.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/ServerActions.d.ts deleted file mode 100644 index 714bd27f..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/ServerActions.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Query } from '../api/Query'; -/** - * Interface defining the set of actions that can be performed against the Firebase server - * (basically corresponds to our wire protocol). - * - * @interface - */ -export declare abstract class ServerActions { - /** - * @param {!Query} query - * @param {function():string} currentHashFn - * @param {?number} tag - * @param {function(string, *)} onComplete - */ - abstract listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void; - /** - * Remove a listen. - * - * @param {!Query} query - * @param {?number} tag - */ - abstract unlisten(query: Query, tag: number | null): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - * @param {string=} hash - */ - put(pathString: string, data: any, onComplete?: (a: string, b: string) => void, hash?: string): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, ?string)} onComplete - * @param {string=} hash - */ - merge(pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void; - /** - * Refreshes the auth token for the current connection. - * @param {string} token The authentication token - */ - refreshAuthToken(token: string): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - onDisconnectPut(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - onDisconnectMerge(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @param {string} pathString - * @param {function(string, string)=} onComplete - */ - onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; - /** - * @param {Object.} stats - */ - reportStats(stats: { - [k: string]: any; - }): void; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/EventEmitter.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/EventEmitter.d.ts deleted file mode 100644 index c54bdf63..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/EventEmitter.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Base class to be used if you want to emit events. Call the constructor with - * the set of allowed event names. - */ -export declare abstract class EventEmitter { - private allowedEvents_; - private listeners_; - /** - * @param {!Array.} allowedEvents_ - */ - constructor(allowedEvents_: Array); - /** - * To be overridden by derived classes in order to fire an initial event when - * somebody subscribes for data. - * - * @param {!string} eventType - * @return {Array.<*>} Array of parameters to trigger initial event with. - */ - abstract getInitialEvent(eventType: string): any[]; - /** - * To be called by derived classes to trigger events. - * @param {!string} eventType - * @param {...*} var_args - */ - protected trigger(eventType: string, ...var_args: any[]): void; - on(eventType: string, callback: (a: any) => void, context: any): void; - off(eventType: string, callback: (a: any) => void, context: any): void; - private validateEventType_(eventType); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/OnlineMonitor.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/OnlineMonitor.d.ts deleted file mode 100644 index 9f23cdf6..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/OnlineMonitor.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { EventEmitter } from './EventEmitter'; -/** - * Monitors online state (as reported by window.online/offline events). - * - * The expectation is that this could have many false positives (thinks we are online - * when we're not), but no false negatives. So we can safely use it to determine when - * we definitely cannot reach the internet. - * - * @extends {EventEmitter} - */ -export declare class OnlineMonitor extends EventEmitter { - private online_; - static getInstance(): OnlineMonitor; - constructor(); - /** - * @param {!string} eventType - * @return {Array.} - */ - getInitialEvent(eventType: string): boolean[]; - /** - * @return {boolean} - */ - currentlyOnline(): boolean; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/Tree.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/Tree.d.ts deleted file mode 100644 index e58021d6..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/Tree.d.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { Path } from './Path'; -/** - * Node in a Tree. - */ -export declare class TreeNode { - children: { - [name: string]: TreeNode; - }; - childCount: number; - value: T | null; -} -/** - * A light-weight tree, traversable by path. Nodes can have both values and children. - * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty - * children. - */ -export declare class Tree { - private name_; - private parent_; - private node_; - /** - * @template T - * @param {string=} name_ Optional name of the node. - * @param {Tree=} parent_ Optional parent node. - * @param {TreeNode=} node_ Optional node to wrap. - */ - constructor(name_?: string, parent_?: Tree | null, node_?: TreeNode); - /** - * Returns a sub-Tree for the given path. - * - * @param {!(string|Path)} pathObj Path to look up. - * @return {!Tree.} Tree for path. - */ - subTree(pathObj: string | Path): Tree; - /** - * Returns the data associated with this tree node. - * - * @return {?T} The data or null if no data exists. - */ - getValue(): T | null; - /** - * Sets data to this tree node. - * - * @param {!T} value Value to set. - */ - setValue(value: T): void; - /** - * Clears the contents of the tree node (its value and all children). - */ - clear(): void; - /** - * @return {boolean} Whether the tree has any children. - */ - hasChildren(): boolean; - /** - * @return {boolean} Whether the tree is empty (no value or children). - */ - isEmpty(): boolean; - /** - * Calls action for each child of this tree node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - forEachChild(action: (tree: Tree) => void): void; - /** - * Does a depth-first traversal of this node's descendants, calling action for each one. - * - * @param {function(!Tree.)} action Action to be called for each child. - * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to - * false. - * @param {boolean=} childrenFirst Whether to call action on children before calling it on - * parent. - */ - forEachDescendant(action: (tree: Tree) => void, includeSelf?: boolean, childrenFirst?: boolean): void; - /** - * Calls action on each ancestor node. - * - * @param {function(!Tree.)} action Action to be called on each parent; return - * true to abort. - * @param {boolean=} includeSelf Whether to call action on this node as well. - * @return {boolean} true if the action callback returned true. - */ - forEachAncestor(action: (tree: Tree) => void, includeSelf?: boolean): boolean; - /** - * Does a depth-first traversal of this node's descendants. When a descendant with a value - * is found, action is called on it and traversal does not continue inside the node. - * Action is *not* called on this node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - forEachImmediateDescendantWithValue(action: (tree: Tree) => void): void; - /** - * @return {!Path} The path of this tree node, as a Path. - */ - path(): Path; - /** - * @return {string} The name of the tree node. - */ - name(): string; - /** - * @return {?Tree} The parent tree node, or null if this is the root of the tree. - */ - parent(): Tree | null; - /** - * Adds or removes this child from its parent based on whether it's empty or not. - * - * @private - */ - private updateParents_(); - /** - * Adds or removes the passed child to this tree node, depending on whether it's empty. - * - * @param {string} childName The name of the child to update. - * @param {!Tree.} child The child to update. - * @private - */ - private updateChild_(childName, child); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/VisibilityMonitor.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/VisibilityMonitor.d.ts deleted file mode 100644 index 20327138..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/util/VisibilityMonitor.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { EventEmitter } from './EventEmitter'; -/** - * @extends {EventEmitter} - */ -export declare class VisibilityMonitor extends EventEmitter { - private visible_; - static getInstance(): VisibilityMonitor; - constructor(); - /** - * @param {!string} eventType - * @return {Array.} - */ - getInitialEvent(eventType: string): boolean[]; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/QueryParams.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/QueryParams.d.ts deleted file mode 100644 index 206a6a48..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/QueryParams.d.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { NodeFilter } from './filter/NodeFilter'; -import { Index } from '../snap/indexes/Index'; -/** - * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a - * range to be returned for a particular location. It is assumed that validation of parameters is done at the - * user-facing API level, so it is not done here. - * @constructor - */ -export declare class QueryParams { - private limitSet_; - private startSet_; - private startNameSet_; - private endSet_; - private endNameSet_; - private limit_; - private viewFrom_; - private indexStartValue_; - private indexStartName_; - private indexEndValue_; - private indexEndName_; - private index_; - /** - * Wire Protocol Constants - * @const - * @enum {string} - * @private - */ - private static readonly WIRE_PROTOCOL_CONSTANTS_; - /** - * REST Query Constants - * @const - * @enum {string} - * @private - */ - private static readonly REST_QUERY_CONSTANTS_; - /** - * Default, empty query parameters - * @type {!QueryParams} - * @const - */ - static readonly DEFAULT: QueryParams; - /** - * @return {boolean} - */ - hasStart(): boolean; - /** - * @return {boolean} True if it would return from left. - */ - isViewFromLeft(): boolean; - /** - * Only valid to call if hasStart() returns true - * @return {*} - */ - getIndexStartValue(): any; - /** - * Only valid to call if hasStart() returns true. - * Returns the starting key name for the range defined by these query parameters - * @return {!string} - */ - getIndexStartName(): string; - /** - * @return {boolean} - */ - hasEnd(): boolean; - /** - * Only valid to call if hasEnd() returns true. - * @return {*} - */ - getIndexEndValue(): any; - /** - * Only valid to call if hasEnd() returns true. - * Returns the end key name for the range defined by these query parameters - * @return {!string} - */ - getIndexEndName(): string; - /** - * @return {boolean} - */ - hasLimit(): boolean; - /** - * @return {boolean} True if a limit has been set and it has been explicitly anchored - */ - hasAnchoredLimit(): boolean; - /** - * Only valid to call if hasLimit() returns true - * @return {!number} - */ - getLimit(): number; - /** - * @return {!Index} - */ - getIndex(): Index; - /** - * @return {!QueryParams} - * @private - */ - private copy_(); - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - limit(newLimit: number): QueryParams; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - limitToFirst(newLimit: number): QueryParams; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - limitToLast(newLimit: number): QueryParams; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - startAt(indexValue: any, key?: string | null): QueryParams; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - endAt(indexValue: any, key?: string | null): QueryParams; - /** - * @param {!Index} index - * @return {!QueryParams} - */ - orderBy(index: Index): QueryParams; - /** - * @return {!Object} - */ - getQueryObject(): Object; - /** - * @return {boolean} - */ - loadsAllData(): boolean; - /** - * @return {boolean} - */ - isDefault(): boolean; - /** - * @return {!NodeFilter} - */ - getNodeFilter(): NodeFilter; - /** - * Returns a set of REST query string parameters representing this query. - * - * @return {!Object.} query string parameters - */ - toRestQueryStringParameters(): { - [k: string]: any; - }; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/LimitedFilter.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/LimitedFilter.d.ts deleted file mode 100644 index 1bd0e053..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/LimitedFilter.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Node } from '../../snap/Node'; -import { NodeFilter } from './NodeFilter'; -import { Index } from '../../snap/indexes/Index'; -import { IndexedFilter } from './IndexedFilter'; -import { QueryParams } from '../QueryParams'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -/** - * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible - * - * @constructor - * @implements {NodeFilter} - */ -export declare class LimitedFilter implements NodeFilter { - /** - * @const - * @type {RangedFilter} - * @private - */ - private readonly rangedFilter_; - /** - * @const - * @type {!Index} - * @private - */ - private readonly index_; - /** - * @const - * @type {number} - * @private - */ - private readonly limit_; - /** - * @const - * @type {boolean} - * @private - */ - private readonly reverse_; - /** - * @param {!QueryParams} params - */ - constructor(params: QueryParams); - /** - * @inheritDoc - */ - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * @inheritDoc - */ - filtersNodes(): boolean; - /** - * @inheritDoc - */ - getIndexedFilter(): IndexedFilter; - /** - * @inheritDoc - */ - getIndex(): Index; - /** - * @param {!Node} snap - * @param {string} childKey - * @param {!Node} childSnap - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} changeAccumulator - * @return {!Node} - * @private - */ - private fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/NodeFilter.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/NodeFilter.d.ts deleted file mode 100644 index 7846f09a..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/NodeFilter.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Node } from '../../snap/Node'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -import { Index } from '../../snap/indexes/Index'; -/** - * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping - * track of any child changes. This class does not track value changes as value changes depend on more - * than just the node itself. Different kind of queries require different kind of implementations of this interface. - * @interface - */ -export interface NodeFilter { - /** - * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. - * The method expects an indexed snap. - * - * @param {!Node} snap - * @param {string} key - * @param {!Node} newChild - * @param {!Path} affectedPath - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} optChangeAccumulator - * @return {!Node} - */ - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * Update a node in full and output any resulting change from this complete update. - * - * @param {!Node} oldSnap - * @param {!Node} newSnap - * @param {?ChildChangeAccumulator} optChangeAccumulator - * @return {!Node} - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * Update the priority of the root node - * - * @param {!Node} oldSnap - * @param {!Node} newPriority - * @return {!Node} - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * Returns true if children might be filtered due to query criteria - * - * @return {boolean} - */ - filtersNodes(): boolean; - /** - * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. - * @return {!NodeFilter} - */ - getIndexedFilter(): NodeFilter; - /** - * Returns the index that this filter uses - * @return {!Index} - */ - getIndex(): Index; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/RangedFilter.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/RangedFilter.d.ts deleted file mode 100644 index 83de78e9..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/core/view/filter/RangedFilter.d.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { IndexedFilter } from './IndexedFilter'; -import { NamedNode, Node } from '../../../core/snap/Node'; -import { NodeFilter } from './NodeFilter'; -import { QueryParams } from '../QueryParams'; -import { Index } from '../../snap/indexes/Index'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -/** - * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node - * - * @constructor - * @implements {NodeFilter} - */ -export declare class RangedFilter implements NodeFilter { - /** - * @type {!IndexedFilter} - * @const - * @private - */ - private indexedFilter_; - /** - * @const - * @type {!Index} - * @private - */ - private index_; - /** - * @const - * @type {!NamedNode} - * @private - */ - private startPost_; - /** - * @const - * @type {!NamedNode} - * @private - */ - private endPost_; - /** - * @param {!QueryParams} params - */ - constructor(params: QueryParams); - /** - * @return {!NamedNode} - */ - getStartPost(): NamedNode; - /** - * @return {!NamedNode} - */ - getEndPost(): NamedNode; - /** - * @param {!NamedNode} node - * @return {boolean} - */ - matches(node: NamedNode): boolean; - /** - * @inheritDoc - */ - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * @inheritDoc - */ - filtersNodes(): boolean; - /** - * @inheritDoc - */ - getIndexedFilter(): IndexedFilter; - /** - * @inheritDoc - */ - getIndex(): Index; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - private static getStartPost_(params); - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - private static getEndPost_(params); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/nodePatches.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/nodePatches.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/nodePatches.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/BrowserPollConnection.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/BrowserPollConnection.d.ts deleted file mode 100644 index 6ddbf213..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/BrowserPollConnection.d.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { CountedSet } from '../core/util/CountedSet'; -import { PacketReceiver } from './polling/PacketReceiver'; -import { Transport } from './Transport'; -import { RepoInfo } from '../core/RepoInfo'; -export declare const FIREBASE_LONGPOLL_START_PARAM = "start"; -export declare const FIREBASE_LONGPOLL_CLOSE_COMMAND = "close"; -export declare const FIREBASE_LONGPOLL_COMMAND_CB_NAME = "pLPCommand"; -export declare const FIREBASE_LONGPOLL_DATA_CB_NAME = "pRTLPCB"; -export declare const FIREBASE_LONGPOLL_ID_PARAM = "id"; -export declare const FIREBASE_LONGPOLL_PW_PARAM = "pw"; -export declare const FIREBASE_LONGPOLL_SERIAL_PARAM = "ser"; -export declare const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = "cb"; -export declare const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg"; -export declare const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts"; -export declare const FIREBASE_LONGPOLL_DATA_PARAM = "d"; -export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = "disconn"; -export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe"; -/** - * This class manages a single long-polling connection. - * - * @constructor - * @implements {Transport} - */ -export declare class BrowserPollConnection implements Transport { - connId: string; - repoInfo: RepoInfo; - transportSessionId: string; - lastSessionId: string; - bytesSent: number; - bytesReceived: number; - urlFn: (params: object) => string; - scriptTagHolder: FirebaseIFrameScriptHolder; - myDisconnFrame: HTMLIFrameElement; - curSegmentNum: number; - myPacketOrderer: PacketReceiver; - id: string; - password: string; - private log_; - private stats_; - private everConnected_; - private isClosed_; - private connectTimeoutTimer_; - private onDisconnect_; - /** - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing - * transport session - * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a - * connection previously - */ - constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); - /** - * - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - open(onMessage: (msg: Object) => void, onDisconnect: (a?: boolean) => void): void; - /** - * Call this when a handshake has completed successfully and we want to consider the connection established - */ - start(): void; - private static forceAllow_; - /** - * Forces long polling to be considered as a potential transport - */ - static forceAllow(): void; - private static forceDisallow_; - /** - * Forces longpolling to not be considered as a potential transport - */ - static forceDisallow(): void; - static isAvailable(): boolean; - /** - * No-op for polling - */ - markConnectionHealthy(): void; - /** - * Stops polling and cleans up the iframe - * @private - */ - private shutdown_(); - /** - * Triggered when this transport is closed - * @private - */ - private onClosed_(); - /** - * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server - * that we've left. - */ - close(): void; - /** - * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then - * broken into chunks (since URLs have a small maximum length). - * @param {!Object} data The JSON data to transmit. - */ - send(data: Object): void; - /** - * This is how we notify the server that we're leaving. - * We aren't able to send requests with DHTML on a window close event, but we can - * trigger XHR requests in some browsers (everything but Opera basically). - * @param {!string} id - * @param {!string} pw - */ - addDisconnectPingFrame(id: string, pw: string): void; - /** - * Used to track the bytes received by this client - * @param {*} args - * @private - */ - private incrementIncomingBytes_(args); -} -export interface IFrameElement extends HTMLIFrameElement { - doc: Document; -} -/********************************************************************************************* - * A wrapper around an iframe that is used as a long-polling script holder. - * @constructor - *********************************************************************************************/ -export declare class FirebaseIFrameScriptHolder { - onDisconnect: () => void; - urlFn: (a: object) => string; - /** - * @type {CountedSet.} - */ - outstandingRequests: CountedSet; - pendingSegs: { - seg: number; - ts: number; - d: any; - }[]; - currentSerial: number; - sendNewPolls: boolean; - uniqueCallbackIdentifier: number; - myIFrame: IFrameElement; - alive: boolean; - myID: string; - myPW: string; - commandCB: (command: string, ...args: any[]) => void; - onMessageCB: (...args: any[]) => void; - /** - * @param commandCB - The callback to be called when control commands are recevied from the server. - * @param onMessageCB - The callback to be triggered when responses arrive from the server. - * @param onDisconnect - The callback to be triggered when this tag holder is closed - * @param urlFn - A function that provides the URL of the endpoint to send data to. - */ - constructor(commandCB: (command: string, ...args: any[]) => void, onMessageCB: (...args: any[]) => void, onDisconnect: () => void, urlFn: (a: object) => string); - /** - * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can - * actually use. - * @private - * @return {Element} - */ - private static createIFrame_(); - /** - * Cancel all outstanding queries and remove the frame. - */ - close(): void; - /** - * Actually start the long-polling session by adding the first script tag(s) to the iframe. - * @param {!string} id - The ID of this connection - * @param {!string} pw - The password for this connection - */ - startLongPoll(id: string, pw: string): void; - /** - * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't - * too many outstanding requests and we are still alive. - * - * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if - * needed. - */ - private newRequest_(); - /** - * Queue a packet for transmission to the server. - * @param segnum - A sequential id for this packet segment used for reassembly - * @param totalsegs - The total number of segments in this packet - * @param data - The data for this segment. - */ - enqueueSegment(segnum: number, totalsegs: number, data: any): void; - /** - * Add a script tag for a regular long-poll request. - * @param {!string} url - The URL of the script tag. - * @param {!number} serial - The serial number of the request. - * @private - */ - private addLongPollTag_(url, serial); - /** - * Add an arbitrary script tag to the iframe. - * @param {!string} url - The URL for the script tag source. - * @param {!function()} loadCB - A callback to be triggered once the script has loaded. - */ - addTag(url: string, loadCB: () => void): void; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Connection.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Connection.d.ts deleted file mode 100644 index 62f5d648..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Connection.d.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { RepoInfo } from '../core/RepoInfo'; -/** - * Creates a new real-time connection to the server using whichever method works - * best in the current browser. - * - * @constructor - */ -export declare class Connection { - id: string; - private repoInfo_; - private onMessage_; - private onReady_; - private onDisconnect_; - private onKill_; - lastSessionId: string; - connectionCount: number; - pendingDataMessages: any[]; - sessionId: string; - private conn_; - private healthyTimeout_; - private isHealthy_; - private log_; - private primaryResponsesRequired_; - private rx_; - private secondaryConn_; - private secondaryResponsesRequired_; - private state_; - private transportManager_; - private tx_; - /** - * @param {!string} id - an id for this connection - * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to - * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives - * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages. - * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost - * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down. - * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server - */ - constructor(id: string, repoInfo_: RepoInfo, onMessage_: (a: Object) => void, onReady_: (a: number, b: string) => void, onDisconnect_: () => void, onKill_: (a: string) => void, lastSessionId?: string); - /** - * Starts a connection attempt - * @private - */ - private start_(); - /** - * @return {!string} - * @private - */ - private nextTransportId_(); - private disconnReceiver_(conn); - private connReceiver_(conn); - /** - * - * @param {Object} dataMsg An arbitrary data message to be sent to the server - */ - sendRequest(dataMsg: object): void; - tryCleanupConnection(): void; - private onSecondaryControl_(controlData); - private onSecondaryMessageReceived_(parsedData); - private upgradeIfSecondaryHealthy_(); - private proceedWithUpgrade_(); - private onPrimaryMessageReceived_(parsedData); - private onDataMessage_(message); - private onPrimaryResponse_(); - private onControl_(controlData); - /** - * - * @param {Object} handshake The handshake data returned from the server - * @private - */ - private onHandshake_(handshake); - private tryStartUpgrade_(); - private startUpgrade_(conn); - private onReset_(host); - private onConnectionEstablished_(conn, timestamp); - private sendPingOnPrimaryIfNecessary_(); - private onSecondaryConnectionLost_(); - /** - * - * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if - * we should flush the host cache - * @private - */ - private onConnectionLost_(everConnected); - /** - * - * @param {string} reason - * @private - */ - private onConnectionShutdown_(reason); - private sendData_(data); - /** - * Cleans up this connection, calling the appropriate callbacks - */ - close(): void; - /** - * - * @private - */ - private closeConnections_(); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Transport.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Transport.d.ts deleted file mode 100644 index e3bad3dc..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/Transport.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { RepoInfo } from '../core/RepoInfo'; -export interface TransportConstructor { - new (connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string): Transport; - isAvailable: () => boolean; - responsesRequiredToBeHealthy?: number; - healthyTimeout?: number; -} -export declare abstract class Transport { - /** - * Bytes received since connection started. - * @type {number} - */ - abstract bytesReceived: number; - /** - * Bytes sent since connection started. - * @type {number} - */ - abstract bytesSent: number; - /** - * An identifier for this connection, used for logging - * @type {string} - */ - abstract connId: string; - /** - * - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @interface - */ - constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); - /** - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - abstract open(onMessage: (a: Object) => void, onDisconnect: (a?: boolean) => void): void; - abstract start(): void; - abstract close(): void; - /** - * @param {!Object} data The JSON data to transmit - */ - abstract send(data: Object): void; - abstract markConnectionHealthy(): void; - abstract markConnectionHealthy(): void; -} -export interface TransportConstructor { - new (connId: string, RepoInfo: any, transportSessionId?: string, lastSessionId?: string): any; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/TransportManager.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/TransportManager.d.ts deleted file mode 100644 index fa8ca042..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/TransportManager.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { BrowserPollConnection } from './BrowserPollConnection'; -import { WebSocketConnection } from './WebSocketConnection'; -import { TransportConstructor } from './Transport'; -import { RepoInfo } from '../core/RepoInfo'; -/** - * Currently simplistic, this class manages what transport a Connection should use at various stages of its - * lifecycle. - * - * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if - * they are available. - * @constructor - */ -export declare class TransportManager { - private transports_; - /** - * @const - * @type {!Array.} - */ - static readonly ALL_TRANSPORTS: (typeof BrowserPollConnection | typeof WebSocketConnection)[]; - /** - * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to - */ - constructor(repoInfo: RepoInfo); - /** - * @param {!RepoInfo} repoInfo - * @private - */ - private initTransports_(repoInfo); - /** - * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the - * initial transport to use - */ - initialTransport(): TransportConstructor; - /** - * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next - * transport, or null - */ - upgradeTransport(): TransportConstructor | null; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/WebSocketConnection.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/WebSocketConnection.d.ts deleted file mode 100644 index 76c21237..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/WebSocketConnection.d.ts +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { RepoInfo } from '../core/RepoInfo'; -import { Transport } from './Transport'; -export declare function setWebSocketImpl(impl: any): void; -/** - * Create a new websocket connection with the given callbacks. - * @constructor - * @implements {Transport} - */ -export declare class WebSocketConnection implements Transport { - connId: string; - keepaliveTimer: number | null; - frames: string[] | null; - totalFrames: number; - bytesSent: number; - bytesReceived: number; - connURL: string; - onDisconnect: (a?: boolean) => void; - onMessage: (msg: Object) => void; - mySock: any | null; - private log_; - private stats_; - private everConnected_; - private isClosed_; - /** - * @param {string} connId identifier for this transport - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - */ - constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); - /** - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @return {string} connection url - * @private - */ - private static connectionURL_(repoInfo, transportSessionId?, lastSessionId?); - /** - * - * @param onMessage Callback when messages arrive - * @param onDisconnect Callback with connection lost. - */ - open(onMessage: (msg: Object) => void, onDisconnect: (a?: boolean) => void): void; - /** - * No-op for websockets, we don't need to do anything once the connection is confirmed as open - */ - start(): void; - static forceDisallow_: Boolean; - static forceDisallow(): void; - static isAvailable(): boolean; - /** - * Number of response before we consider the connection "healthy." - * @type {number} - */ - static responsesRequiredToBeHealthy: number; - /** - * Time to wait for the connection te become healthy before giving up. - * @type {number} - */ - static healthyTimeout: number; - /** - * Returns true if we previously failed to connect with this transport. - * @return {boolean} - */ - static previouslyFailed(): boolean; - markConnectionHealthy(): void; - private appendFrame_(data); - /** - * @param {number} frameCount The number of frames we are expecting from the server - * @private - */ - private handleNewFrameCount_(frameCount); - /** - * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 - * @param {!String} data - * @return {?String} Any remaining data to be process, or null if there is none - * @private - */ - private extractFrameCount_(data); - /** - * Process a websocket frame that has arrived from the server. - * @param mess The frame data - */ - handleIncomingFrame(mess: { - [k: string]: any; - }): void; - /** - * Send a message to the server - * @param {Object} data The JSON object to transmit - */ - send(data: Object): void; - private shutdown_(); - private onClosed_(); - /** - * External-facing close handler. - * Close the websocket and kill the connection. - */ - close(): void; - /** - * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after - * the last activity. - */ - resetKeepAlive(): void; - /** - * Send a string over the websocket. - * - * @param {string} str String to send. - * @private - */ - private sendString_(str); -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/polling/PacketReceiver.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/polling/PacketReceiver.d.ts deleted file mode 100644 index 734d6b01..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/src/realtime/polling/PacketReceiver.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This class ensures the packets from the server arrive in order - * This class takes data from the server and ensures it gets passed into the callbacks in order. - * @constructor - */ -export declare class PacketReceiver { - private onMessage_; - pendingResponses: any[]; - currentResponseNum: number; - closeAfterResponse: number; - onClose: (() => void) | null; - /** - * @param onMessage_ - */ - constructor(onMessage_: (a: Object) => void); - closeAfter(responseNum: number, callback: () => void): void; - /** - * Each message from the server comes with a response number, and an array of data. The responseNumber - * allows us to ensure that we process them in the right order, since we can't be guaranteed that all - * browsers will respond in the same order as the requests we sent - * @param {number} requestNum - * @param {Array} data - */ - handleResponse(requestNum: number, data: any[]): void; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/browser/crawler_support.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/browser/crawler_support.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/browser/crawler_support.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/compound_write.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/compound_write.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/compound_write.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/connection.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/connection.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/connection.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/database.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/database.test.d.ts deleted file mode 100644 index 872ffe6c..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/database.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -import '../index'; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/datasnapshot.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/datasnapshot.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/datasnapshot.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/EventAccumulator.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/EventAccumulator.d.ts deleted file mode 100644 index 591e1926..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/EventAccumulator.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export declare const EventAccumulatorFactory: { - waitsForCount: (maxCount: any) => EventAccumulator; -}; -export declare class EventAccumulator { - condition: Function; - eventData: any[]; - promise: any; - resolve: any; - reject: any; - private onResetFxn; - private onEventFxn; - constructor(condition: Function); - addEvent(eventData?: any): void; - reset(condition?: Function): void; - onEvent(cb: Function): void; - onReset(cb: Function): void; - _testCondition(): any; -} diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/events.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/events.d.ts deleted file mode 100644 index 24f73855..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/events.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * A set of functions to clean up event handlers. - * @type {function()} - */ -export declare let eventCleanupHandlers: any[]; -/** Clean up outstanding event handlers */ -export declare function eventCleanup(): void; -/** - * Creates a struct which waits for many events. - * @param {Array} pathAndEvents an array of tuples of [Firebase, [event type strings]] - * @param {string=} helperName - * @return {{waiter: waiter, watchesInitializedWaiter: watchesInitializedWaiter, unregister: unregister, addExpectedEvents: addExpectedEvents}} - */ -export declare function eventTestHelper(pathAndEvents: any, helperName?: any): { - promise: Promise<{}>; - initPromise: Promise<{}>; - waiter: () => boolean; - watchesInitializedWaiter: () => boolean; - unregister: () => void; - addExpectedEvents: (moreEvents: any) => void; -}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/util.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/util.d.ts deleted file mode 100644 index bde3f4a7..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/helpers/util.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import '../../index'; -import { Reference } from '../../src/api/Reference'; -import { Query } from '../../src/api/Query'; -export declare const TEST_PROJECT: any; -export declare const DATABASE_ADDRESS: any; -export declare const DATABASE_URL: any; -/** - * Fake Firebase App Authentication functions for testing. - * @param {!FirebaseApp} app - * @return {!FirebaseApp} - */ -export declare function patchFakeAuthFunctions(app: any): any; -export declare function createTestApp(): FirebaseApp; -/** - * Gets or creates a root node to the test namespace. All calls sharing the - * value of opt_i will share an app context. - * @param {number=} i - * @param {string=} ref - * @return {Reference} - */ -export declare function getRootNode(i?: number, ref?: string): any; -/** - * Create multiple refs to the same top level - * push key - each on it's own Firebase.Context. - * @param {int=} numNodes - * @return {Reference|Array} - */ -export declare function getRandomNode(numNodes?: any): Reference | Array; -export declare function getQueryValue(query: Query): Promise; -export declare function pause(milliseconds: number): Promise<{}>; -export declare function getPath(query: Query): string; -export declare function shuffle(arr: any, randFn?: () => number): void; -export declare function testAuthTokenProvider(app: any): { - setToken: (token: any) => Promise; - setNextToken: (token: any) => void; -}; -export declare function getFreshRepo(path: any): any; -export declare function getFreshRepoFromReference(ref: any): any; -export declare function getSnap(path: any): any; -export declare function getVal(path: any): any; -export declare function canCreateExtraConnections(): boolean; -export declare function buildObjFromKey(key: any): {}; -export declare function testRepoInfo(url: any): RepoInfo; -export declare function repoInfoForConnectionTest(): RepoInfo; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/info.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/info.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/info.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/node.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/node.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/node.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/order.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/order.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/order.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/order_by.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/order_by.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/order_by.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/path.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/path.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/path.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/promise.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/promise.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/promise.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/query.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/query.test.d.ts deleted file mode 100644 index 1828cc2d..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/query.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -import '../src/core/snap/ChildrenNode'; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/repoinfo.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/repoinfo.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/repoinfo.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/sortedmap.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/sortedmap.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/sortedmap.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/sparsesnapshottree.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/sparsesnapshottree.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/sparsesnapshottree.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/packages/database/test/transaction.test.d.ts b/functions/node_modules/@firebase/database/dist/packages/database/test/transaction.test.d.ts deleted file mode 100644 index 872ffe6c..00000000 --- a/functions/node_modules/@firebase/database/dist/packages/database/test/transaction.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -import '../index'; diff --git a/functions/node_modules/@firebase/database/dist/src/api/DataSnapshot.d.ts b/functions/node_modules/@firebase/database/dist/src/api/DataSnapshot.d.ts deleted file mode 100644 index 54df8389..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/DataSnapshot.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Node } from '../core/snap/Node'; -import { Reference } from './Reference'; -import { Index } from '../core/snap/indexes/Index'; -/** - * Class representing a firebase data snapshot. It wraps a SnapshotNode and - * surfaces the public methods (val, forEach, etc.) we want to expose. - */ -export declare class DataSnapshot { - private readonly node_; - private readonly ref_; - private readonly index_; - /** - * @param {!Node} node_ A SnapshotNode to wrap. - * @param {!Reference} ref_ The ref of the location this snapshot came from. - * @param {!Index} index_ The iteration order for this snapshot - */ - constructor(node_: Node, ref_: Reference, index_: Index); - /** - * Retrieves the snapshot contents as JSON. Returns null if the snapshot is - * empty. - * - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - val(): any; - /** - * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting - * the entire node contents. - * @return {*} JSON representation of the DataSnapshot contents, or null if empty. - */ - exportVal(): any; - toJSON(): any; - /** - * Returns whether the snapshot contains a non-null value. - * - * @return {boolean} Whether the snapshot contains a non-null value, or is empty. - */ - exists(): boolean; - /** - * Returns a DataSnapshot of the specified child node's contents. - * - * @param {!string} childPathString Path to a child. - * @return {!DataSnapshot} DataSnapshot for child node. - */ - child(childPathString: string): DataSnapshot; - /** - * Returns whether the snapshot contains a child at the specified path. - * - * @param {!string} childPathString Path to a child. - * @return {boolean} Whether the child exists. - */ - hasChild(childPathString: string): boolean; - /** - * Returns the priority of the object, or null if no priority was set. - * - * @return {string|number|null} The priority. - */ - getPriority(): string | number | null; - /** - * Iterates through child nodes and calls the specified action for each one. - * - * @param {function(!DataSnapshot)} action Callback function to be called - * for each child. - * @return {boolean} True if forEach was canceled by action returning true for - * one of the child nodes. - */ - forEach(action: (d: DataSnapshot) => boolean | void): boolean; - /** - * Returns whether this DataSnapshot has children. - * @return {boolean} True if the DataSnapshot contains 1 or more child nodes. - */ - hasChildren(): boolean; - readonly key: string; - /** - * Returns the number of children for this DataSnapshot. - * @return {number} The number of children that this DataSnapshot contains. - */ - numChildren(): number; - /** - * @return {Reference} The Firebase reference for the location this snapshot's data came from. - */ - getRef(): Reference; - readonly ref: Reference; -} diff --git a/functions/node_modules/@firebase/database/dist/src/api/Database.d.ts b/functions/node_modules/@firebase/database/dist/src/api/Database.d.ts deleted file mode 100644 index c0543fd4..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/Database.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { Reference } from './Reference'; -import { Repo } from '../core/Repo'; -import { FirebaseApp } from '@firebase/app-types'; -import { FirebaseService } from '@firebase/app-types/private'; -/** - * Class representing a firebase database. - * @implements {FirebaseService} - */ -export declare class Database implements FirebaseService { - private repo_; - INTERNAL: DatabaseInternals; - private root_; - static readonly ServerValue: { - TIMESTAMP: { - '.sv': string; - }; - }; - /** - * The constructor should not be called by users of our public API. - * @param {!Repo} repo_ - */ - constructor(repo_: Repo); - readonly app: FirebaseApp; - /** - * Returns a reference to the root or to the path specified in the provided - * argument. - - * @param {string|Reference=} path The relative string path or an existing - * Reference to a database location. - * @throws If a Reference is provided, throws if it does not belong to the - * same project. - * @return {!Reference} Firebase reference. - **/ - ref(path?: string): Reference; - ref(path?: Reference): Reference; - /** - * Returns a reference to the root or the path specified in url. - * We throw a exception if the url is not in the same domain as the - * current repo. - * @param {string} url - * @return {!Reference} Firebase reference. - */ - refFromURL(url: string): Reference; - /** - * @param {string} apiName - */ - private checkDeleted_(apiName); - goOffline(): void; - goOnline(): void; -} -export declare class DatabaseInternals { - database: Database; - /** @param {!Database} database */ - constructor(database: Database); - /** @return {Promise} */ - delete(): Promise; -} diff --git a/functions/node_modules/@firebase/database/dist/src/api/Query.d.ts b/functions/node_modules/@firebase/database/dist/src/api/Query.d.ts deleted file mode 100644 index cc59f80c..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/Query.d.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { Path } from '../core/util/Path'; -import { Repo } from '../core/Repo'; -import { QueryParams } from '../core/view/QueryParams'; -import { Reference } from './Reference'; -import { DataSnapshot } from './DataSnapshot'; -export interface SnapshotCallback { - (a: DataSnapshot, b?: string): any; -} -/** - * A Query represents a filter to be applied to a firebase location. This object purely represents the - * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js. - * - * Since every Firebase reference is a query, Firebase inherits from this object. - */ -export declare class Query { - repo: Repo; - path: Path; - private queryParams_; - private orderByCalled_; - static __referenceConstructor: new (repo: Repo, path: Path) => Query; - constructor(repo: Repo, path: Path, queryParams_: QueryParams, orderByCalled_: boolean); - /** - * Validates start/end values for queries. - * @param {!QueryParams} params - * @private - */ - private static validateQueryEndpoints_(params); - /** - * Validates that limit* has been called with the correct combination of parameters - * @param {!QueryParams} params - * @private - */ - private static validateLimit_(params); - /** - * Validates that no other order by call has been made - * @param {!string} fnName - * @private - */ - private validateNoPreviousOrderByCall_(fnName); - /** - * @return {!QueryParams} - */ - getQueryParams(): QueryParams; - /** - * @return {!Reference} - */ - getRef(): Reference; - /** - * @param {!string} eventType - * @param {!function(DataSnapshot, string=)} callback - * @param {(function(Error)|Object)=} cancelCallbackOrContext - * @param {Object=} context - * @return {!function(DataSnapshot, string=)} - */ - on(eventType: string, callback: SnapshotCallback, cancelCallbackOrContext?: ((a: Error) => any) | Object, context?: Object): SnapshotCallback; - /** - * @param {!function(!DataSnapshot)} callback - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - protected onValueEvent(callback: (a: DataSnapshot) => void, cancelCallback: ((a: Error) => void) | null, context: Object | null): void; - /** - * @param {!Object.} callbacks - * @param {?function(Error)} cancelCallback - * @param {?Object} context - * @protected - */ - onChildEvent(callbacks: { - [k: string]: SnapshotCallback; - }, cancelCallback: ((a: Error) => any) | null, context: Object | null): void; - /** - * @param {string=} eventType - * @param {(function(!DataSnapshot, ?string=))=} callback - * @param {Object=} context - */ - off(eventType?: string, callback?: SnapshotCallback, context?: Object): void; - /** - * Attaches a listener, waits for the first event, and then removes the listener - * @param {!string} eventType - * @param {!function(!DataSnapshot, string=)} userCallback - * @param cancelOrContext - * @param context - * @return {!firebase.Promise} - */ - once(eventType: string, userCallback?: SnapshotCallback, cancelOrContext?: ((a: Error) => void) | Object, context?: Object): Promise; - /** - * Set a limit and anchor it to the start of the window. - * @param {!number} limit - * @return {!Query} - */ - limitToFirst(limit: number): Query; - /** - * Set a limit and anchor it to the end of the window. - * @param {!number} limit - * @return {!Query} - */ - limitToLast(limit: number): Query; - /** - * Given a child path, return a new query ordered by the specified grandchild path. - * @param {!string} path - * @return {!Query} - */ - orderByChild(path: string): Query; - /** - * Return a new query ordered by the KeyIndex - * @return {!Query} - */ - orderByKey(): Query; - /** - * Return a new query ordered by the PriorityIndex - * @return {!Query} - */ - orderByPriority(): Query; - /** - * Return a new query ordered by the ValueIndex - * @return {!Query} - */ - orderByValue(): Query; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - startAt(value?: number | string | boolean | null, name?: string | null): Query; - /** - * @param {number|string|boolean|null} value - * @param {?string=} name - * @return {!Query} - */ - endAt(value?: number | string | boolean | null, name?: string | null): Query; - /** - * Load the selection of children with exactly the specified value, and, optionally, - * the specified name. - * @param {number|string|boolean|null} value - * @param {string=} name - * @return {!Query} - */ - equalTo(value: number | string | boolean | null, name?: string): Query; - /** - * @return {!string} URL for this location. - */ - toString(): string; - toJSON(): string; - /** - * An object representation of the query parameters used by this Query. - * @return {!Object} - */ - queryObject(): Object; - /** - * @return {!string} - */ - queryIdentifier(): string; - /** - * Return true if this query and the provided query are equivalent; otherwise, return false. - * @param {Query} other - * @return {boolean} - */ - isEqual(other: Query): boolean; - /** - * Helper used by .on and .once to extract the context and or cancel arguments. - * @param {!string} fnName The function name (on or once) - * @param {(function(Error)|Object)=} cancelOrContext - * @param {Object=} context - * @return {{cancel: ?function(Error), context: ?Object}} - * @private - */ - private static getCancelAndContextArgs_(fnName, cancelOrContext?, context?); - readonly ref: Reference; -} diff --git a/functions/node_modules/@firebase/database/dist/src/api/Reference.d.ts b/functions/node_modules/@firebase/database/dist/src/api/Reference.d.ts deleted file mode 100644 index d4b1492b..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/Reference.d.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { OnDisconnect } from './onDisconnect'; -import { TransactionResult } from './TransactionResult'; -import { Query } from './Query'; -import { Repo } from '../core/Repo'; -import { Path } from '../core/util/Path'; -import { Database } from './Database'; -import { DataSnapshot } from './DataSnapshot'; -export interface ReferenceConstructor { - new (repo: Repo, path: Path): Reference; -} -export declare class Reference extends Query { - then: (a?: any) => Promise; - catch: (a?: Error) => Promise; - /** - * Call options: - * new Reference(Repo, Path) or - * new Reference(url: string, string|RepoManager) - * - * Externally - this is the firebase.database.Reference type. - * - * @param {!Repo} repo - * @param {(!Path)} path - * @extends {Query} - */ - constructor(repo: Repo, path: Path); - /** @return {?string} */ - getKey(): string | null; - /** - * @param {!(string|Path)} pathString - * @return {!Reference} - */ - child(pathString: string | Path): Reference; - /** @return {?Reference} */ - getParent(): Reference | null; - /** @return {!Reference} */ - getRoot(): Reference; - /** @return {!Database} */ - databaseProp(): Database; - /** - * @param {*} newVal - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - set(newVal: any, onComplete?: (a: Error | null) => void): Promise; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - update(objectToMerge: Object, onComplete?: (a: Error | null) => void): Promise; - /** - * @param {*} newVal - * @param {string|number|null} newPriority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - setWithPriority(newVal: any, newPriority: string | number | null, onComplete?: (a: Error | null) => void): Promise; - /** - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - remove(onComplete?: (a: Error | null) => void): Promise; - /** - * @param {function(*):*} transactionUpdate - * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete - * @param {boolean=} applyLocally - * @return {!Promise} - */ - transaction(transactionUpdate: (a: any) => any, onComplete?: (a: Error | null, b: boolean, c: DataSnapshot | null) => void, applyLocally?: boolean): Promise; - /** - * @param {string|number|null} priority - * @param {function(?Error)=} onComplete - * @return {!Promise} - */ - setPriority(priority: string | number | null, onComplete?: (a: Error | null) => void): Promise; - /** - * @param {*=} value - * @param {function(?Error)=} onComplete - * @return {!Reference} - */ - push(value?: any, onComplete?: (a: Error | null) => void): Reference; - /** - * @return {!OnDisconnect} - */ - onDisconnect(): OnDisconnect; - readonly database: Database; - readonly key: string | null; - readonly parent: Reference | null; - readonly root: Reference; -} diff --git a/functions/node_modules/@firebase/database/dist/src/api/TransactionResult.d.ts b/functions/node_modules/@firebase/database/dist/src/api/TransactionResult.d.ts deleted file mode 100644 index e2604b33..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/TransactionResult.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { DataSnapshot } from './DataSnapshot'; -export declare class TransactionResult { - committed: boolean; - snapshot: DataSnapshot; - /** - * A type for the resolve value of Firebase.transaction. - * @constructor - * @dict - * @param {boolean} committed - * @param {DataSnapshot} snapshot - */ - constructor(committed: boolean, snapshot: DataSnapshot); - toJSON(): object; -} diff --git a/functions/node_modules/@firebase/database/dist/src/api/internal.d.ts b/functions/node_modules/@firebase/database/dist/src/api/internal.d.ts deleted file mode 100644 index 1d7f9d92..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/internal.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Reference } from './Reference'; -/** - * INTERNAL methods for internal-use only (tests, etc.). - * - * Customers shouldn't use these or else should be aware that they could break at any time. - * - * @const - */ -export declare const forceLongPolling: () => void; -export declare const forceWebSockets: () => void; -export declare const isWebSocketsAvailable: () => boolean; -export declare const setSecurityDebugCallback: (ref: Reference, callback: (a: Object) => void) => void; -export declare const stats: (ref: Reference, showDelta?: boolean) => void; -export declare const statsIncrementCounter: (ref: Reference, metric: string) => void; -export declare const dataUpdateCount: (ref: Reference) => number; -export declare const interceptServerData: (ref: Reference, callback: (a: string, b: any) => void) => void; diff --git a/functions/node_modules/@firebase/database/dist/src/api/onDisconnect.d.ts b/functions/node_modules/@firebase/database/dist/src/api/onDisconnect.d.ts deleted file mode 100644 index a476a1eb..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/onDisconnect.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Repo } from '../core/Repo'; -import { Path } from '../core/util/Path'; -/** - * @constructor - */ -export declare class OnDisconnect { - private repo_; - private path_; - /** - * @param {!Repo} repo_ - * @param {!Path} path_ - */ - constructor(repo_: Repo, path_: Path); - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - cancel(onComplete?: (a: Error | null) => void): Promise; - /** - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - remove(onComplete?: (a: Error | null) => void): Promise; - /** - * @param {*} value - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - set(value: any, onComplete?: (a: Error | null) => void): Promise; - /** - * @param {*} value - * @param {number|string|null} priority - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - setWithPriority(value: any, priority: number | string | null, onComplete?: (a: Error | null) => void): Promise; - /** - * @param {!Object} objectToMerge - * @param {function(?Error)=} onComplete - * @return {!firebase.Promise} - */ - update(objectToMerge: object, onComplete?: (a: Error | null) => void): Promise; -} diff --git a/functions/node_modules/@firebase/database/dist/src/api/test_access.d.ts b/functions/node_modules/@firebase/database/dist/src/api/test_access.d.ts deleted file mode 100644 index 347e6203..00000000 --- a/functions/node_modules/@firebase/database/dist/src/api/test_access.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { RepoInfo } from '../core/RepoInfo'; -import { PersistentConnection } from '../core/PersistentConnection'; -import { Connection } from '../realtime/Connection'; -import { Query } from './Query'; -export declare const DataConnection: typeof PersistentConnection; -export declare const RealTimeConnection: typeof Connection; -/** - * @param {function(): string} newHash - * @return {function()} - */ -export declare const hijackHash: (newHash: () => string) => () => void; -/** - * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined} - */ -export declare const ConnectionTarget: typeof RepoInfo; -/** - * @param {!Query} query - * @return {!string} - */ -export declare const queryIdentifier: (query: Query) => string; -/** - * @param {!Query} firebaseRef - * @return {!Object} - */ -export declare const listens: (firebaseRef: Query) => any; -/** - * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection. - * - * @param {boolean} forceRestClient - */ -export declare const forceRestClient: (forceRestClient: boolean) => void; diff --git a/functions/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts b/functions/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts deleted file mode 100644 index c735829e..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/AuthTokenProvider.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseApp } from '@firebase/app-types'; -import { FirebaseAuthTokenData } from '@firebase/app-types/private'; -/** - * Abstraction around FirebaseApp's token fetching capabilities. - */ -export declare class AuthTokenProvider { - private app_; - /** - * @param {!FirebaseApp} app_ - */ - constructor(app_: FirebaseApp); - /** - * @param {boolean} forceRefresh - * @return {!Promise} - */ - getToken(forceRefresh: boolean): Promise; - addTokenChangeListener(listener: (token: string | null) => void): void; - removeTokenChangeListener(listener: (token: string | null) => void): void; - notifyForInvalidToken(): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts b/functions/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts deleted file mode 100644 index eb0789c9..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/CompoundWrite.d.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { ImmutableTree } from './util/ImmutableTree'; -import { Path } from './util/Path'; -import { Node, NamedNode } from './snap/Node'; -/** - * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with - * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write - * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write - * to reflect the write added. - * - * @constructor - * @param {!ImmutableTree.} writeTree - */ -export declare class CompoundWrite { - private writeTree_; - constructor(writeTree_: ImmutableTree); - /** - * @type {!CompoundWrite} - */ - static Empty: CompoundWrite; - /** - * @param {!Path} path - * @param {!Node} node - * @return {!CompoundWrite} - */ - addWrite(path: Path, node: Node): CompoundWrite; - /** - * @param {!Path} path - * @param {!Object.} updates - * @return {!CompoundWrite} - */ - addWrites(path: Path, updates: { - [name: string]: Node; - }): CompoundWrite; - /** - * Will remove a write at the given path and deeper paths. This will not modify a write at a higher - * location, which must be removed by calling this method with that path. - * - * @param {!Path} path The path at which a write and all deeper writes should be removed - * @return {!CompoundWrite} The new CompoundWrite with the removed path - */ - removeWrite(path: Path): CompoundWrite; - /** - * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be - * considered "complete". - * - * @param {!Path} path The path to check for - * @return {boolean} Whether there is a complete write at that path - */ - hasCompleteWrite(path: Path): boolean; - /** - * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate - * writes from deeper paths, but will return child nodes from a more shallow path. - * - * @param {!Path} path The path to get a complete write - * @return {?Node} The node if complete at that path, or null otherwise. - */ - getCompleteNode(path: Path): Node | null; - /** - * Returns all children that are guaranteed to be a complete overwrite. - * - * @return {!Array.} A list of all complete children. - */ - getCompleteChildren(): Array; - /** - * @param {!Path} path - * @return {!CompoundWrite} - */ - childCompoundWrite(path: Path): CompoundWrite; - /** - * Returns true if this CompoundWrite is empty and therefore does not modify any nodes. - * @return {boolean} Whether this CompoundWrite is empty - */ - isEmpty(): boolean; - /** - * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the - * node - * @param {!Node} node The node to apply this CompoundWrite to - * @return {!Node} The node with all writes applied - */ - apply(node: Node): Node; - /** - * @param {!Path} relativePath - * @param {!ImmutableTree.} writeTree - * @param {!Node} node - * @return {!Node} - * @private - */ - private static applySubtreeWrite_; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts b/functions/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts deleted file mode 100644 index ecd1dd3e..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/PersistentConnection.d.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { ServerActions } from './ServerActions'; -import { AuthTokenProvider } from './AuthTokenProvider'; -import { RepoInfo } from './RepoInfo'; -import { Query } from '../api/Query'; -/** - * Firebase connection. Abstracts wire protocol and handles reconnecting. - * - * NOTE: All JSON objects sent to the realtime connection must have property names enclosed - * in quotes to make sure the closure compiler does not minify them. - */ -export declare class PersistentConnection extends ServerActions { - private repoInfo_; - private onDataUpdate_; - private onConnectStatus_; - private onServerInfoUpdate_; - private authTokenProvider_; - private authOverride_; - id: number; - private log_; - /** @private {Object} */ - private interruptReasons_; - private listens_; - private outstandingPuts_; - private outstandingPutCount_; - private onDisconnectRequestQueue_; - private connected_; - private reconnectDelay_; - private maxReconnectDelay_; - private securityDebugCallback_; - lastSessionId: string | null; - /** @private {number|null} */ - private establishConnectionTimer_; - /** @private {boolean} */ - private visible_; - private requestCBHash_; - private requestNumber_; - /** @private {?{ - * sendRequest(Object), - * close() - * }} */ - private realtime_; - /** @private {string|null} */ - private authToken_; - private forceTokenRefresh_; - private invalidAuthTokenCount_; - private firstConnection_; - private lastConnectionAttemptTime_; - private lastConnectionEstablishedTime_; - /** - * @private - */ - private static nextPersistentConnectionId_; - /** - * Counter for number of connections created. Mainly used for tagging in the logs - * @type {number} - * @private - */ - private static nextConnectionId_; - /** - * @implements {ServerActions} - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param onConnectStatus_ - * @param onServerInfoUpdate_ - * @param authTokenProvider_ - * @param authOverride_ - */ - constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: any, c: boolean, d: number | null) => void, onConnectStatus_: (a: boolean) => void, onServerInfoUpdate_: (a: any) => void, authTokenProvider_: AuthTokenProvider, authOverride_?: Object | null); - /** - * @param {!string} action - * @param {*} body - * @param {function(*)=} onResponse - * @protected - */ - protected sendRequest(action: string, body: any, onResponse?: (a: any) => void): void; - /** - * @inheritDoc - */ - listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void; - /** - * @param {!{onComplete(), - * hashFn():!string, - * query: !Query, - * tag: ?number}} listenSpec - * @private - */ - private sendListen_(listenSpec); - /** - * @param {*} payload - * @param {!Query} query - * @private - */ - private static warnOnListenWarnings_(payload, query); - /** - * @inheritDoc - */ - refreshAuthToken(token: string): void; - /** - * @param {!string} credential - * @private - */ - private reduceReconnectDelayIfAdminCredential_(credential); - /** - * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like - * a auth revoked (the connection is closed). - */ - tryAuth(): void; - /** - * @inheritDoc - */ - unlisten(query: Query, tag: number | null): void; - private sendUnlisten_(pathString, queryId, queryObj, tag); - /** - * @inheritDoc - */ - onDisconnectPut(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @inheritDoc - */ - onDisconnectMerge(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @inheritDoc - */ - onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; - private sendOnDisconnect_(action, pathString, data, onComplete); - /** - * @inheritDoc - */ - put(pathString: string, data: any, onComplete?: (a: string, b: string) => void, hash?: string): void; - /** - * @inheritDoc - */ - merge(pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void; - putInternal(action: string, pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void; - private sendPut_(index); - /** - * @inheritDoc - */ - reportStats(stats: { - [k: string]: any; - }): void; - /** - * @param {*} message - * @private - */ - private onDataMessage_(message); - private onDataPush_(action, body); - private onReady_(timestamp, sessionId); - private scheduleConnect_(timeout); - /** - * @param {boolean} visible - * @private - */ - private onVisible_(visible); - private onOnline_(online); - private onRealtimeDisconnect_(); - private establishConnection_(); - /** - * @param {string} reason - */ - interrupt(reason: string): void; - /** - * @param {string} reason - */ - resume(reason: string): void; - private handleTimestamp_(timestamp); - private cancelSentTransactions_(); - /** - * @param {!string} pathString - * @param {Array.<*>=} query - * @private - */ - private onListenRevoked_(pathString, query?); - /** - * @param {!string} pathString - * @param {!string} queryId - * @return {{queries:Array., onComplete:function(string)}} - * @private - */ - private removeListen_(pathString, queryId); - private onAuthRevoked_(statusCode, explanation); - private onSecurityDebugPacket_(body); - private restoreState_(); - /** - * Sends client stats for first connection - * @private - */ - private sendConnectStats_(); - /** - * @return {boolean} - * @private - */ - private shouldReconnect_(); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts b/functions/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts deleted file mode 100644 index 7db79f1c..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/ReadonlyRestClient.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { ServerActions } from './ServerActions'; -import { RepoInfo } from './RepoInfo'; -import { AuthTokenProvider } from './AuthTokenProvider'; -import { Query } from '../api/Query'; -/** - * An implementation of ServerActions that communicates with the server via REST requests. - * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full - * persistent connection (using WebSockets or long-polling) - */ -export declare class ReadonlyRestClient extends ServerActions { - private repoInfo_; - private onDataUpdate_; - private authTokenProvider_; - reportStats(stats: { - [k: string]: any; - }): void; - /** @private {function(...[*])} */ - private log_; - /** - * We don't actually need to track listens, except to prevent us calling an onComplete for a listen - * that's been removed. :-/ - * - * @private {!Object.} - */ - private listens_; - /** - * @param {!Query} query - * @param {?number=} tag - * @return {string} - * @private - */ - static getListenId_(query: Query, tag?: number | null): string; - /** - * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to - * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server - * @param {AuthTokenProvider} authTokenProvider_ - * @implements {ServerActions} - */ - constructor(repoInfo_: RepoInfo, onDataUpdate_: (a: string, b: any, c: boolean, d: number | null) => void, authTokenProvider_: AuthTokenProvider); - /** @inheritDoc */ - listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void; - /** @inheritDoc */ - unlisten(query: Query, tag: number | null): void; - /** @inheritDoc */ - refreshAuthToken(token: string): void; - /** - * Performs a REST request to the given path, with the provided query string parameters, - * and any auth credentials we have. - * - * @param {!string} pathString - * @param {!Object.} queryStringParameters - * @param {?function(?number, *=)} callback - * @private - */ - private restRequest_(pathString, queryStringParameters, callback); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/Repo.d.ts b/functions/node_modules/@firebase/database/dist/src/core/Repo.d.ts deleted file mode 100644 index be514c72..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/Repo.d.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { Path } from './util/Path'; -import { PersistentConnection } from './PersistentConnection'; -import { FirebaseApp } from '@firebase/app-types'; -import { RepoInfo } from './RepoInfo'; -import { Database } from '../api/Database'; -import { Query } from '../api/Query'; -import { EventRegistration } from './view/EventRegistration'; -/** - * A connection to a single data repository. - */ -export declare class Repo { - repoInfo_: RepoInfo; - app: FirebaseApp; - dataUpdateCount: number; - private infoSyncTree_; - private serverSyncTree_; - private stats_; - private statsListener_; - private eventQueue_; - private nextWriteId_; - private server_; - private statsReporter_; - private transactions_init_; - private infoData_; - private abortTransactions_; - private rerunTransactions_; - private interceptServerDataCallback_; - private __database; - private onDisconnect_; - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @type {?PersistentConnection} - */ - persistentConnection_: PersistentConnection | null; - /** - * @param {!RepoInfo} repoInfo_ - * @param {boolean} forceRestClient - * @param {!FirebaseApp} app - */ - constructor(repoInfo_: RepoInfo, forceRestClient: boolean, app: FirebaseApp); - /** - * @return {string} The URL corresponding to the root of this Firebase. - */ - toString(): string; - /** - * @return {!string} The namespace represented by the repo. - */ - name(): string; - /** - * @return {!number} The time in milliseconds, taking the server offset into account if we have one. - */ - serverTime(): number; - /** - * Generate ServerValues using some variables from the repo object. - * @return {!Object} - */ - generateServerValues(): Object; - /** - * Called by realtime when we get new messages from the server. - * - * @private - * @param {string} pathString - * @param {*} data - * @param {boolean} isMerge - * @param {?number} tag - */ - private onDataUpdate_(pathString, data, isMerge, tag); - /** - * TODO: This should be @private but it's used by test_access.js and internal.js - * @param {?function(!string, *):*} callback - * @private - */ - interceptServerData_(callback: ((a: string, b: any) => any) | null): void; - /** - * @param {!boolean} connectStatus - * @private - */ - private onConnectStatus_(connectStatus); - /** - * @param {!Object} updates - * @private - */ - private onServerInfoUpdate_(updates); - /** - * - * @param {!string} pathString - * @param {*} value - * @private - */ - private updateInfo_(pathString, value); - /** - * @return {!number} - * @private - */ - private getNextWriteId_(); - /** - * @param {!Path} path - * @param {*} newVal - * @param {number|string|null} newPriority - * @param {?function(?Error, *=)} onComplete - */ - setWithPriority(path: Path, newVal: any, newPriority: number | string | null, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; - /** - * @param {!Path} path - * @param {!Object} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - update(path: Path, childrenToMerge: { - [k: string]: any; - }, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; - /** - * Applies all of the changes stored up in the onDisconnect_ tree. - * @private - */ - private runOnDisconnectEvents_(); - /** - * @param {!Path} path - * @param {?function(?Error, *=)} onComplete - */ - onDisconnectCancel(path: Path, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; - /** - * @param {!Path} path - * @param {*} value - * @param {?function(?Error, *=)} onComplete - */ - onDisconnectSet(path: Path, value: any, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; - /** - * @param {!Path} path - * @param {*} value - * @param {*} priority - * @param {?function(?Error, *=)} onComplete - */ - onDisconnectSetWithPriority(path: Path, value: any, priority: any, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; - /** - * @param {!Path} path - * @param {*} childrenToMerge - * @param {?function(?Error, *=)} onComplete - */ - onDisconnectUpdate(path: Path, childrenToMerge: { - [k: string]: any; - }, onComplete: ((status: Error | null, errorReason?: string) => void) | null): void; - /** - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - */ - addEventCallbackForQuery(query: Query, eventRegistration: EventRegistration): void; - /** - * @param {!Query} query - * @param {?EventRegistration} eventRegistration - */ - removeEventCallbackForQuery(query: Query, eventRegistration: EventRegistration): void; - interrupt(): void; - resume(): void; - stats(showDelta?: boolean): void; - statsIncrementCounter(metric: string): void; - /** - * @param {...*} var_args - * @private - */ - private log_(...var_args); - /** - * @param {?function(?Error, *=)} callback - * @param {!string} status - * @param {?string=} errorReason - */ - callOnCompleteCallback(callback: ((status: Error | null, errorReason?: string) => void) | null, status: string, errorReason?: string | null): void; - readonly database: Database; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts b/functions/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts deleted file mode 100644 index a0e62ec6..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/RepoInfo.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * A class that holds metadata about a Repo object - * - * @constructor - */ -export declare class RepoInfo { - secure: boolean; - namespace: string; - webSocketOnly: boolean; - persistenceKey: string; - host: string; - domain: string; - internalHost: string; - /** - * @param {string} host Hostname portion of the url for the repo - * @param {boolean} secure Whether or not this repo is accessed over ssl - * @param {string} namespace The namespace represented by the repo - * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest). - * @param {string=} persistenceKey Override the default session persistence storage key - */ - constructor(host: string, secure: boolean, namespace: string, webSocketOnly: boolean, persistenceKey?: string); - needsQueryParam(): boolean; - isCacheableHost(): boolean; - isDemoHost(): boolean; - isCustomHost(): boolean; - updateHost(newHost: string): void; - /** - * Returns the websocket URL for this repo - * @param {string} type of connection - * @param {Object} params list - * @return {string} The URL for this repo - */ - connectionURL(type: string, params: { - [k: string]: string; - }): string; - /** @return {string} */ - toString(): string; - /** @return {string} */ - toURLString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/RepoManager.d.ts b/functions/node_modules/@firebase/database/dist/src/core/RepoManager.d.ts deleted file mode 100644 index a5084fdc..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/RepoManager.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { FirebaseApp } from '@firebase/app-types'; -import { Repo } from './Repo'; -import './Repo_transaction'; -import { Database } from '../api/Database'; -import { RepoInfo } from './RepoInfo'; -/** - * Creates and caches Repo instances. - */ -export declare class RepoManager { - /** - * @private {!Object.>} - */ - private repos_; - /** - * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes). - * @private {boolean} - */ - private useRestClient_; - static getInstance(): RepoManager; - interrupt(): void; - resume(): void; - /** - * This function should only ever be called to CREATE a new database instance. - * - * @param {!FirebaseApp} app - * @return {!Database} - */ - databaseFromApp(app: FirebaseApp, url?: string): Database; - /** - * Remove the repo and make sure it is disconnected. - * - * @param {!Repo} repo - */ - deleteRepo(repo: Repo): void; - /** - * Ensures a repo doesn't already exist and then creates one using the - * provided app. - * - * @param {!RepoInfo} repoInfo The metadata about the Repo - * @param {!FirebaseApp} app - * @return {!Repo} The Repo object for the specified server / repoName. - */ - createRepo(repoInfo: RepoInfo, app: FirebaseApp): Repo; - /** - * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. - * @param {boolean} forceRestClient - */ - forceRestClient(forceRestClient: boolean): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/Repo_transaction.d.ts b/functions/node_modules/@firebase/database/dist/src/core/Repo_transaction.d.ts deleted file mode 100644 index adfdfdd6..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/Repo_transaction.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { DataSnapshot } from '../api/DataSnapshot'; -import { Path } from './util/Path'; -/** - * @enum {number} - */ -export declare enum TransactionStatus { - RUN = 0, - SENT = 1, - COMPLETED = 2, - SENT_NEEDS_ABORT = 3, - NEEDS_ABORT = 4, -} -declare module './Repo' { - interface Repo { - startTransaction(path: Path, transactionUpdate: (a: any) => void, onComplete: ((a: Error, b: boolean, c: DataSnapshot) => void) | null, applyLocally: boolean): void; - } -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts b/functions/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts deleted file mode 100644 index 714bd27f..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/ServerActions.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Query } from '../api/Query'; -/** - * Interface defining the set of actions that can be performed against the Firebase server - * (basically corresponds to our wire protocol). - * - * @interface - */ -export declare abstract class ServerActions { - /** - * @param {!Query} query - * @param {function():string} currentHashFn - * @param {?number} tag - * @param {function(string, *)} onComplete - */ - abstract listen(query: Query, currentHashFn: () => string, tag: number | null, onComplete: (a: string, b: any) => void): void; - /** - * Remove a listen. - * - * @param {!Query} query - * @param {?number} tag - */ - abstract unlisten(query: Query, tag: number | null): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - * @param {string=} hash - */ - put(pathString: string, data: any, onComplete?: (a: string, b: string) => void, hash?: string): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, ?string)} onComplete - * @param {string=} hash - */ - merge(pathString: string, data: any, onComplete: (a: string, b: string | null) => void, hash?: string): void; - /** - * Refreshes the auth token for the current connection. - * @param {string} token The authentication token - */ - refreshAuthToken(token: string): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - onDisconnectPut(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @param {string} pathString - * @param {*} data - * @param {function(string, string)=} onComplete - */ - onDisconnectMerge(pathString: string, data: any, onComplete?: (a: string, b: string) => void): void; - /** - * @param {string} pathString - * @param {function(string, string)=} onComplete - */ - onDisconnectCancel(pathString: string, onComplete?: (a: string, b: string) => void): void; - /** - * @param {Object.} stats - */ - reportStats(stats: { - [k: string]: any; - }): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts b/functions/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts deleted file mode 100644 index 86be45b4..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/SnapshotHolder.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { Path } from './util/Path'; -import { Node } from './snap/Node'; -/** - * Mutable object which basically just stores a reference to the "latest" immutable snapshot. - * - * @constructor - */ -export declare class SnapshotHolder { - private rootNode_; - getNode(path: Path): Node; - updateSnapshot(path: Path, newSnapshotNode: Node): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts b/functions/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts deleted file mode 100644 index b9928567..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/SparseSnapshotTree.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Path } from './util/Path'; -import { Node } from './snap/Node'; -/** - * Helper class to store a sparse set of snapshots. - * - * @constructor - */ -export declare class SparseSnapshotTree { - /** - * @private - * @type {Node} - */ - private value_; - /** - * @private - * @type {CountedSet} - */ - private children_; - /** - * Gets the node stored at the given path if one exists. - * - * @param {!Path} path Path to look up snapshot for. - * @return {?Node} The retrieved node, or null. - */ - find(path: Path): Node | null; - /** - * Stores the given node at the specified path. If there is already a node - * at a shallower path, it merges the new data into that snapshot node. - * - * @param {!Path} path Path to look up snapshot for. - * @param {!Node} data The new data, or null. - */ - remember(path: Path, data: Node): void; - /** - * Purge the data at path from the cache. - * - * @param {!Path} path Path to look up snapshot for. - * @return {boolean} True if this node should now be removed. - */ - forget(path: Path): boolean; - /** - * Recursively iterates through all of the stored tree and calls the - * callback on each one. - * - * @param {!Path} prefixPath Path to look up node for. - * @param {!Function} func The function to invoke for each tree. - */ - forEachTree(prefixPath: Path, func: (a: Path, b: Node) => any): void; - /** - * Iterates through each immediate child and triggers the callback. - * - * @param {!Function} func The function to invoke for each child. - */ - forEachChild(func: (a: string, b: SparseSnapshotTree) => void): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts b/functions/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts deleted file mode 100644 index 804d2c09..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/SyncPoint.d.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { View } from './view/View'; -import { Operation } from './operation/Operation'; -import { WriteTreeRef } from './WriteTree'; -import { Query } from '../api/Query'; -import { EventRegistration } from './view/EventRegistration'; -import { Node } from './snap/Node'; -import { Path } from './util/Path'; -import { Event } from './view/Event'; -import { ReferenceConstructor } from '../api/Reference'; -/** - * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to - * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes - * and user writes (set, transaction, update). - * - * It's responsible for: - * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed). - * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite, - * applyUserOverwrite, etc.) - */ -export declare class SyncPoint { - static __referenceConstructor: ReferenceConstructor; - /** - * The Views being tracked at this location in the tree, stored as a map where the key is a - * queryId and the value is the View for that query. - * - * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case). - * - * @type {!Object.} - * @private - */ - private views_; - /** - * @return {boolean} - */ - isEmpty(): boolean; - /** - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} optCompleteServerCache - * @return {!Array.} - */ - applyOperation(operation: Operation, writesCache: WriteTreeRef, optCompleteServerCache: Node | null): Event[]; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache Complete server cache, if we have it. - * @param {boolean} serverCacheComplete - * @return {!Array.} Events to raise. - */ - addEventRegistration(query: Query, eventRegistration: EventRegistration, writesCache: WriteTreeRef, serverCache: Node | null, serverCacheComplete: boolean): Event[]; - /** - * Remove event callback(s). Return cancelEvents if a cancelError is specified. - * - * If query is the default query, we'll check all views for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified view(s). - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events - */ - removeEventRegistration(query: Query, eventRegistration: EventRegistration | null, cancelError?: Error): { - removed: Query[]; - events: Event[]; - }; - /** - * @return {!Array.} - */ - getQueryViews(): View[]; - /** - * - * @param {!Path} path The path to the desired complete snapshot - * @return {?Node} A complete cache, if it exists - */ - getCompleteServerCache(path: Path): Node | null; - /** - * @param {!Query} query - * @return {?View} - */ - viewForQuery(query: Query): View | null; - /** - * @param {!Query} query - * @return {boolean} - */ - viewExistsForQuery(query: Query): boolean; - /** - * @return {boolean} - */ - hasCompleteView(): boolean; - /** - * @return {?View} - */ - getCompleteView(): View | null; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts b/functions/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts deleted file mode 100644 index d288437a..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/SyncTree.d.ts +++ /dev/null @@ -1,303 +0,0 @@ -import { Path } from './util/Path'; -import { Query } from '../api/Query'; -import { Node } from './snap/Node'; -import { Event } from './view/Event'; -import { EventRegistration } from './view/EventRegistration'; -/** - * @typedef {{ - * startListening: function( - * !Query, - * ?number, - * function():string, - * function(!string, *):!Array. - * ):!Array., - * - * stopListening: function(!Query, ?number) - * }} - */ -export interface ListenProvider { - startListening(query: Query, tag: number | null, hashFn: () => string, onComplete: (a: string, b?: any) => Event[]): Event[]; - stopListening(a: Query, b: number | null): void; -} -/** - * SyncTree is the central class for managing event callback registration, data caching, views - * (query processing), and event generation. There are typically two SyncTree instances for - * each Repo, one for the normal Firebase data, and one for the .info data. - * - * It has a number of responsibilities, including: - * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()). - * - Applying and caching data changes for user set(), transaction(), and update() calls - * (applyUserOverwrite(), applyUserMerge()). - * - Applying and caching data changes for server data changes (applyServerOverwrite(), - * applyServerMerge()). - * - Generating user-facing events for server and user changes (all of the apply* methods - * return the set of events that need to be raised as a result). - * - Maintaining the appropriate set of server listens to ensure we are always subscribed - * to the correct set of paths and queries to satisfy the current set of user event - * callbacks (listens are started/stopped using the provided listenProvider). - * - * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual - * events are returned to the caller rather than raised synchronously. - * - * @constructor - */ -export declare class SyncTree { - private listenProvider_; - /** - * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views. - * @type {!ImmutableTree.} - * @private - */ - private syncPointTree_; - /** - * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.). - * @type {!WriteTree} - * @private - */ - private pendingWriteTree_; - private tagToQueryMap_; - private queryToTagMap_; - /** - * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening - * to server data. - */ - constructor(listenProvider_: ListenProvider); - /** - * Apply the data changes for a user-generated set() or transaction() call. - * - * @param {!Path} path - * @param {!Node} newData - * @param {number} writeId - * @param {boolean=} visible - * @return {!Array.} Events to raise. - */ - applyUserOverwrite(path: Path, newData: Node, writeId: number, visible?: boolean): Event[]; - /** - * Apply the data from a user-generated update() call - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - * @return {!Array.} Events to raise. - */ - applyUserMerge(path: Path, changedChildren: { - [k: string]: Node; - }, writeId: number): Event[]; - /** - * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge(). - * - * @param {!number} writeId - * @param {boolean=} revert True if the given write failed and needs to be reverted - * @return {!Array.} Events to raise. - */ - ackUserWrite(writeId: number, revert?: boolean): Event[]; - /** - * Apply new server data for the specified path.. - * - * @param {!Path} path - * @param {!Node} newData - * @return {!Array.} Events to raise. - */ - applyServerOverwrite(path: Path, newData: Node): Event[]; - /** - * Apply new server data to be merged in at the specified path. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @return {!Array.} Events to raise. - */ - applyServerMerge(path: Path, changedChildren: { - [k: string]: Node; - }): Event[]; - /** - * Apply a listen complete for a query - * - * @param {!Path} path - * @return {!Array.} Events to raise. - */ - applyListenComplete(path: Path): Event[]; - /** - * Apply new server data for the specified tagged query. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - applyTaggedQueryOverwrite(path: Path, snap: Node, tag: number): Event[]; - /** - * Apply server data to be merged in for the specified tagged query. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - applyTaggedQueryMerge(path: Path, changedChildren: { - [k: string]: Node; - }, tag: number): Event[]; - /** - * Apply a listen complete for a tagged query - * - * @param {!Path} path - * @param {!number} tag - * @return {!Array.} Events to raise. - */ - applyTaggedListenComplete(path: Path, tag: number): Event[]; - /** - * Add an event callback for the specified query. - * - * @param {!Query} query - * @param {!EventRegistration} eventRegistration - * @return {!Array.} Events to raise. - */ - addEventRegistration(query: Query, eventRegistration: EventRegistration): Event[]; - /** - * Remove event callback(s). - * - * If query is the default query, we'll check all queries for the specified eventRegistration. - * If eventRegistration is null, we'll remove all callbacks for the specified query/queries. - * - * @param {!Query} query - * @param {?EventRegistration} eventRegistration If null, all callbacks are removed. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - removeEventRegistration(query: Query, eventRegistration: EventRegistration | null, cancelError?: Error): Event[]; - /** - * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above - * it, but as this is only used by transaction code, that should always be the case anyways. - * - * Note: this method will *include* hidden writes from transaction with applyLocally set to false. - * @param {!Path} path The path to the data we want - * @param {Array.=} writeIdsToExclude A specific set to be excluded - * @return {?Node} - */ - calcCompleteEventCache(path: Path, writeIdsToExclude?: number[]): Node | null; - /** - * This collapses multiple unfiltered views into a single view, since we only need a single - * listener for them. - * - * @param {!ImmutableTree.} subtree - * @return {!Array.} - * @private - */ - private collectDistinctViewsForSubTree_(subtree); - /** - * @param {!Array.} queries - * @private - */ - private removeTags_(queries); - /** - * Normalizes a query to a query we send the server for listening - * @param {!Query} query - * @return {!Query} The normalized query - * @private - */ - private static queryForListening_(query); - /** - * For a given new listen, manage the de-duplication of outstanding subscriptions. - * - * @param {!Query} query - * @param {!View} view - * @return {!Array.} This method can return events to support synchronous data sources - * @private - */ - private setupListener_(query, view); - /** - * - * @param {!View} view - * @return {{hashFn: function(), onComplete: function(!string, *)}} - * @private - */ - private createListenerForView_(view); - /** - * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_. - * @private - * @param {!Query} query - * @return {string} - */ - private static makeQueryKey_(query); - /** - * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId. - * @private - * @param {!string} queryKey - * @return {{queryId: !string, path: !Path}} - */ - private static parseQueryKey_(queryKey); - /** - * Return the query associated with the given tag, if we have one - * @param {!number} tag - * @return {?string} - * @private - */ - private queryKeyForTag_(tag); - /** - * Return the tag associated with the given query. - * @param {!Query} query - * @return {?number} - * @private - */ - private tagForQuery_(query); - /** - * Static tracker for next query tag. - * @type {number} - * @private - */ - private static nextQueryTag_; - /** - * Static accessor for query tags. - * @return {number} - * @private - */ - private static getNextQueryTag_(); - /** - * A helper method to apply tagged operations - * - * @param {!Path} queryPath - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - private applyTaggedOperation_(queryPath, operation); - /** - * A helper method that visits all descendant and ancestor SyncPoints, applying the operation. - * - * NOTES: - * - Descendant SyncPoints will be visited first (since we raise events depth-first). - - * - We call applyOperation() on each SyncPoint passing three things: - * 1. A version of the Operation that has been made relative to the SyncPoint location. - * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location. - * 3. A snapshot Node with cached server data, if we have it. - - * - We concatenate all of the events returned by each SyncPoint and return the result. - * - * @param {!Operation} operation - * @return {!Array.} - * @private - */ - private applyOperationToSyncPoints_(operation); - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - private applyOperationHelper_(operation, syncPointTree, serverCache, writesCache); - /** - * Recursive helper for applyOperationToSyncPoints_ - * - * @private - * @param {!Operation} operation - * @param {ImmutableTree.} syncPointTree - * @param {?Node} serverCache - * @param {!WriteTreeRef} writesCache - * @return {!Array.} - */ - private applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts b/functions/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts deleted file mode 100644 index dc2fe122..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/WriteTree.d.ts +++ /dev/null @@ -1,307 +0,0 @@ -import { Path } from './util/Path'; -import { ChildrenNode } from './snap/ChildrenNode'; -import { NamedNode, Node } from './snap/Node'; -import { CacheNode } from './view/CacheNode'; -import { Index } from './snap/indexes/Index'; -/** - * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In - * the case of a set() or transaction, snap wil be non-null. In the case of an update(), children will be non-null. - */ -export interface WriteRecord { - writeId: number; - path: Path; - snap?: Node | null; - children?: { - [k: string]: Node; - } | null; - visible: boolean; -} -/** - * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them - * with underlying server data (to create "event cache" data). Pending writes are added with addOverwrite() - * and addMerge(), and removed with removeWrite(). - * - * @constructor - */ -export declare class WriteTree { - /** - * A tree tracking the result of applying all visible writes. This does not include transactions with - * applyLocally=false or writes that are completely shadowed by other writes. - * - * @type {!CompoundWrite} - * @private - */ - private visibleWrites_; - /** - * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary - * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also - * used by transactions). - * - * @type {!Array.} - * @private - */ - private allWrites_; - private lastWriteId_; - /** - * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path. - * - * @param {!Path} path - * @return {!WriteTreeRef} - */ - childWrites(path: Path): WriteTreeRef; - /** - * Record a new overwrite from user code. - * - * @param {!Path} path - * @param {!Node} snap - * @param {!number} writeId - * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches - */ - addOverwrite(path: Path, snap: Node, writeId: number, visible?: boolean): void; - /** - * Record a new merge from user code. - * - * @param {!Path} path - * @param {!Object.} changedChildren - * @param {!number} writeId - */ - addMerge(path: Path, changedChildren: { - [k: string]: Node; - }, writeId: number): void; - /** - * @param {!number} writeId - * @return {?WriteRecord} - */ - getWrite(writeId: number): WriteRecord | null; - /** - * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates - * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate. - * - * @param {!number} writeId - * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise - * events as a result). - */ - removeWrite(writeId: number): boolean; - /** - * Return a complete snapshot for the given path if there's visible write data at that path, else null. - * No server data is considered. - * - * @param {!Path} path - * @return {?Node} - */ - getCompleteWriteData(path: Path): Node | null; - /** - * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden - * writes), attempt to calculate a complete snapshot for the given path - * - * @param {!Path} treePath - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude An optional set to be excluded - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - calcCompleteEventCache(treePath: Path, completeServerCache: Node | null, writeIdsToExclude?: number[], includeHiddenWrites?: boolean): Node | null; - /** - * With optional, underlying server data, attempt to return a children node of children that we have complete data for. - * Used when creating new views, to pre-fill their complete event children snapshot. - * - * @param {!Path} treePath - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - calcCompleteEventChildren(treePath: Path, completeServerChildren: ChildrenNode | null): Node; - /** - * Given that the underlying server data has updated, determine what, if anything, needs to be - * applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events - * - * Either existingEventSnap or existingServerSnap must exist - * - * @param {!Path} treePath - * @param {!Path} childPath - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - calcEventCacheAfterServerOverwrite(treePath: Path, childPath: Path, existingEventSnap: Node | null, existingServerSnap: Node | null): Node | null; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!Path} treePath - * @param {!string} childKey - * @param {!CacheNode} existingServerSnap - * @return {?Node} - */ - calcCompleteChild(treePath: Path, childKey: string, existingServerSnap: CacheNode): Node | null; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - shadowingWrite(path: Path): Node | null; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window. - * - * @param {!Path} treePath - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - calcIndexedSlice(treePath: Path, completeServerData: Node | null, startPost: NamedNode, count: number, reverse: boolean, index: Index): NamedNode[]; - /** - * @param {!WriteRecord} writeRecord - * @param {!Path} path - * @return {boolean} - * @private - */ - private recordContainsPath_(writeRecord, path); - /** - * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots - * @private - */ - private resetTree_(); - /** - * The default filter used when constructing the tree. Keep everything that's visible. - * - * @param {!WriteRecord} write - * @return {boolean} - * @private - */ - private static DefaultFilter_(write); - /** - * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of - * event data at that path. - * - * @param {!Array.} writes - * @param {!function(!WriteRecord):boolean} filter - * @param {!Path} treeRoot - * @return {!CompoundWrite} - * @private - */ - private static layerTree_(writes, filter, treeRoot); -} -/** - * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods - * just proxy to the underlying WriteTree. - * - * @constructor - */ -export declare class WriteTreeRef { - /** - * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler - * interface to callers. - * - * @type {!Path} - * @private - * @const - */ - private readonly treePath_; - /** - * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate - * path prefixed. - * - * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of - * the data. - * - * @type {!WriteTree} - * @private - * @const - */ - private readonly writeTree_; - /** - * @param {!Path} path - * @param {!WriteTree} writeTree - */ - constructor(path: Path, writeTree: WriteTree); - /** - * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used - * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node - * can lead to a more expensive calculation. - * - * @param {?Node} completeServerCache - * @param {Array.=} writeIdsToExclude Optional writes to exclude. - * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false - * @return {?Node} - */ - calcCompleteEventCache(completeServerCache: Node | null, writeIdsToExclude?: number[], includeHiddenWrites?: boolean): Node | null; - /** - * If possible, returns a children node containing all of the complete children we have data for. The returned data is a - * mix of the given server data and write data. - * - * @param {?ChildrenNode} completeServerChildren - * @return {!ChildrenNode} - */ - calcCompleteEventChildren(completeServerChildren: ChildrenNode | null): ChildrenNode; - /** - * Given that either the underlying server data has updated or the outstanding writes have updated, determine what, - * if anything, needs to be applied to the event cache. - * - * Possibilities: - * - * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data - * - * 2. Some write is completely shadowing. No events to be raised - * - * 3. Is partially shadowed. Events should be raised - * - * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert - * - * @param {!Path} path - * @param {?Node} existingEventSnap - * @param {?Node} existingServerSnap - * @return {?Node} - */ - calcEventCacheAfterServerOverwrite(path: Path, existingEventSnap: Node | null, existingServerSnap: Node | null): Node | null; - /** - * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at - * a higher path, this will return the child of that write relative to the write and this path. - * Returns null if there is no write at this path. - * - * @param {!Path} path - * @return {?Node} - */ - shadowingWrite(path: Path): Node | null; - /** - * This method is used when processing child remove events on a query. If we can, we pull in children that were outside - * the window, but may now be in the window - * - * @param {?Node} completeServerData - * @param {!NamedNode} startPost - * @param {!number} count - * @param {boolean} reverse - * @param {!Index} index - * @return {!Array.} - */ - calcIndexedSlice(completeServerData: Node | null, startPost: NamedNode, count: number, reverse: boolean, index: Index): NamedNode[]; - /** - * Returns a complete child for a given server snap after applying all user writes or null if there is no - * complete child for this ChildKey. - * - * @param {!string} childKey - * @param {!CacheNode} existingServerCache - * @return {?Node} - */ - calcCompleteChild(childKey: string, existingServerCache: CacheNode): Node | null; - /** - * Return a WriteTreeRef for a child. - * - * @param {string} childName - * @return {!WriteTreeRef} - */ - child(childName: string): WriteTreeRef; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts b/functions/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts deleted file mode 100644 index b5f30aaf..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/operation/AckUserWrite.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Path } from '../util/Path'; -import { Operation, OperationSource, OperationType } from './Operation'; -import { ImmutableTree } from '../util/ImmutableTree'; -export declare class AckUserWrite implements Operation { - /**@inheritDoc */ path: Path; - /**@inheritDoc */ affectedTree: ImmutableTree; - /**@inheritDoc */ revert: boolean; - /** @inheritDoc */ - type: OperationType; - /** @inheritDoc */ - source: OperationSource; - /** - * - * @param {!Path} path - * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap. - * @param {!boolean} revert - */ - constructor( - /**@inheritDoc */ path: Path, - /**@inheritDoc */ affectedTree: ImmutableTree, - /**@inheritDoc */ revert: boolean); - /** - * @inheritDoc - */ - operationForChild(childName: string): AckUserWrite; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts b/functions/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts deleted file mode 100644 index 8e2ce271..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/operation/ListenComplete.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Path } from '../util/Path'; -import { Operation, OperationSource, OperationType } from './Operation'; -/** - * @param {!OperationSource} source - * @param {!Path} path - * @constructor - * @implements {Operation} - */ -export declare class ListenComplete implements Operation { - source: OperationSource; - path: Path; - /** @inheritDoc */ - type: OperationType; - constructor(source: OperationSource, path: Path); - operationForChild(childName: string): ListenComplete; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts b/functions/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts deleted file mode 100644 index 934faf41..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/operation/Merge.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Operation, OperationSource, OperationType } from './Operation'; -import { Path } from '../util/Path'; -import { ImmutableTree } from '../util/ImmutableTree'; -import { Node } from '../snap/Node'; -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!ImmutableTree.} children - * @constructor - * @implements {Operation} - */ -export declare class Merge implements Operation { - /**@inheritDoc */ source: OperationSource; - /**@inheritDoc */ path: Path; - /**@inheritDoc */ children: ImmutableTree; - /** @inheritDoc */ - type: OperationType; - constructor( - /**@inheritDoc */ source: OperationSource, - /**@inheritDoc */ path: Path, - /**@inheritDoc */ children: ImmutableTree); - /** - * @inheritDoc - */ - operationForChild(childName: string): Operation; - /** - * @inheritDoc - */ - toString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts b/functions/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts deleted file mode 100644 index 606d21ce..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/operation/Operation.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Path } from '../util/Path'; -/** - * - * @enum - */ -export declare enum OperationType { - OVERWRITE = 0, - MERGE = 1, - ACK_USER_WRITE = 2, - LISTEN_COMPLETE = 3, -} -/** - * @interface - */ -export interface Operation { - /** - * @type {!OperationSource} - */ - source: OperationSource; - /** - * @type {!OperationType} - */ - type: OperationType; - /** - * @type {!Path} - */ - path: Path; - /** - * @param {string} childName - * @return {?Operation} - */ - operationForChild(childName: string): Operation | null; -} -/** - * @param {boolean} fromUser - * @param {boolean} fromServer - * @param {?string} queryId - * @param {boolean} tagged - * @constructor - */ -export declare class OperationSource { - fromUser: boolean; - fromServer: boolean; - queryId: string | null; - tagged: boolean; - constructor(fromUser: boolean, fromServer: boolean, queryId: string | null, tagged: boolean); - /** - * @const - * @type {!OperationSource} - */ - static User: OperationSource; - /** - * @const - * @type {!OperationSource} - */ - static Server: OperationSource; - /** - * @param {string} queryId - * @return {!OperationSource} - */ - static forServerTaggedQuery: (queryId: string) => OperationSource; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts b/functions/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts deleted file mode 100644 index 31e66d74..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/operation/Overwrite.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Operation, OperationSource, OperationType } from './Operation'; -import { Path } from '../util/Path'; -import { Node } from '../snap/Node'; -/** - * @param {!OperationSource} source - * @param {!Path} path - * @param {!Node} snap - * @constructor - * @implements {Operation} - */ -export declare class Overwrite implements Operation { - source: OperationSource; - path: Path; - snap: Node; - /** @inheritDoc */ - type: OperationType; - constructor(source: OperationSource, path: Path, snap: Node); - operationForChild(childName: string): Overwrite; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts deleted file mode 100644 index 45cf8dfb..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/ChildrenNode.d.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { SortedMap, SortedMapIterator } from '../util/SortedMap'; -import { Node, NamedNode } from './Node'; -import { IndexMap } from './IndexMap'; -import { Index } from './indexes/Index'; -import { Path } from '../util/Path'; -export interface ChildrenNodeConstructor { - new (children_: SortedMap, priorityNode_: Node | null, indexMap_: IndexMap): ChildrenNode; - EMPTY_NODE: ChildrenNode; -} -/** - * ChildrenNode is a class for storing internal nodes in a DataSnapshot - * (i.e. nodes with children). It implements Node and stores the - * list of children in the children property, sorted by child name. - * - * @constructor - * @implements {Node} - */ -export declare class ChildrenNode implements Node { - private readonly children_; - private readonly priorityNode_; - private indexMap_; - private lazyHash_; - static readonly EMPTY_NODE: ChildrenNode; - /** - * - * @param {!SortedMap.} children_ List of children - * of this node.. - * @param {?Node} priorityNode_ The priority of this node (as a snapshot node). - * @param {!IndexMap} indexMap_ - */ - constructor(children_: SortedMap, priorityNode_: Node | null, indexMap_: IndexMap); - /** @inheritDoc */ - isLeafNode(): boolean; - /** @inheritDoc */ - getPriority(): Node; - /** @inheritDoc */ - updatePriority(newPriorityNode: Node): Node; - /** @inheritDoc */ - getImmediateChild(childName: string): Node; - /** @inheritDoc */ - getChild(path: Path): Node; - /** @inheritDoc */ - hasChild(childName: string): boolean; - /** @inheritDoc */ - updateImmediateChild(childName: string, newChildNode: Node): Node; - /** @inheritDoc */ - updateChild(path: Path, newChildNode: Node): Node; - /** @inheritDoc */ - isEmpty(): boolean; - /** @inheritDoc */ - numChildren(): number; - /** - * @private - * @type {RegExp} - */ - private static INTEGER_REGEXP_; - /** @inheritDoc */ - val(exportFormat?: boolean): object; - /** @inheritDoc */ - hash(): string; - /** @inheritDoc */ - getPredecessorChildName(childName: string, childNode: Node, index: Index): string; - /** - * @param {!Index} indexDefinition - * @return {?string} - */ - getFirstChildName(indexDefinition: Index): string | null; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - getFirstChild(indexDefinition: Index): NamedNode | null; - /** - * Given an index, return the key name of the largest value we have, according to that index - * @param {!Index} indexDefinition - * @return {?string} - */ - getLastChildName(indexDefinition: Index): string | null; - /** - * @param {!Index} indexDefinition - * @return {?NamedNode} - */ - getLastChild(indexDefinition: Index): NamedNode | null; - /** - * @inheritDoc - */ - forEachChild(index: Index, action: (key: string, node: Node) => boolean | void): boolean; - /** - * @param {!Index} indexDefinition - * @return {SortedMapIterator} - */ - getIterator(indexDefinition: Index): SortedMapIterator; - /** - * - * @param {!NamedNode} startPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - getIteratorFrom(startPost: NamedNode, indexDefinition: Index): SortedMapIterator; - /** - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - getReverseIterator(indexDefinition: Index): SortedMapIterator; - /** - * @param {!NamedNode} endPost - * @param {!Index} indexDefinition - * @return {!SortedMapIterator} - */ - getReverseIteratorFrom(endPost: NamedNode, indexDefinition: Index): SortedMapIterator; - /** - * @inheritDoc - */ - compareTo(other: ChildrenNode): number; - /** - * @inheritDoc - */ - withIndex(indexDefinition: Index): Node; - /** - * @inheritDoc - */ - isIndexed(index: Index): boolean; - /** - * @inheritDoc - */ - equals(other: Node): boolean; - /** - * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used - * instead. - * - * @private - * @param {!Index} indexDefinition - * @return {?SortedMap.} - */ - private resolveIndex_(indexDefinition); -} -/** - * @constructor - * @extends {ChildrenNode} - * @private - */ -export declare class MaxNode extends ChildrenNode { - constructor(); - compareTo(other: Node): number; - equals(other: Node): boolean; - getPriority(): MaxNode; - getImmediateChild(childName: string): ChildrenNode; - isEmpty(): boolean; -} -/** - * Marker that will sort higher than any other snapshot. - * @type {!MAX_NODE} - * @const - */ -export declare const MAX_NODE: MaxNode; -/** - * Document NamedNode extensions - */ -declare module './Node' { - interface NamedNode { - MIN: NamedNode; - MAX: NamedNode; - } -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts deleted file mode 100644 index 46e27048..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/IndexMap.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { NamedNode, Node } from './Node'; -import { SortedMap } from '../util/SortedMap'; -import { Index } from './indexes/Index'; -/** - * - * @param {Object.>} indexes - * @param {Object.} indexSet - * @constructor - */ -export declare class IndexMap { - private indexes_; - private indexSet_; - /** - * The default IndexMap for nodes without a priority - * @type {!IndexMap} - * @const - */ - static readonly Default: IndexMap; - constructor(indexes_: { - [k: string]: SortedMap | object; - }, indexSet_: { - [k: string]: Index; - }); - /** - * - * @param {!string} indexKey - * @return {?SortedMap.} - */ - get(indexKey: string): SortedMap | null; - /** - * @param {!Index} indexDefinition - * @return {boolean} - */ - hasIndex(indexDefinition: Index): boolean; - /** - * @param {!Index} indexDefinition - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - addIndex(indexDefinition: Index, existingChildren: SortedMap): IndexMap; - /** - * Ensure that this node is properly tracked in any indexes that we're maintaining - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - addToIndexes(namedNode: NamedNode, existingChildren: SortedMap): IndexMap; - /** - * Create a new IndexMap instance with the given value removed - * @param {!NamedNode} namedNode - * @param {!SortedMap.} existingChildren - * @return {!IndexMap} - */ - removeFromIndexes(namedNode: NamedNode, existingChildren: SortedMap): IndexMap; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts deleted file mode 100644 index 94c2ad73..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/LeafNode.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { Node } from './Node'; -import { Path } from '../util/Path'; -import { Index } from './indexes/Index'; -import { ChildrenNodeConstructor } from './ChildrenNode'; -/** - * LeafNode is a class for storing leaf nodes in a DataSnapshot. It - * implements Node and stores the value of the node (a string, - * number, or boolean) accessible via getValue(). - */ -export declare class LeafNode implements Node { - private readonly value_; - private priorityNode_; - static __childrenNodeConstructor: ChildrenNodeConstructor; - /** - * The sort order for comparing leaf nodes of different types. If two leaf nodes have - * the same type, the comparison falls back to their value - * @type {Array.} - * @const - */ - static VALUE_TYPE_ORDER: string[]; - private lazyHash_; - /** - * @implements {Node} - * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node. - * The object type is possible in the event of a deferred value - * @param {!Node=} priorityNode_ The priority of this node. - */ - constructor(value_: string | number | boolean | object, priorityNode_?: Node); - /** @inheritDoc */ - isLeafNode(): boolean; - /** @inheritDoc */ - getPriority(): Node; - /** @inheritDoc */ - updatePriority(newPriorityNode: Node): Node; - /** @inheritDoc */ - getImmediateChild(childName: string): Node; - /** @inheritDoc */ - getChild(path: Path): Node; - /** - * @inheritDoc - */ - hasChild(): boolean; - /** @inheritDoc */ - getPredecessorChildName(childName: String, childNode: Node): null; - /** @inheritDoc */ - updateImmediateChild(childName: string, newChildNode: Node): Node; - /** @inheritDoc */ - updateChild(path: Path, newChildNode: Node): Node; - /** @inheritDoc */ - isEmpty(): boolean; - /** @inheritDoc */ - numChildren(): number; - /** @inheritDoc */ - forEachChild(index: Index, action: (s: string, n: Node) => void): any; - /** - * @inheritDoc - */ - val(exportFormat?: boolean): Object; - /** @inheritDoc */ - hash(): string; - /** - * Returns the value of the leaf node. - * @return {Object|string|number|boolean} The value of the node. - */ - getValue(): object | string | number | boolean; - /** - * @inheritDoc - */ - compareTo(other: Node): number; - /** - * Comparison specifically for two leaf nodes - * @param {!LeafNode} otherLeaf - * @return {!number} - * @private - */ - private compareToLeafNode_(otherLeaf); - /** - * @inheritDoc - */ - withIndex(): Node; - /** - * @inheritDoc - */ - isIndexed(): boolean; - /** - * @inheritDoc - */ - equals(other: Node): boolean; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts deleted file mode 100644 index 7a999e3e..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/Node.d.ts +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Path } from '../util/Path'; -import { Index } from './indexes/Index'; -/** - * Node is an interface defining the common functionality for nodes in - * a DataSnapshot. - * - * @interface - */ -export interface Node { - /** - * Whether this node is a leaf node. - * @return {boolean} Whether this is a leaf node. - */ - isLeafNode(): boolean; - /** - * Gets the priority of the node. - * @return {!Node} The priority of the node. - */ - getPriority(): Node; - /** - * Returns a duplicate node with the new priority. - * @param {!Node} newPriorityNode New priority to set for the node. - * @return {!Node} Node with new priority. - */ - updatePriority(newPriorityNode: Node): Node; - /** - * Returns the specified immediate child, or null if it doesn't exist. - * @param {string} childName The name of the child to retrieve. - * @return {!Node} The retrieved child, or an empty node. - */ - getImmediateChild(childName: string): Node; - /** - * Returns a child by path, or null if it doesn't exist. - * @param {!Path} path The path of the child to retrieve. - * @return {!Node} The retrieved child or an empty node. - */ - getChild(path: Path): Node; - /** - * Returns the name of the child immediately prior to the specified childNode, or null. - * @param {!string} childName The name of the child to find the predecessor of. - * @param {!Node} childNode The node to find the predecessor of. - * @param {!Index} index The index to use to determine the predecessor - * @return {?string} The name of the predecessor child, or null if childNode is the first child. - */ - getPredecessorChildName(childName: String, childNode: Node, index: Index): string | null; - /** - * Returns a duplicate node, with the specified immediate child updated. - * Any value in the node will be removed. - * @param {string} childName The name of the child to update. - * @param {!Node} newChildNode The new child node - * @return {!Node} The updated node. - */ - updateImmediateChild(childName: string, newChildNode: Node): Node; - /** - * Returns a duplicate node, with the specified child updated. Any value will - * be removed. - * @param {!Path} path The path of the child to update. - * @param {!Node} newChildNode The new child node, which may be an empty node - * @return {!Node} The updated node. - */ - updateChild(path: Path, newChildNode: Node): Node; - /** - * True if the immediate child specified exists - * @param {!string} childName - * @return {boolean} - */ - hasChild(childName: string): boolean; - /** - * @return {boolean} True if this node has no value or children. - */ - isEmpty(): boolean; - /** - * @return {number} The number of children of this node. - */ - numChildren(): number; - /** - * Calls action for each child. - * @param {!Index} index - * @param {function(string, !Node)} action Action to be called for - * each child. It's passed the child name and the child node. - * @return {*} The first truthy value return by action, or the last falsey one - */ - forEachChild(index: Index, action: (a: string, b: Node) => void): any; - /** - * @param {boolean=} exportFormat True for export format (also wire protocol format). - * @return {*} Value of this node as JSON. - */ - val(exportFormat?: boolean): Object; - /** - * @return {string} hash representing the node contents. - */ - hash(): string; - /** - * @param {!Node} other Another node - * @return {!number} -1 for less than, 0 for equal, 1 for greater than other - */ - compareTo(other: Node): number; - /** - * @param {!Node} other - * @return {boolean} Whether or not this snapshot equals other - */ - equals(other: Node): boolean; - /** - * @param {!Index} indexDefinition - * @return {!Node} This node, with the specified index now available - */ - withIndex(indexDefinition: Index): Node; - /** - * @param {!Index} indexDefinition - * @return {boolean} - */ - isIndexed(indexDefinition: Index): boolean; -} -/** - * - * @param {!string} name - * @param {!Node} node - * @constructor - * @struct - */ -export declare class NamedNode { - name: string; - node: Node; - constructor(name: string, node: Node); - /** - * - * @param {!string} name - * @param {!Node} node - * @return {NamedNode} - */ - static Wrap(name: string, node: Node): NamedNode; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts deleted file mode 100644 index 88b293bc..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/childSet.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SortedMap } from '../util/SortedMap'; -import { NamedNode } from './Node'; -/** - * Takes a list of child nodes and constructs a SortedSet using the given comparison - * function - * - * Uses the algorithm described in the paper linked here: - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458 - * - * @template K, V - * @param {Array.} childList Unsorted list of children - * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used - * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's - * type is not NamedNode - * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map - * @return {SortedMap.} - */ -export declare const buildChildSet: (childList: NamedNode[], cmp: (a: NamedNode, b: NamedNode) => number, keyFn?: (a: NamedNode) => K, mapSortFn?: (a: K, b: K) => number) => SortedMap; diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts deleted file mode 100644 index f886b7d2..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/comparators.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { NamedNode } from './Node'; -export declare function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode): number; -export declare function NAME_COMPARATOR(left: string, right: string): number; diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts deleted file mode 100644 index ed3a0261..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/Index.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Node, NamedNode } from '../Node'; -import { Comparator } from '../../util/SortedMap'; -/** - * - * @constructor - */ -export declare abstract class Index { - /** - * @param {!NamedNode} a - * @param {!NamedNode} b - * @return {number} - */ - abstract compare(a: NamedNode, b: NamedNode): number; - /** - * @param {!Node} node - * @return {boolean} - */ - abstract isDefinedOn(node: Node): boolean; - /** - * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for - * this index - */ - getCompare(): Comparator; - /** - * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different, - * it's possible that the changes are isolated to parts of the snapshot that are not indexed. - * - * @param {!Node} oldNode - * @param {!Node} newNode - * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode - */ - indexedValueChanged(oldNode: Node, newNode: Node): boolean; - /** - * @return {!NamedNode} a node wrapper that will sort equal to or less than - * any other node wrapper, using this index - */ - minPost(): NamedNode; - /** - * @return {!NamedNode} a node wrapper that will sort greater than or equal to - * any other node wrapper, using this index - */ - abstract maxPost(): NamedNode; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - abstract makePost(indexValue: any, name: string): NamedNode; - /** - * @return {!string} String representation for inclusion in a query spec - */ - abstract toString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts deleted file mode 100644 index aff8db34..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/KeyIndex.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Index } from './Index'; -import { Node, NamedNode } from '../Node'; -import { ChildrenNode } from '../ChildrenNode'; -export declare class KeyIndex extends Index { - static __EMPTY_NODE: ChildrenNode; - /** - * @inheritDoc - */ - compare(a: NamedNode, b: NamedNode): number; - /** - * @inheritDoc - */ - isDefinedOn(node: Node): boolean; - /** - * @inheritDoc - */ - indexedValueChanged(oldNode: Node, newNode: Node): boolean; - /** - * @inheritDoc - */ - minPost(): any; - /** - * @inheritDoc - */ - maxPost(): NamedNode; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - makePost(indexValue: string, name: string): NamedNode; - /** - * @return {!string} String representation for inclusion in a query spec - */ - toString(): string; -} -export declare const KEY_INDEX: KeyIndex; diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts deleted file mode 100644 index 7333a9bb..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PathIndex.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Index } from './Index'; -import { NamedNode, Node } from '../Node'; -import { Path } from '../../util/Path'; -/** - * @param {!Path} indexPath - * @constructor - * @extends {Index} - */ -export declare class PathIndex extends Index { - private indexPath_; - constructor(indexPath_: Path); - /** - * @param {!Node} snap - * @return {!Node} - * @protected - */ - protected extractChild(snap: Node): Node; - /** - * @inheritDoc - */ - isDefinedOn(node: Node): boolean; - /** - * @inheritDoc - */ - compare(a: NamedNode, b: NamedNode): number; - /** - * @inheritDoc - */ - makePost(indexValue: object, name: string): NamedNode; - /** - * @inheritDoc - */ - maxPost(): NamedNode; - /** - * @inheritDoc - */ - toString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts deleted file mode 100644 index e706ab13..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/PriorityIndex.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Index } from './Index'; -import { NamedNode, Node } from '../Node'; -export declare function setNodeFromJSON(val: (a: any) => Node): void; -export declare function setMaxNode(val: Node): void; -/** - * @constructor - * @extends {Index} - * @private - */ -export declare class PriorityIndex extends Index { - /** - * @inheritDoc - */ - compare(a: NamedNode, b: NamedNode): number; - /** - * @inheritDoc - */ - isDefinedOn(node: Node): boolean; - /** - * @inheritDoc - */ - indexedValueChanged(oldNode: Node, newNode: Node): boolean; - /** - * @inheritDoc - */ - minPost(): NamedNode; - /** - * @inheritDoc - */ - maxPost(): NamedNode; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - makePost(indexValue: any, name: string): NamedNode; - /** - * @return {!string} String representation for inclusion in a query spec - */ - toString(): string; -} -export declare const PRIORITY_INDEX: PriorityIndex; diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts deleted file mode 100644 index ba23fc44..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/indexes/ValueIndex.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Index } from './Index'; -import { NamedNode, Node } from '../Node'; -/** - * @constructor - * @extends {Index} - * @private - */ -export declare class ValueIndex extends Index { - /** - * @inheritDoc - */ - compare(a: NamedNode, b: NamedNode): number; - /** - * @inheritDoc - */ - isDefinedOn(node: Node): boolean; - /** - * @inheritDoc - */ - indexedValueChanged(oldNode: Node, newNode: Node): boolean; - /** - * @inheritDoc - */ - minPost(): NamedNode; - /** - * @inheritDoc - */ - maxPost(): NamedNode; - /** - * @param {*} indexValue - * @param {string} name - * @return {!NamedNode} - */ - makePost(indexValue: object, name: string): NamedNode; - /** - * @return {!string} String representation for inclusion in a query spec - */ - toString(): string; -} -export declare const VALUE_INDEX: ValueIndex; diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts deleted file mode 100644 index cda4e1da..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/nodeFromJSON.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Node } from './Node'; -/** - * Constructs a snapshot node representing the passed JSON and returns it. - * @param {*} json JSON to create a node for. - * @param {?string|?number=} priority Optional priority to use. This will be ignored if the - * passed JSON contains a .priority property. - * @return {!Node} - */ -export declare function nodeFromJSON(json: any | null, priority?: string | number | null): Node; diff --git a/functions/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts b/functions/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts deleted file mode 100644 index 8e338c6e..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/snap/snap.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Node } from './Node'; -export declare function setMaxNode(val: Node): void; -/** - * @param {(!string|!number)} priority - * @return {!string} - */ -export declare const priorityHashText: (priority: string | number) => string; -/** - * Validates that a priority snapshot Node is valid. - * - * @param {!Node} priorityNode - */ -export declare const validatePriorityNode: (priorityNode: Node) => void; diff --git a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts b/functions/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts deleted file mode 100644 index 71412369..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsCollection.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Tracks a collection of stats. - * - * @constructor - */ -export declare class StatsCollection { - private counters_; - incrementCounter(name: string, amount?: number): void; - get(): { - [k: string]: number; - }; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts b/functions/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts deleted file mode 100644 index 624697cd..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsListener.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { StatsCollection } from './StatsCollection'; -/** - * Returns the delta from the previous call to get stats. - * - * @param collection_ The collection to "listen" to. - * @constructor - */ -export declare class StatsListener { - private collection_; - private last_; - constructor(collection_: StatsCollection); - get(): { - [k: string]: number; - }; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts b/functions/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts deleted file mode 100644 index e24d26b4..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsManager.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { StatsCollection } from './StatsCollection'; -import { RepoInfo } from '../RepoInfo'; -export declare class StatsManager { - private static collections_; - private static reporters_; - static getCollection(repoInfo: RepoInfo): StatsCollection; - static getOrCreateReporter(repoInfo: RepoInfo, creatorFunction: () => T): T; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts b/functions/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts deleted file mode 100644 index 0156d610..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/stats/StatsReporter.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { StatsCollection } from './StatsCollection'; -import { ServerActions } from '../ServerActions'; -/** - * @constructor - */ -export declare class StatsReporter { - private server_; - private statsListener_; - private statsToReport_; - /** - * @param collection - * @param server_ - */ - constructor(collection: StatsCollection, server_: ServerActions); - includeStat(stat: string): void; - private reportStats_(); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts b/functions/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts deleted file mode 100644 index a9d26b71..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/storage/DOMStorageWrapper.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Wraps a DOM Storage object and: - * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types. - * - prefixes names with "firebase:" to avoid collisions with app data. - * - * We automatically (see storage.js) create two such wrappers, one for sessionStorage, - * and one for localStorage. - * - * @constructor - */ -export declare class DOMStorageWrapper { - private domStorage_; - private prefix_; - /** - * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage) - */ - constructor(domStorage_: Storage); - /** - * @param {string} key The key to save the value under - * @param {?Object} value The value being stored, or null to remove the key. - */ - set(key: string, value: any | null): void; - /** - * @param {string} key - * @return {*} The value that was stored under this key, or null - */ - get(key: string): any; - /** - * @param {string} key - */ - remove(key: string): void; - isInMemoryStorage: boolean; - /** - * @param {string} name - * @return {string} - */ - prefixedName_(name: string): string; - toString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts b/functions/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts deleted file mode 100644 index 07817aac..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/storage/MemoryStorage.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * An in-memory storage implementation that matches the API of DOMStorageWrapper - * (TODO: create interface for both to implement). - * - * @constructor - */ -export declare class MemoryStorage { - private cache_; - set(key: string, value: any | null): void; - get(key: string): any; - remove(key: string): void; - isInMemoryStorage: boolean; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts b/functions/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts deleted file mode 100644 index 778cb1f3..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/storage/storage.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { DOMStorageWrapper } from './DOMStorageWrapper'; -import { MemoryStorage } from './MemoryStorage'; -/** A storage object that lasts across sessions */ -export declare const PersistentStorage: DOMStorageWrapper | MemoryStorage; -/** A storage object that only lasts one session */ -export declare const SessionStorage: DOMStorageWrapper | MemoryStorage; diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/CountedSet.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/CountedSet.d.ts deleted file mode 100644 index 9a8c6da9..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/CountedSet.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Implements a set with a count of elements. - * - * @template K, V - */ -export declare class CountedSet { - set: { - [k: string]: V; - }; - /** - * @param {!K} item - * @param {V} val - */ - add(item: K, val: V): void; - /** - * @param {!K} key - * @return {boolean} - */ - contains(key: K): any; - /** - * @param {!K} item - * @return {V} - */ - get(item: K): V | void; - /** - * @param {!K} item - */ - remove(item: K): void; - /** - * Deletes everything in the set - */ - clear(): void; - /** - * True if there's nothing in the set - * @return {boolean} - */ - isEmpty(): boolean; - /** - * @return {number} The number of items in the set - */ - count(): number; - /** - * Run a function on each k,v pair in the set - * @param {function(K, V)} fn - */ - each(fn: (k: K, v: V) => void): void; - /** - * Mostly for debugging - * @return {Array.} The keys present in this CountedSet - */ - keys(): K[]; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts deleted file mode 100644 index c54bdf63..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/EventEmitter.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Base class to be used if you want to emit events. Call the constructor with - * the set of allowed event names. - */ -export declare abstract class EventEmitter { - private allowedEvents_; - private listeners_; - /** - * @param {!Array.} allowedEvents_ - */ - constructor(allowedEvents_: Array); - /** - * To be overridden by derived classes in order to fire an initial event when - * somebody subscribes for data. - * - * @param {!string} eventType - * @return {Array.<*>} Array of parameters to trigger initial event with. - */ - abstract getInitialEvent(eventType: string): any[]; - /** - * To be called by derived classes to trigger events. - * @param {!string} eventType - * @param {...*} var_args - */ - protected trigger(eventType: string, ...var_args: any[]): void; - on(eventType: string, callback: (a: any) => void, context: any): void; - off(eventType: string, callback: (a: any) => void, context: any): void; - private validateEventType_(eventType); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts deleted file mode 100644 index c05e43ca..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/ImmutableTree.d.ts +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { SortedMap } from './SortedMap'; -import { Path } from './Path'; -/** - * A tree with immutable elements. - */ -export declare class ImmutableTree { - readonly value: T | null; - readonly children: SortedMap>; - static Empty: ImmutableTree; - /** - * @template T - * @param {!Object.} obj - * @return {!ImmutableTree.} - */ - static fromObject(obj: { - [k: string]: T; - }): ImmutableTree; - /** - * @template T - * @param {?T} value - * @param {SortedMap.>=} children - */ - constructor(value: T | null, children?: SortedMap>); - /** - * True if the value is empty and there are no children - * @return {boolean} - */ - isEmpty(): boolean; - /** - * Given a path and predicate, return the first node and the path to that node - * where the predicate returns true. - * - * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects - * on the way back out, it may be better to pass down a pathSoFar obj. - * - * @param {!Path} relativePath The remainder of the path - * @param {function(T):boolean} predicate The predicate to satisfy to return a - * node - * @return {?{path:!Path, value:!T}} - */ - findRootMostMatchingPathAndValue(relativePath: Path, predicate: (a: T) => boolean): { - path: Path; - value: T; - } | null; - /** - * Find, if it exists, the shortest subpath of the given path that points a defined - * value in the tree - * @param {!Path} relativePath - * @return {?{path: !Path, value: !T}} - */ - findRootMostValueAndPath(relativePath: Path): { - path: Path; - value: T; - } | null; - /** - * @param {!Path} relativePath - * @return {!ImmutableTree.} The subtree at the given path - */ - subtree(relativePath: Path): ImmutableTree; - /** - * Sets a value at the specified path. - * - * @param {!Path} relativePath Path to set value at. - * @param {?T} toSet Value to set. - * @return {!ImmutableTree.} Resulting tree. - */ - set(relativePath: Path, toSet: T | null): ImmutableTree; - /** - * Removes the value at the specified path. - * - * @param {!Path} relativePath Path to value to remove. - * @return {!ImmutableTree.} Resulting tree. - */ - remove(relativePath: Path): ImmutableTree; - /** - * Gets a value from the tree. - * - * @param {!Path} relativePath Path to get value for. - * @return {?T} Value at path, or null. - */ - get(relativePath: Path): T | null; - /** - * Replace the subtree at the specified path with the given new tree. - * - * @param {!Path} relativePath Path to replace subtree for. - * @param {!ImmutableTree} newTree New tree. - * @return {!ImmutableTree} Resulting tree. - */ - setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree; - /** - * Performs a depth first fold on this tree. Transforms a tree into a single - * value, given a function that operates on the path to a node, an optional - * current value, and a map of child names to folded subtrees - * @template V - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - */ - fold(fn: (path: Path, value: T, children: { - [k: string]: V; - }) => V): V; - /** - * Recursive helper for public-facing fold() method - * @template V - * @param {!Path} pathSoFar - * @param {function(Path, ?T, Object.):V} fn - * @return {V} - * @private - */ - private fold_(pathSoFar, fn); - /** - * Find the first matching value on the given path. Return the result of applying f to it. - * @template V - * @param {!Path} path - * @param {!function(!Path, !T):?V} f - * @return {?V} - */ - findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null; - private findOnPath_(pathToFollow, pathSoFar, f); - /** - * - * @param {!Path} path - * @param {!function(!Path, !T)} f - * @returns {!ImmutableTree.} - */ - foreachOnPath(path: Path, f: (path: Path, value: T) => void): ImmutableTree; - private foreachOnPath_(pathToFollow, currentRelativePath, f); - /** - * Calls the given function for each node in the tree that has a value. - * - * @param {function(!Path, !T)} f A function to be called with - * the path from the root of the tree to a node, and the value at that node. - * Called in depth-first order. - */ - foreach(f: (path: Path, value: T) => void): void; - private foreach_(currentRelativePath, f); - /** - * - * @param {function(string, !T)} f - */ - foreachChild(f: (name: string, value: T) => void): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts deleted file mode 100644 index bfcec808..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/NextPushId.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Fancy ID generator that creates 20-character string identifiers with the - * following properties: - * - * 1. They're based on timestamp so that they sort *after* any existing ids. - * 2. They contain 72-bits of random data after the timestamp so that IDs won't - * collide with other clients' IDs. - * 3. They sort *lexicographically* (so the timestamp is converted to characters - * that will sort properly). - * 4. They're monotonically increasing. Even if you generate more than one in - * the same timestamp, the latter ones will sort after the former ones. We do - * this by using the previous random bits but "incrementing" them by 1 (only - * in the case of a timestamp collision). - */ -export declare const nextPushId: (now: number) => string; diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts deleted file mode 100644 index 9f23cdf6..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/OnlineMonitor.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { EventEmitter } from './EventEmitter'; -/** - * Monitors online state (as reported by window.online/offline events). - * - * The expectation is that this could have many false positives (thinks we are online - * when we're not), but no false negatives. So we can safely use it to determine when - * we definitely cannot reach the internet. - * - * @extends {EventEmitter} - */ -export declare class OnlineMonitor extends EventEmitter { - private online_; - static getInstance(): OnlineMonitor; - constructor(); - /** - * @param {!string} eventType - * @return {Array.} - */ - getInitialEvent(eventType: string): boolean[]; - /** - * @return {boolean} - */ - currentlyOnline(): boolean; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/Path.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/Path.d.ts deleted file mode 100644 index 68fd455f..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/Path.d.ts +++ /dev/null @@ -1,116 +0,0 @@ -/** - * An immutable object representing a parsed path. It's immutable so that you - * can pass them around to other functions without worrying about them changing - * it. - */ -export declare class Path { - private pieces_; - private pieceNum_; - /** - * Singleton to represent an empty path - * - * @const - */ - static readonly Empty: Path; - /** - * @param {string|Array.} pathOrString Path string to parse, - * or another path, or the raw tokens array - * @param {number=} pieceNum - */ - constructor(pathOrString: string | string[], pieceNum?: number); - getFront(): string | null; - /** - * @return {number} The number of segments in this path - */ - getLength(): number; - /** - * @return {!Path} - */ - popFront(): Path; - /** - * @return {?string} - */ - getBack(): string | null; - toString(): string; - toUrlEncodedString(): string; - /** - * Shallow copy of the parts of the path. - * - * @param {number=} begin - * @return {!Array} - */ - slice(begin?: number): string[]; - /** - * @return {?Path} - */ - parent(): Path | null; - /** - * @param {string|!Path} childPathObj - * @return {!Path} - */ - child(childPathObj: string | Path): Path; - /** - * @return {boolean} True if there are no segments in this path - */ - isEmpty(): boolean; - /** - * @param {!Path} outerPath - * @param {!Path} innerPath - * @return {!Path} The path from outerPath to innerPath - */ - static relativePath(outerPath: Path, innerPath: Path): Path; - /** - * @param {!Path} left - * @param {!Path} right - * @return {number} -1, 0, 1 if left is less, equal, or greater than the right. - */ - static comparePaths(left: Path, right: Path): number; - /** - * - * @param {Path} other - * @return {boolean} true if paths are the same. - */ - equals(other: Path): boolean; - /** - * - * @param {!Path} other - * @return {boolean} True if this path is a parent (or the same as) other - */ - contains(other: Path): boolean; -} -/** - * Dynamic (mutable) path used to count path lengths. - * - * This class is used to efficiently check paths for valid - * length (in UTF8 bytes) and depth (used in path validation). - * - * Throws Error exception if path is ever invalid. - * - * The definition of a path always begins with '/'. - */ -export declare class ValidationPath { - private errorPrefix_; - /** @type {!Array} */ - private parts_; - /** @type {number} Initialize to number of '/' chars needed in path. */ - private byteLength_; - /** - * @param {!Path} path Initial Path. - * @param {string} errorPrefix_ Prefix for any error messages. - */ - constructor(path: Path, errorPrefix_: string); - /** @const {number} Maximum key depth. */ - static readonly MAX_PATH_DEPTH: number; - /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */ - static readonly MAX_PATH_LENGTH_BYTES: number; - /** @param {string} child */ - push(child: string): void; - pop(): void; - private checkValid_(); - /** - * String for use in error messages - uses '.' notation for path. - * - * @return {string} - */ - toErrorString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts deleted file mode 100644 index 325dd16e..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/ServerValues.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { SparseSnapshotTree } from '../SparseSnapshotTree'; -import { Node } from '../snap/Node'; -/** - * Generate placeholders for deferred values. - * @param {?Object} values - * @return {!Object} - */ -export declare const generateWithValues: (values: { - [k: string]: any; -}) => { - [k: string]: any; -}; -/** - * Value to use when firing local events. When writing server values, fire - * local events with an approximate value, otherwise return value as-is. - * @param {(Object|string|number|boolean)} value - * @param {!Object} serverValues - * @return {!(string|number|boolean)} - */ -export declare const resolveDeferredValue: (value: string | number | boolean | { - [k: string]: any; -}, serverValues: { - [k: string]: any; -}) => string | number | boolean; -/** - * Recursively replace all deferred values and priorities in the tree with the - * specified generated replacement values. - * @param {!SparseSnapshotTree} tree - * @param {!Object} serverValues - * @return {!SparseSnapshotTree} - */ -export declare const resolveDeferredValueTree: (tree: SparseSnapshotTree, serverValues: Object) => SparseSnapshotTree; -/** - * Recursively replace all deferred values and priorities in the node with the - * specified generated replacement values. If there are no server values in the node, - * it'll be returned as-is. - * @param {!Node} node - * @param {!Object} serverValues - * @return {!Node} - */ -export declare const resolveDeferredValueSnapshot: (node: Node, serverValues: Object) => Node; diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts deleted file mode 100644 index 0f4584d2..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/SortedMap.d.ts +++ /dev/null @@ -1,361 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Implementation of an immutable SortedMap using a Left-leaning - * Red-Black Tree, adapted from the implementation in Mugs - * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen - * (mads379@gmail.com). - * - * Original paper on Left-leaning Red-Black Trees: - * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf - * - * Invariant 1: No red node has a red child - * Invariant 2: Every leaf path has the same number of black nodes - * Invariant 3: Only the left child can be red (left leaning) - */ -export declare type Comparator = (key1: K, key2: K) => number; -/** - * An iterator over an LLRBNode. - */ -export declare class SortedMapIterator { - private isReverse_; - private resultGenerator_; - /** @private - * @type {Array.} - */ - private nodeStack_; - /** - * @template K, V, T - * @param {LLRBNode|LLRBEmptyNode} node Node to iterate. - * @param {?K} startKey - * @param {function(K, K): number} comparator - * @param {boolean} isReverse_ Whether or not to iterate in reverse - * @param {(function(K, V):T)=} resultGenerator_ - */ - constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse_: boolean, resultGenerator_?: ((k: K, v: V) => T) | null); - getNext(): T; - hasNext(): boolean; - peek(): T; -} -/** - * Represents a node in a Left-leaning Red-Black tree. - */ -export declare class LLRBNode { - key: K; - value: V; - color: boolean; - left: LLRBNode | LLRBEmptyNode; - right: LLRBNode | LLRBEmptyNode; - /** - * @template K, V - * @param {!K} key Key associated with this node. - * @param {!V} value Value associated with this node. - * @param {?boolean} color Whether this node is red. - * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child. - * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child. - */ - constructor(key: K, value: V, color: boolean | null, left?: LLRBNode | LLRBEmptyNode | null, right?: LLRBNode | LLRBEmptyNode | null); - static RED: boolean; - static BLACK: boolean; - /** - * Returns a copy of the current node, optionally replacing pieces of it. - * - * @param {?K} key New key for the node, or null. - * @param {?V} value New value for the node, or null. - * @param {?boolean} color New color for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null. - * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null. - * @return {!LLRBNode} The node copy. - */ - copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; - /** - * @return {number} The total number of nodes in the tree. - */ - count(): number; - /** - * @return {boolean} True if the tree is empty. - */ - isEmpty(): boolean; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - inorderTraversal(action: (k: K, v: V) => any): boolean; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!Object, !Object)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {*} True if traversal was aborted. - */ - reverseTraversal(action: (k: K, v: V) => void): boolean; - /** - * @return {!Object} The minimum node in the tree. - * @private - */ - private min_(); - /** - * @return {!K} The maximum key in the tree. - */ - minKey(): K; - /** - * @return {!K} The maximum key in the tree. - */ - maxKey(): K; - /** - * - * @param {!Object} key Key to insert. - * @param {!Object} value Value to insert. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with the key/value added. - */ - insert(key: K, value: V, comparator: Comparator): LLRBNode; - /** - * @private - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed. - */ - private removeMin_(); - /** - * @param {!Object} key The key of the item to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed. - */ - remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; - /** - * @private - * @return {boolean} Whether this is a RED node. - */ - isRed_(): boolean; - /** - * @private - * @return {!LLRBNode} New tree after performing any needed rotations. - */ - private fixUp_(); - /** - * @private - * @return {!LLRBNode} New tree, after moveRedLeft. - */ - private moveRedLeft_(); - /** - * @private - * @return {!LLRBNode} New tree, after moveRedRight. - */ - private moveRedRight_(); - /** - * @private - * @return {!LLRBNode} New tree, after rotateLeft. - */ - private rotateLeft_(); - /** - * @private - * @return {!LLRBNode} New tree, after rotateRight. - */ - private rotateRight_(); - /** - * @private - * @return {!LLRBNode} New tree, after colorFlip. - */ - private colorFlip_(); - /** - * For testing. - * - * @private - * @return {boolean} True if all is well. - */ - private checkMaxDepth_(); - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - check_(): number; -} -/** - * Represents an empty node (a leaf node in the Red-Black Tree). - */ -export declare class LLRBEmptyNode { - key: K; - value: V; - left: LLRBNode | LLRBEmptyNode; - right: LLRBNode | LLRBEmptyNode; - color: boolean; - /** - * Returns a copy of the current node. - * - * @return {!LLRBEmptyNode} The node copy. - */ - copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; - /** - * Returns a copy of the tree, with the specified key/value added. - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @param {Comparator} comparator Comparator. - * @return {!LLRBNode} New tree, with item added. - */ - insert(key: K, value: V, comparator: Comparator): LLRBNode; - /** - * Returns a copy of the tree, with the specified key removed. - * - * @param {!K} key The key to remove. - * @param {Comparator} comparator Comparator. - * @return {!LLRBEmptyNode} New tree, with item removed. - */ - remove(key: K, comparator: Comparator): LLRBEmptyNode; - /** - * @return {number} The total number of nodes in the tree. - */ - count(): number; - /** - * @return {boolean} True if the tree is empty. - */ - isEmpty(): boolean; - /** - * Traverses the tree in key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V):*} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - inorderTraversal(action: (k: K, v: V) => any): boolean; - /** - * Traverses the tree in reverse key order and calls the specified action function - * for each node. - * - * @param {function(!K, !V)} action Callback function to be called for each - * node. If it returns true, traversal is aborted. - * @return {boolean} True if traversal was aborted. - */ - reverseTraversal(action: (k: K, v: V) => void): boolean; - /** - * @return {null} - */ - minKey(): null; - /** - * @return {null} - */ - maxKey(): null; - /** - * @private - * @return {number} Not sure what this returns exactly. :-). - */ - check_(): number; - /** - * @private - * @return {boolean} Whether this node is red. - */ - isRed_(): boolean; -} -/** - * An immutable sorted map implementation, based on a Left-leaning Red-Black - * tree. - */ -export declare class SortedMap { - private comparator_; - private root_; - /** - * Always use the same empty node, to reduce memory. - * @const - */ - static EMPTY_NODE: LLRBEmptyNode<{}, {}>; - /** - * @template K, V - * @param {function(K, K):number} comparator_ Key comparator. - * @param {LLRBNode=} root_ (Optional) Root node for the map. - */ - constructor(comparator_: Comparator, root_?: LLRBNode | LLRBEmptyNode); - /** - * Returns a copy of the map, with the specified key/value added or replaced. - * (TODO: We should perhaps rename this method to 'put') - * - * @param {!K} key Key to be added. - * @param {!V} value Value to be added. - * @return {!SortedMap.} New map, with item added. - */ - insert(key: K, value: V): SortedMap; - /** - * Returns a copy of the map, with the specified key removed. - * - * @param {!K} key The key to remove. - * @return {!SortedMap.} New map, with item removed. - */ - remove(key: K): SortedMap; - /** - * Returns the value of the node with the given key, or null. - * - * @param {!K} key The key to look up. - * @return {?V} The value of the node with the given key, or null if the - * key doesn't exist. - */ - get(key: K): V | null; - /** - * Returns the key of the item *before* the specified key, or null if key is the first item. - * @param {K} key The key to find the predecessor of - * @return {?K} The predecessor key. - */ - getPredecessorKey(key: K): K | null; - /** - * @return {boolean} True if the map is empty. - */ - isEmpty(): boolean; - /** - * @return {number} The total number of nodes in the map. - */ - count(): number; - /** - * @return {?K} The minimum key in the map. - */ - minKey(): K | null; - /** - * @return {?K} The maximum key in the map. - */ - maxKey(): K | null; - /** - * Traverses the map in key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!K, !V):*} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} The first truthy value returned by action, or the last falsey - * value returned by action - */ - inorderTraversal(action: (k: K, v: V) => any): boolean; - /** - * Traverses the map in reverse key order and calls the specified action function - * for each key/value pair. - * - * @param {function(!Object, !Object)} action Callback function to be called - * for each key/value pair. If action returns true, traversal is aborted. - * @return {*} True if the traversal was aborted. - */ - reverseTraversal(action: (k: K, v: V) => void): boolean; - /** - * Returns an iterator over the SortedMap. - * @template T - * @param {(function(K, V):T)=} resultGenerator - * @return {SortedMapIterator.} The iterator. - */ - getIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; - getIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; - getReverseIteratorFrom(key: K, resultGenerator?: (k: K, v: V) => T): SortedMapIterator; - getReverseIterator(resultGenerator?: (k: K, v: V) => T): SortedMapIterator; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts deleted file mode 100644 index e58021d6..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/Tree.d.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { Path } from './Path'; -/** - * Node in a Tree. - */ -export declare class TreeNode { - children: { - [name: string]: TreeNode; - }; - childCount: number; - value: T | null; -} -/** - * A light-weight tree, traversable by path. Nodes can have both values and children. - * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty - * children. - */ -export declare class Tree { - private name_; - private parent_; - private node_; - /** - * @template T - * @param {string=} name_ Optional name of the node. - * @param {Tree=} parent_ Optional parent node. - * @param {TreeNode=} node_ Optional node to wrap. - */ - constructor(name_?: string, parent_?: Tree | null, node_?: TreeNode); - /** - * Returns a sub-Tree for the given path. - * - * @param {!(string|Path)} pathObj Path to look up. - * @return {!Tree.} Tree for path. - */ - subTree(pathObj: string | Path): Tree; - /** - * Returns the data associated with this tree node. - * - * @return {?T} The data or null if no data exists. - */ - getValue(): T | null; - /** - * Sets data to this tree node. - * - * @param {!T} value Value to set. - */ - setValue(value: T): void; - /** - * Clears the contents of the tree node (its value and all children). - */ - clear(): void; - /** - * @return {boolean} Whether the tree has any children. - */ - hasChildren(): boolean; - /** - * @return {boolean} Whether the tree is empty (no value or children). - */ - isEmpty(): boolean; - /** - * Calls action for each child of this tree node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - forEachChild(action: (tree: Tree) => void): void; - /** - * Does a depth-first traversal of this node's descendants, calling action for each one. - * - * @param {function(!Tree.)} action Action to be called for each child. - * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to - * false. - * @param {boolean=} childrenFirst Whether to call action on children before calling it on - * parent. - */ - forEachDescendant(action: (tree: Tree) => void, includeSelf?: boolean, childrenFirst?: boolean): void; - /** - * Calls action on each ancestor node. - * - * @param {function(!Tree.)} action Action to be called on each parent; return - * true to abort. - * @param {boolean=} includeSelf Whether to call action on this node as well. - * @return {boolean} true if the action callback returned true. - */ - forEachAncestor(action: (tree: Tree) => void, includeSelf?: boolean): boolean; - /** - * Does a depth-first traversal of this node's descendants. When a descendant with a value - * is found, action is called on it and traversal does not continue inside the node. - * Action is *not* called on this node. - * - * @param {function(!Tree.)} action Action to be called for each child. - */ - forEachImmediateDescendantWithValue(action: (tree: Tree) => void): void; - /** - * @return {!Path} The path of this tree node, as a Path. - */ - path(): Path; - /** - * @return {string} The name of the tree node. - */ - name(): string; - /** - * @return {?Tree} The parent tree node, or null if this is the root of the tree. - */ - parent(): Tree | null; - /** - * Adds or removes this child from its parent based on whether it's empty or not. - * - * @private - */ - private updateParents_(); - /** - * Adds or removes the passed child to this tree node, depending on whether it's empty. - * - * @param {string} childName The name of the child to update. - * @param {!Tree.} child The child to update. - * @private - */ - private updateChild_(childName, child); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts deleted file mode 100644 index 20327138..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/VisibilityMonitor.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { EventEmitter } from './EventEmitter'; -/** - * @extends {EventEmitter} - */ -export declare class VisibilityMonitor extends EventEmitter { - private visible_; - static getInstance(): VisibilityMonitor; - constructor(); - /** - * @param {!string} eventType - * @return {Array.} - */ - getInitialEvent(eventType: string): boolean[]; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts deleted file mode 100644 index 604dc8db..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/libs/parser.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Path } from '../Path'; -import { RepoInfo } from '../../RepoInfo'; -/** - * - * @param {!string} dataURL - * @return {{repoInfo: !RepoInfo, path: !Path}} - */ -export declare const parseRepoInfo: (dataURL: string) => { - repoInfo: RepoInfo; - path: Path; -}; -/** - * - * @param {!string} dataURL - * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}} - */ -export declare const parseURL: (dataURL: string) => { - host: string; - port: number; - domain: string; - subdomain: string; - secure: boolean; - scheme: string; - pathString: string; -}; diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/util.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/util.d.ts deleted file mode 100644 index e79fe7b3..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/util.d.ts +++ /dev/null @@ -1,223 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Query } from '../../api/Query'; -/** - * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called). - * @type {function(): number} Generated ID. - */ -export declare const LUIDGenerator: (() => number); -/** - * Sha1 hash of the input string - * @param {!string} str The string to hash - * @return {!string} The resulting hash - */ -export declare const sha1: (str: string) => string; -/** - * Use this for all debug messages in Firebase. - * @type {?function(string)} - */ -export declare let logger: ((a: string) => void) | null; -/** - * The implementation of Firebase.enableLogging (defined here to break dependencies) - * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger - * @param {boolean=} persistent Whether or not to persist logging settings across refreshes - */ -export declare const enableLogging: (logger_?: boolean | ((a: string) => void), persistent?: boolean) => void; -/** - * - * @param {...(string|Arguments)} var_args - */ -export declare const log: (...var_args: string[]) => void; -/** - * @param {!string} prefix - * @return {function(...[*])} - */ -export declare const logWrapper: (prefix: string) => (...var_args: any[]) => void; -/** - * @param {...string} var_args - */ -export declare const error: (...var_args: string[]) => void; -/** - * @param {...string} var_args - */ -export declare const fatal: (...var_args: string[]) => never; -/** - * @param {...*} var_args - */ -export declare const warn: (...var_args: any[]) => void; -/** - * Logs a warning if the containing page uses https. Called when a call to new Firebase - * does not use https. - */ -export declare const warnIfPageIsSecure: () => void; -/** - * @param {!String} methodName - */ -export declare const warnAboutUnsupportedMethod: (methodName: string) => void; -/** - * Returns true if data is NaN, or +/- Infinity. - * @param {*} data - * @return {boolean} - */ -export declare const isInvalidJSONNumber: (data: any) => boolean; -/** - * @param {function()} fn - */ -export declare const executeWhenDOMReady: (fn: () => void) => void; -/** - * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names - * @type {!string} - */ -export declare const MIN_NAME = "[MIN_NAME]"; -/** - * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names - * @type {!string} - */ -export declare const MAX_NAME = "[MAX_NAME]"; -/** - * Compares valid Firebase key names, plus min and max name - * @param {!string} a - * @param {!string} b - * @return {!number} - */ -export declare const nameCompare: (a: string, b: string) => number; -/** - * @param {!string} a - * @param {!string} b - * @return {!number} comparison result. - */ -export declare const stringCompare: (a: string, b: string) => number; -/** - * @param {string} key - * @param {Object} obj - * @return {*} - */ -export declare const requireKey: (key: string, obj: { - [k: string]: any; -}) => any; -/** - * @param {*} obj - * @return {string} - */ -export declare const ObjectToUniqueKey: (obj: any) => string; -/** - * Splits a string into a number of smaller segments of maximum size - * @param {!string} str The string - * @param {!number} segsize The maximum number of chars in the string. - * @return {Array.} The string, split into appropriately-sized chunks - */ -export declare const splitStringBySize: (str: string, segsize: number) => string[]; -/** - * Apply a function to each (key, value) pair in an object or - * apply a function to each (index, value) pair in an array - * @param {!(Object|Array)} obj The object or array to iterate over - * @param {function(?, ?)} fn The function to apply - */ -export declare const each: (obj: Object | any[], fn: (v?: any, k?: any) => void) => void; -/** - * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined. - * @param {function(*)} callback Callback function. - * @param {?Object=} context Optional context to bind to. - * @return {function(*)} - */ -export declare const bindCallback: (callback: (a: any) => void, context?: object) => Function; -/** - * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License) - * I made one modification at the end and removed the NaN / Infinity - * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments. - * @param {!number} v A double - * @return {string} - */ -export declare const doubleToIEEE754String: (v: number) => string; -/** - * Used to detect if we're in a Chrome content script (which executes in an - * isolated environment where long-polling doesn't work). - * @return {boolean} - */ -export declare const isChromeExtensionContentScript: () => boolean; -/** - * Used to detect if we're in a Windows 8 Store app. - * @return {boolean} - */ -export declare const isWindowsStoreApp: () => boolean; -/** - * Converts a server error code to a Javascript Error - * @param {!string} code - * @param {!Query} query - * @return {Error} - */ -export declare const errorForServerCode: (code: string, query: Query) => Error; -/** - * Used to test for integer-looking strings - * @type {RegExp} - * @private - */ -export declare const INTEGER_REGEXP_: RegExp; -/** - * If the string contains a 32-bit integer, return it. Else return null. - * @param {!string} str - * @return {?number} - */ -export declare const tryParseInt: (str: string) => number; -/** - * Helper to run some code but catch any exceptions and re-throw them later. - * Useful for preventing user callbacks from breaking internal code. - * - * Re-throwing the exception from a setTimeout is a little evil, but it's very - * convenient (we don't have to try to figure out when is a safe point to - * re-throw it), and the behavior seems reasonable: - * - * * If you aren't pausing on exceptions, you get an error in the console with - * the correct stack trace. - * * If you're pausing on all exceptions, the debugger will pause on your - * exception and then again when we rethrow it. - * * If you're only pausing on uncaught exceptions, the debugger will only pause - * on us re-throwing it. - * - * @param {!function()} fn The code to guard. - */ -export declare const exceptionGuard: (fn: () => void) => void; -/** - * Helper function to safely call opt_callback with the specified arguments. It: - * 1. Turns into a no-op if opt_callback is null or undefined. - * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state. - * - * @param {?Function=} callback Optional onComplete callback. - * @param {...*} var_args Arbitrary args to be passed to opt_onComplete - */ -export declare const callUserCallback: (callback?: Function, ...var_args: any[]) => void; -/** - * @return {boolean} true if we think we're currently being crawled. - */ -export declare const beingCrawled: () => boolean; -/** - * Export a property of an object using a getter function. - * - * @param {!Object} object - * @param {string} name - * @param {!function(): *} fnGet - */ -export declare const exportPropGetter: (object: Object, name: string, fnGet: () => any) => void; -/** - * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting. - * - * It is removed with clearTimeout() as normal. - * - * @param {Function} fn Function to run. - * @param {number} time Milliseconds to wait before running. - * @return {number|Object} The setTimeout() return value. - */ -export declare const setTimeoutNonBlocking: (fn: Function, time: number) => number | Object; diff --git a/functions/node_modules/@firebase/database/dist/src/core/util/validation.d.ts b/functions/node_modules/@firebase/database/dist/src/core/util/validation.d.ts deleted file mode 100644 index 86c13ff0..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/util/validation.d.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Path, ValidationPath } from './Path'; -import { RepoInfo } from '../RepoInfo'; -/** - * True for invalid Firebase keys - * @type {RegExp} - * @private - */ -export declare const INVALID_KEY_REGEX_: RegExp; -/** - * True for invalid Firebase paths. - * Allows '/' in paths. - * @type {RegExp} - * @private - */ -export declare const INVALID_PATH_REGEX_: RegExp; -/** - * Maximum number of characters to allow in leaf value - * @type {number} - * @private - */ -export declare const MAX_LEAF_SIZE_: number; -/** - * @param {*} key - * @return {boolean} - */ -export declare const isValidKey: (key: any) => boolean; -/** - * @param {string} pathString - * @return {boolean} - */ -export declare const isValidPathString: (pathString: string) => boolean; -/** - * @param {string} pathString - * @return {boolean} - */ -export declare const isValidRootPathString: (pathString: string) => boolean; -/** - * @param {*} priority - * @return {boolean} - */ -export declare const isValidPriority: (priority: any) => boolean; -/** - * Pre-validate a datum passed as an argument to Firebase function. - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -export declare const validateFirebaseDataArg: (fnName: string, argumentNumber: number, data: any, path: Path, optional: boolean) => void; -/** - * Validate a data object client-side before sending to server. - * - * @param {string} errorPrefix - * @param {*} data - * @param {!Path|!ValidationPath} path_ - */ -export declare const validateFirebaseData: (errorPrefix: string, data: any, path_: Path | ValidationPath) => void; -/** - * Pre-validate paths passed in the firebase function. - * - * @param {string} errorPrefix - * @param {Array} mergePaths - */ -export declare const validateFirebaseMergePaths: (errorPrefix: string, mergePaths: Path[]) => void; -/** - * pre-validate an object passed as an argument to firebase function ( - * must be an object - e.g. for firebase.update()). - * - * @param {string} fnName - * @param {number} argumentNumber - * @param {*} data - * @param {!Path} path - * @param {boolean} optional - */ -export declare const validateFirebaseMergeDataArg: (fnName: string, argumentNumber: number, data: any, path: Path, optional: boolean) => void; -export declare const validatePriority: (fnName: string, argumentNumber: number, priority: any, optional: boolean) => void; -export declare const validateEventType: (fnName: string, argumentNumber: number, eventType: string, optional: boolean) => void; -export declare const validateKey: (fnName: string, argumentNumber: number, key: string, optional: boolean) => void; -export declare const validatePathString: (fnName: string, argumentNumber: number, pathString: string, optional: boolean) => void; -export declare const validateRootPathString: (fnName: string, argumentNumber: number, pathString: string, optional: boolean) => void; -export declare const validateWritablePath: (fnName: string, path: Path) => void; -export declare const validateUrl: (fnName: string, argumentNumber: number, parsedUrl: { - repoInfo: RepoInfo; - path: Path; -}) => void; -export declare const validateCredential: (fnName: string, argumentNumber: number, cred: any, optional: boolean) => void; -export declare const validateBoolean: (fnName: string, argumentNumber: number, bool: any, optional: boolean) => void; -export declare const validateString: (fnName: string, argumentNumber: number, string: any, optional: boolean) => void; -export declare const validateObject: (fnName: string, argumentNumber: number, obj: any, optional: boolean) => void; -export declare const validateObjectContainsKey: (fnName: string, argumentNumber: number, obj: any, key: string, optional: boolean, opt_type?: string) => void; diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts deleted file mode 100644 index 4b9add9d..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/CacheNode.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Node } from '../snap/Node'; -import { Path } from '../util/Path'; -/** - * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully - * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g. - * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks - * whether a node potentially had children removed due to a filter. - */ -export declare class CacheNode { - private node_; - private fullyInitialized_; - private filtered_; - /** - * @param {!Node} node_ - * @param {boolean} fullyInitialized_ - * @param {boolean} filtered_ - */ - constructor(node_: Node, fullyInitialized_: boolean, filtered_: boolean); - /** - * Returns whether this node was fully initialized with either server data or a complete overwrite by the client - * @return {boolean} - */ - isFullyInitialized(): boolean; - /** - * Returns whether this node is potentially missing children due to a filter applied to the node - * @return {boolean} - */ - isFiltered(): boolean; - /** - * @param {!Path} path - * @return {boolean} - */ - isCompleteForPath(path: Path): boolean; - /** - * @param {!string} key - * @return {boolean} - */ - isCompleteForChild(key: string): boolean; - /** - * @return {!Node} - */ - getNode(): Node; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/Change.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/Change.d.ts deleted file mode 100644 index a11d50bd..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/Change.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Node } from '../snap/Node'; -/** - * @constructor - * @struct - * @param {!string} type The event type - * @param {!Node} snapshotNode The data - * @param {string=} childName The name for this child, if it's a child event - * @param {Node=} oldSnap Used for intermediate processing of child changed events - * @param {string=} prevName The name for the previous child, if applicable - */ -export declare class Change { - type: string; - snapshotNode: Node; - childName: string; - oldSnap: Node; - prevName: string; - constructor(type: string, snapshotNode: Node, childName?: string, oldSnap?: Node, prevName?: string); - /** - * @param {!Node} snapshot - * @return {!Change} - */ - static valueChange(snapshot: Node): Change; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - static childAddedChange(childKey: string, snapshot: Node): Change; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - static childRemovedChange(childKey: string, snapshot: Node): Change; - /** - * @param {string} childKey - * @param {!Node} newSnapshot - * @param {!Node} oldSnapshot - * @return {!Change} - */ - static childChangedChange(childKey: string, newSnapshot: Node, oldSnapshot: Node): Change; - /** - * @param {string} childKey - * @param {!Node} snapshot - * @return {!Change} - */ - static childMovedChange(childKey: string, snapshot: Node): Change; - /** Event type for a child added */ - static CHILD_ADDED: string; - /** Event type for a child removed */ - static CHILD_REMOVED: string; - /** Event type for a child changed */ - static CHILD_CHANGED: string; - /** Event type for a child moved */ - static CHILD_MOVED: string; - /** Event type for a value change */ - static VALUE: string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts deleted file mode 100644 index 7b5eff59..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/ChildChangeAccumulator.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Change } from './Change'; -/** - * @constructor - */ -export declare class ChildChangeAccumulator { - private changeMap_; - /** - * @param {!Change} change - */ - trackChildChange(change: Change): void; - /** - * @return {!Array.} - */ - getChanges(): Change[]; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts deleted file mode 100644 index 2d558fa4..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/CompleteChildSource.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { NamedNode, Node } from '../snap/Node'; -import { Index } from '../snap/indexes/Index'; -import { WriteTreeRef } from '../WriteTree'; -import { ViewCache } from './ViewCache'; -/** - * Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface - * can help to get complete children that can be pulled in. - * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from - * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view. - * - * @interface - */ -export interface CompleteChildSource { - /** - * @param {!string} childKey - * @return {?Node} - */ - getCompleteChild(childKey: string): Node | null; - /** - * @param {!Index} index - * @param {!NamedNode} child - * @param {boolean} reverse - * @return {?NamedNode} - */ - getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; -} -/** - * An implementation of CompleteChildSource that never returns any additional children - * - * @private - * @constructor - * @implements CompleteChildSource - */ -export declare class NoCompleteChildSource_ implements CompleteChildSource { - /** - * @inheritDoc - */ - getCompleteChild(childKey?: string): Node | null; - /** - * @inheritDoc - */ - getChildAfterChild(index?: Index, child?: NamedNode, reverse?: boolean): NamedNode | null; -} -/** - * Singleton instance. - * @const - * @type {!CompleteChildSource} - */ -export declare const NO_COMPLETE_CHILD_SOURCE: NoCompleteChildSource_; -/** - * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or - * old event caches available to calculate complete children. - * - * - * @implements CompleteChildSource - */ -export declare class WriteTreeCompleteChildSource implements CompleteChildSource { - private writes_; - private viewCache_; - private optCompleteServerCache_; - /** - * @param {!WriteTreeRef} writes_ - * @param {!ViewCache} viewCache_ - * @param {?Node} optCompleteServerCache_ - */ - constructor(writes_: WriteTreeRef, viewCache_: ViewCache, optCompleteServerCache_?: Node | null); - /** - * @inheritDoc - */ - getCompleteChild(childKey: string): Node | null; - /** - * @inheritDoc - */ - getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/Event.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/Event.d.ts deleted file mode 100644 index a9841158..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/Event.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { Path } from '../util/Path'; -import { EventRegistration } from './EventRegistration'; -import { DataSnapshot } from '../../api/DataSnapshot'; -/** - * Encapsulates the data needed to raise an event - * @interface - */ -export interface Event { - /** - * @return {!Path} - */ - getPath(): Path; - /** - * @return {!string} - */ - getEventType(): string; - /** - * @return {!function()} - */ - getEventRunner(): () => void; - /** - * @return {!string} - */ - toString(): string; -} -/** - * Encapsulates the data needed to raise an event - * @implements {Event} - */ -export declare class DataEvent implements Event { - eventType: 'value' | ' child_added' | ' child_changed' | ' child_moved' | ' child_removed'; - eventRegistration: EventRegistration; - snapshot: DataSnapshot; - prevName: string | null; - /** - * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed - * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided - * @param {!DataSnapshot} snapshot The data backing the event - * @param {?string=} prevName Optional, the name of the previous child for child_* events. - */ - constructor(eventType: 'value' | ' child_added' | ' child_changed' | ' child_moved' | ' child_removed', eventRegistration: EventRegistration, snapshot: DataSnapshot, prevName?: string | null); - /** - * @inheritDoc - */ - getPath(): Path; - /** - * @inheritDoc - */ - getEventType(): string; - /** - * @inheritDoc - */ - getEventRunner(): () => void; - /** - * @inheritDoc - */ - toString(): string; -} -export declare class CancelEvent implements Event { - eventRegistration: EventRegistration; - error: Error; - path: Path; - /** - * @param {EventRegistration} eventRegistration - * @param {Error} error - * @param {!Path} path - */ - constructor(eventRegistration: EventRegistration, error: Error, path: Path); - /** - * @inheritDoc - */ - getPath(): Path; - /** - * @inheritDoc - */ - getEventType(): string; - /** - * @inheritDoc - */ - getEventRunner(): () => void; - /** - * @inheritDoc - */ - toString(): string; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts deleted file mode 100644 index a24e9b8f..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/EventGenerator.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Node } from '../snap/Node'; -import { Change } from './Change'; -import { Query } from '../../api/Query'; -import { EventRegistration } from './EventRegistration'; -import { Event } from './Event'; -/** - * An EventGenerator is used to convert "raw" changes (Change) as computed by the - * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges() - * for details. - * - * @constructor - */ -export declare class EventGenerator { - private query_; - private index_; - /** - * - * @param {!Query} query_ - */ - constructor(query_: Query); - /** - * Given a set of raw changes (no moved events and prevName not specified yet), and a set of - * EventRegistrations that should be notified of these changes, generate the actual events to be raised. - * - * Notes: - * - child_moved events will be synthesized at this time for any child_changed events that affect - * our index. - * - prevName will be calculated based on the index ordering. - * - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {!Array.} eventRegistrations - * @return {!Array.} - */ - generateEventsForChanges(changes: Change[], eventCache: Node, eventRegistrations: EventRegistration[]): Event[]; - /** - * Given changes of a single change type, generate the corresponding events. - * - * @param {!Array.} events - * @param {!string} eventType - * @param {!Array.} changes - * @param {!Array.} registrations - * @param {!Node} eventCache - * @private - */ - private generateEventsForType_(events, eventType, changes, registrations, eventCache); - /** - * @param {!Change} change - * @param {!Node} eventCache - * @return {!Change} - * @private - */ - private materializeSingleChange_(change, eventCache); - /** - * @param {!Change} a - * @param {!Change} b - * @return {number} - * @private - */ - private compareChanges_(a, b); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts deleted file mode 100644 index 11ad4521..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/EventQueue.d.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Path } from '../util/Path'; -import { Event } from './Event'; -/** - * The event queue serves a few purposes: - * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more - * events being queued. - * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events, - * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call - * left off, ensuring that the events are still raised synchronously and in order. - * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued - * events are raised synchronously. - * - * NOTE: This can all go away if/when we move to async events. - * - * @constructor - */ -export declare class EventQueue { - /** - * @private - * @type {!Array.} - */ - private eventLists_; - /** - * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes. - * @private - * @type {!number} - */ - private recursionDepth_; - /** - * @param {!Array.} eventDataList The new events to queue. - */ - queueEvents(eventDataList: Event[]): void; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) - * for the specified path. - * - * It is assumed that the new events are all for the specified path. - * - * @param {!Path} path The path to raise events for. - * @param {!Array.} eventDataList The new events to raise. - */ - raiseEventsAtPath(path: Path, eventDataList: Event[]): void; - /** - * Queues the specified events and synchronously raises all events (including previously queued ones) for - * locations related to the specified change path (i.e. all ancestors and descendants). - * - * It is assumed that the new events are all related (ancestor or descendant) to the specified path. - * - * @param {!Path} changedPath The path to raise events for. - * @param {!Array.} eventDataList The events to raise - */ - raiseEventsForChangedPath(changedPath: Path, eventDataList: Event[]): void; - /** - * @param {!function(!Path):boolean} predicate - * @private - */ - private raiseQueuedEventsMatchingPredicate_(predicate); -} -/** - * @param {!Path} path - * @constructor - */ -export declare class EventList { - private readonly path_; - /** - * @type {!Array.} - * @private - */ - private events_; - constructor(path_: Path); - /** - * @param {!Event} eventData - */ - add(eventData: Event): void; - /** - * Iterates through the list and raises each event - */ - raise(): void; - /** - * @return {!Path} - */ - getPath(): Path; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts deleted file mode 100644 index edc5ec95..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/EventRegistration.d.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { DataSnapshot } from '../../api/DataSnapshot'; -import { DataEvent, CancelEvent, Event } from './Event'; -import { Path } from '../util/Path'; -import { Change } from './Change'; -import { Query } from '../../api/Query'; -/** - * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback - * to be notified of that type of event. - * - * That said, it can also contain a cancel callback to be notified if the event is canceled. And - * currently, this code is organized around the idea that you would register multiple child_ callbacks - * together, as a single EventRegistration. Though currently we don't do that. - */ -export interface EventRegistration { - /** - * True if this container has a callback to trigger for this event type - * @param {!string} eventType - * @return {boolean} - */ - respondsTo(eventType: string): boolean; - /** - * @param {!Change} change - * @param {!Query} query - * @return {!Event} - */ - createEvent(change: Change, query: Query): Event; - /** - * Given event data, return a function to trigger the user's callback - * @param {!Event} eventData - * @return {function()} - */ - getEventRunner(eventData: Event): () => void; - /** - * @param {!Error} error - * @param {!Path} path - * @return {?CancelEvent} - */ - createCancelEvent(error: Error, path: Path): CancelEvent | null; - /** - * @param {!EventRegistration} other - * @return {boolean} - */ - matches(other: EventRegistration): boolean; - /** - * False basically means this is a "dummy" callback container being used as a sentinel - * to remove all callback containers of a particular type. (e.g. if the user does - * ref.off('value') without specifying a specific callback). - * - * (TODO: Rework this, since it's hacky) - * - * @return {boolean} - */ - hasAnyCallback(): boolean; -} -/** - * Represents registration for 'value' events. - */ -export declare class ValueEventRegistration implements EventRegistration { - private callback_; - private cancelCallback_; - private context_; - /** - * @param {?function(!DataSnapshot)} callback_ - * @param {?function(Error)} cancelCallback_ - * @param {?Object} context_ - */ - constructor(callback_: ((d: DataSnapshot) => void) | null, cancelCallback_: ((e: Error) => void) | null, context_: Object | null); - /** - * @inheritDoc - */ - respondsTo(eventType: string): boolean; - /** - * @inheritDoc - */ - createEvent(change: Change, query: Query): DataEvent; - /** - * @inheritDoc - */ - getEventRunner(eventData: CancelEvent | DataEvent): () => void; - /** - * @inheritDoc - */ - createCancelEvent(error: Error, path: Path): CancelEvent | null; - /** - * @inheritDoc - */ - matches(other: EventRegistration): boolean; - /** - * @inheritDoc - */ - hasAnyCallback(): boolean; -} -/** - * Represents the registration of 1 or more child_xxx events. - * - * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you - * register a group of callbacks together in the future. - * - * @constructor - * @implements {EventRegistration} - */ -export declare class ChildEventRegistration implements EventRegistration { - private callbacks_; - private cancelCallback_; - private context_; - /** - * @param {?Object.} callbacks_ - * @param {?function(Error)} cancelCallback_ - * @param {Object=} context_ - */ - constructor(callbacks_: ({ - [k: string]: (d: DataSnapshot, s?: string | null) => void; - }) | null, cancelCallback_: ((e: Error) => void) | null, context_?: Object); - /** - * @inheritDoc - */ - respondsTo(eventType: string): boolean; - /** - * @inheritDoc - */ - createCancelEvent(error: Error, path: Path): CancelEvent | null; - /** - * @inheritDoc - */ - createEvent(change: Change, query: Query): DataEvent; - /** - * @inheritDoc - */ - getEventRunner(eventData: CancelEvent | DataEvent): () => void; - /** - * @inheritDoc - */ - matches(other: EventRegistration): boolean; - /** - * @inheritDoc - */ - hasAnyCallback(): boolean; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts deleted file mode 100644 index 206a6a48..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/QueryParams.d.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { NodeFilter } from './filter/NodeFilter'; -import { Index } from '../snap/indexes/Index'; -/** - * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a - * range to be returned for a particular location. It is assumed that validation of parameters is done at the - * user-facing API level, so it is not done here. - * @constructor - */ -export declare class QueryParams { - private limitSet_; - private startSet_; - private startNameSet_; - private endSet_; - private endNameSet_; - private limit_; - private viewFrom_; - private indexStartValue_; - private indexStartName_; - private indexEndValue_; - private indexEndName_; - private index_; - /** - * Wire Protocol Constants - * @const - * @enum {string} - * @private - */ - private static readonly WIRE_PROTOCOL_CONSTANTS_; - /** - * REST Query Constants - * @const - * @enum {string} - * @private - */ - private static readonly REST_QUERY_CONSTANTS_; - /** - * Default, empty query parameters - * @type {!QueryParams} - * @const - */ - static readonly DEFAULT: QueryParams; - /** - * @return {boolean} - */ - hasStart(): boolean; - /** - * @return {boolean} True if it would return from left. - */ - isViewFromLeft(): boolean; - /** - * Only valid to call if hasStart() returns true - * @return {*} - */ - getIndexStartValue(): any; - /** - * Only valid to call if hasStart() returns true. - * Returns the starting key name for the range defined by these query parameters - * @return {!string} - */ - getIndexStartName(): string; - /** - * @return {boolean} - */ - hasEnd(): boolean; - /** - * Only valid to call if hasEnd() returns true. - * @return {*} - */ - getIndexEndValue(): any; - /** - * Only valid to call if hasEnd() returns true. - * Returns the end key name for the range defined by these query parameters - * @return {!string} - */ - getIndexEndName(): string; - /** - * @return {boolean} - */ - hasLimit(): boolean; - /** - * @return {boolean} True if a limit has been set and it has been explicitly anchored - */ - hasAnchoredLimit(): boolean; - /** - * Only valid to call if hasLimit() returns true - * @return {!number} - */ - getLimit(): number; - /** - * @return {!Index} - */ - getIndex(): Index; - /** - * @return {!QueryParams} - * @private - */ - private copy_(); - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - limit(newLimit: number): QueryParams; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - limitToFirst(newLimit: number): QueryParams; - /** - * @param {!number} newLimit - * @return {!QueryParams} - */ - limitToLast(newLimit: number): QueryParams; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - startAt(indexValue: any, key?: string | null): QueryParams; - /** - * @param {*} indexValue - * @param {?string=} key - * @return {!QueryParams} - */ - endAt(indexValue: any, key?: string | null): QueryParams; - /** - * @param {!Index} index - * @return {!QueryParams} - */ - orderBy(index: Index): QueryParams; - /** - * @return {!Object} - */ - getQueryObject(): Object; - /** - * @return {boolean} - */ - loadsAllData(): boolean; - /** - * @return {boolean} - */ - isDefault(): boolean; - /** - * @return {!NodeFilter} - */ - getNodeFilter(): NodeFilter; - /** - * Returns a set of REST query string parameters representing this query. - * - * @return {!Object.} query string parameters - */ - toRestQueryStringParameters(): { - [k: string]: any; - }; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/View.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/View.d.ts deleted file mode 100644 index 606efd81..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/View.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { ViewCache } from './ViewCache'; -import { Operation } from '../operation/Operation'; -import { Change } from './Change'; -import { Query } from '../../api/Query'; -import { EventRegistration } from './EventRegistration'; -import { Node } from '../snap/Node'; -import { Path } from '../util/Path'; -import { WriteTreeRef } from '../WriteTree'; -import { Event } from './Event'; -/** - * A view represents a specific location and query that has 1 or more event registrations. - * - * It does several things: - * - Maintains the list of event registrations for this location/query. - * - Maintains a cache of the data visible for this location/query. - * - Applies new operations (via applyOperation), updates the cache, and based on the event - * registrations returns the set of events to be raised. - * @constructor - */ -export declare class View { - private query_; - private processor_; - private viewCache_; - private eventRegistrations_; - private eventGenerator_; - /** - * - * @param {!Query} query_ - * @param {!ViewCache} initialViewCache - */ - constructor(query_: Query, initialViewCache: ViewCache); - /** - * @return {!Query} - */ - getQuery(): Query; - /** - * @return {?Node} - */ - getServerCache(): Node | null; - /** - * @param {!Path} path - * @return {?Node} - */ - getCompleteServerCache(path: Path): Node | null; - /** - * @return {boolean} - */ - isEmpty(): boolean; - /** - * @param {!EventRegistration} eventRegistration - */ - addEventRegistration(eventRegistration: EventRegistration): void; - /** - * @param {?EventRegistration} eventRegistration If null, remove all callbacks. - * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned. - * @return {!Array.} Cancel events, if cancelError was provided. - */ - removeEventRegistration(eventRegistration: EventRegistration | null, cancelError?: Error): Event[]; - /** - * Applies the given Operation, updates our cache, and returns the appropriate events. - * - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @return {!Array.} - */ - applyOperation(operation: Operation, writesCache: WriteTreeRef, completeServerCache: Node | null): Event[]; - /** - * @param {!EventRegistration} registration - * @return {!Array.} - */ - getInitialEvents(registration: EventRegistration): Event[]; - /** - * @private - * @param {!Array.} changes - * @param {!Node} eventCache - * @param {EventRegistration=} eventRegistration - * @return {!Array.} - */ - generateEventsForChanges_(changes: Change[], eventCache: Node, eventRegistration?: EventRegistration): Event[]; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts deleted file mode 100644 index f7275db3..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/ViewCache.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { CacheNode } from './CacheNode'; -import { Node } from '../snap/Node'; -/** - * Stores the data we have cached for a view. - * - * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes). - * - * @constructor - */ -export declare class ViewCache { - private readonly eventCache_; - private readonly serverCache_; - /** - * - * @param {!CacheNode} eventCache_ - * @param {!CacheNode} serverCache_ - */ - constructor(eventCache_: CacheNode, serverCache_: CacheNode); - /** - * @const - * @type {ViewCache} - */ - static Empty: ViewCache; - /** - * @param {!Node} eventSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - updateEventSnap(eventSnap: Node, complete: boolean, filtered: boolean): ViewCache; - /** - * @param {!Node} serverSnap - * @param {boolean} complete - * @param {boolean} filtered - * @return {!ViewCache} - */ - updateServerSnap(serverSnap: Node, complete: boolean, filtered: boolean): ViewCache; - /** - * @return {!CacheNode} - */ - getEventCache(): CacheNode; - /** - * @return {?Node} - */ - getCompleteEventSnap(): Node | null; - /** - * @return {!CacheNode} - */ - getServerCache(): CacheNode; - /** - * @return {?Node} - */ - getCompleteServerSnap(): Node | null; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts deleted file mode 100644 index 8e78fccd..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/ViewProcessor.d.ts +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Operation } from '../operation/Operation'; -import { ChildChangeAccumulator } from './ChildChangeAccumulator'; -import { Change } from './Change'; -import { Path } from '../util/Path'; -import { ViewCache } from './ViewCache'; -import { NodeFilter } from './filter/NodeFilter'; -import { WriteTreeRef } from '../WriteTree'; -import { Node } from '../snap/Node'; -/** - * @constructor - * @struct - */ -export declare class ProcessorResult { - readonly viewCache: ViewCache; - readonly changes: Change[]; - /** - * @param {!ViewCache} viewCache - * @param {!Array.} changes - */ - constructor(viewCache: ViewCache, changes: Change[]); -} -/** - * @constructor - */ -export declare class ViewProcessor { - private readonly filter_; - /** - * @param {!NodeFilter} filter_ - */ - constructor(filter_: NodeFilter); - /** - * @param {!ViewCache} viewCache - */ - assertIndexed(viewCache: ViewCache): void; - /** - * @param {!ViewCache} oldViewCache - * @param {!Operation} operation - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @return {!ProcessorResult} - */ - applyOperation(oldViewCache: ViewCache, operation: Operation, writesCache: WriteTreeRef, completeCache: Node | null): ProcessorResult; - /** - * @param {!ViewCache} oldViewCache - * @param {!ViewCache} newViewCache - * @param {!Array.} accumulator - * @private - */ - private static maybeAddValueEvent_(oldViewCache, newViewCache, accumulator); - /** - * @param {!ViewCache} viewCache - * @param {!Path} changePath - * @param {!WriteTreeRef} writesCache - * @param {!CompleteChildSource} source - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - private generateEventCacheAfterServerEvent_(viewCache, changePath, writesCache, source, accumulator); - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - applyServerOverwrite_(oldViewCache: ViewCache, changePath: Path, changedSnap: Node, writesCache: WriteTreeRef, completeCache: Node | null, filterServerNode: boolean, accumulator: ChildChangeAccumulator): ViewCache; - /** - * @param {!ViewCache} oldViewCache - * @param {!Path} changePath - * @param {!Node} changedSnap - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - applyUserOverwrite_(oldViewCache: ViewCache, changePath: Path, changedSnap: Node, writesCache: WriteTreeRef, completeCache: Node | null, accumulator: ChildChangeAccumulator): ViewCache; - /** - * @param {!ViewCache} viewCache - * @param {string} childKey - * @return {boolean} - * @private - */ - private static cacheHasChild_(viewCache, childKey); - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - private applyUserMerge_(viewCache, path, changedChildren, writesCache, serverCache, accumulator); - /** - * @param {!Node} node - * @param {ImmutableTree.} merge - * @return {!Node} - * @private - */ - private applyMerge_(node, merge); - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!ImmutableTree.} changedChildren - * @param {!WriteTreeRef} writesCache - * @param {?Node} serverCache - * @param {boolean} filterServerNode - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - private applyServerMerge_(viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator); - /** - * @param {!ViewCache} viewCache - * @param {!Path} ackPath - * @param {!ImmutableTree} affectedTree - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - private ackUserWrite_(viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator); - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - private listenComplete_(viewCache, path, writesCache, accumulator); - /** - * @param {!ViewCache} viewCache - * @param {!Path} path - * @param {!WriteTreeRef} writesCache - * @param {?Node} completeServerCache - * @param {!ChildChangeAccumulator} accumulator - * @return {!ViewCache} - * @private - */ - private revertUserWrite_(viewCache, path, writesCache, completeServerCache, accumulator); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts deleted file mode 100644 index 49869e90..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/filter/IndexedFilter.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { NodeFilter } from './NodeFilter'; -import { Index } from '../../snap/indexes/Index'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -import { Node } from '../../snap/Node'; -/** - * Doesn't really filter nodes but applies an index to the node and keeps track of any changes - * - * @constructor - * @implements {NodeFilter} - * @param {!Index} index - */ -export declare class IndexedFilter implements NodeFilter { - private readonly index_; - constructor(index_: Index); - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * @inheritDoc - */ - filtersNodes(): boolean; - /** - * @inheritDoc - */ - getIndexedFilter(): IndexedFilter; - /** - * @inheritDoc - */ - getIndex(): Index; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts deleted file mode 100644 index 1bd0e053..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/filter/LimitedFilter.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Node } from '../../snap/Node'; -import { NodeFilter } from './NodeFilter'; -import { Index } from '../../snap/indexes/Index'; -import { IndexedFilter } from './IndexedFilter'; -import { QueryParams } from '../QueryParams'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -/** - * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible - * - * @constructor - * @implements {NodeFilter} - */ -export declare class LimitedFilter implements NodeFilter { - /** - * @const - * @type {RangedFilter} - * @private - */ - private readonly rangedFilter_; - /** - * @const - * @type {!Index} - * @private - */ - private readonly index_; - /** - * @const - * @type {number} - * @private - */ - private readonly limit_; - /** - * @const - * @type {boolean} - * @private - */ - private readonly reverse_; - /** - * @param {!QueryParams} params - */ - constructor(params: QueryParams); - /** - * @inheritDoc - */ - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * @inheritDoc - */ - filtersNodes(): boolean; - /** - * @inheritDoc - */ - getIndexedFilter(): IndexedFilter; - /** - * @inheritDoc - */ - getIndex(): Index; - /** - * @param {!Node} snap - * @param {string} childKey - * @param {!Node} childSnap - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} changeAccumulator - * @return {!Node} - * @private - */ - private fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator); -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts deleted file mode 100644 index 7846f09a..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/filter/NodeFilter.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Node } from '../../snap/Node'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -import { Index } from '../../snap/indexes/Index'; -/** - * NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping - * track of any child changes. This class does not track value changes as value changes depend on more - * than just the node itself. Different kind of queries require different kind of implementations of this interface. - * @interface - */ -export interface NodeFilter { - /** - * Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op. - * The method expects an indexed snap. - * - * @param {!Node} snap - * @param {string} key - * @param {!Node} newChild - * @param {!Path} affectedPath - * @param {!CompleteChildSource} source - * @param {?ChildChangeAccumulator} optChangeAccumulator - * @return {!Node} - */ - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * Update a node in full and output any resulting change from this complete update. - * - * @param {!Node} oldSnap - * @param {!Node} newSnap - * @param {?ChildChangeAccumulator} optChangeAccumulator - * @return {!Node} - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * Update the priority of the root node - * - * @param {!Node} oldSnap - * @param {!Node} newPriority - * @return {!Node} - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * Returns true if children might be filtered due to query criteria - * - * @return {boolean} - */ - filtersNodes(): boolean; - /** - * Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children. - * @return {!NodeFilter} - */ - getIndexedFilter(): NodeFilter; - /** - * Returns the index that this filter uses - * @return {!Index} - */ - getIndex(): Index; -} diff --git a/functions/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts b/functions/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts deleted file mode 100644 index 83de78e9..00000000 --- a/functions/node_modules/@firebase/database/dist/src/core/view/filter/RangedFilter.d.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { IndexedFilter } from './IndexedFilter'; -import { NamedNode, Node } from '../../../core/snap/Node'; -import { NodeFilter } from './NodeFilter'; -import { QueryParams } from '../QueryParams'; -import { Index } from '../../snap/indexes/Index'; -import { Path } from '../../util/Path'; -import { CompleteChildSource } from '../CompleteChildSource'; -import { ChildChangeAccumulator } from '../ChildChangeAccumulator'; -/** - * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node - * - * @constructor - * @implements {NodeFilter} - */ -export declare class RangedFilter implements NodeFilter { - /** - * @type {!IndexedFilter} - * @const - * @private - */ - private indexedFilter_; - /** - * @const - * @type {!Index} - * @private - */ - private index_; - /** - * @const - * @type {!NamedNode} - * @private - */ - private startPost_; - /** - * @const - * @type {!NamedNode} - * @private - */ - private endPost_; - /** - * @param {!QueryParams} params - */ - constructor(params: QueryParams); - /** - * @return {!NamedNode} - */ - getStartPost(): NamedNode; - /** - * @return {!NamedNode} - */ - getEndPost(): NamedNode; - /** - * @param {!NamedNode} node - * @return {boolean} - */ - matches(node: NamedNode): boolean; - /** - * @inheritDoc - */ - updateChild(snap: Node, key: string, newChild: Node, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updateFullNode(oldSnap: Node, newSnap: Node, optChangeAccumulator: ChildChangeAccumulator | null): Node; - /** - * @inheritDoc - */ - updatePriority(oldSnap: Node, newPriority: Node): Node; - /** - * @inheritDoc - */ - filtersNodes(): boolean; - /** - * @inheritDoc - */ - getIndexedFilter(): IndexedFilter; - /** - * @inheritDoc - */ - getIndex(): Index; - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - private static getStartPost_(params); - /** - * @param {!QueryParams} params - * @return {!NamedNode} - * @private - */ - private static getEndPost_(params); -} diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts deleted file mode 100644 index 6ddbf213..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/BrowserPollConnection.d.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { CountedSet } from '../core/util/CountedSet'; -import { PacketReceiver } from './polling/PacketReceiver'; -import { Transport } from './Transport'; -import { RepoInfo } from '../core/RepoInfo'; -export declare const FIREBASE_LONGPOLL_START_PARAM = "start"; -export declare const FIREBASE_LONGPOLL_CLOSE_COMMAND = "close"; -export declare const FIREBASE_LONGPOLL_COMMAND_CB_NAME = "pLPCommand"; -export declare const FIREBASE_LONGPOLL_DATA_CB_NAME = "pRTLPCB"; -export declare const FIREBASE_LONGPOLL_ID_PARAM = "id"; -export declare const FIREBASE_LONGPOLL_PW_PARAM = "pw"; -export declare const FIREBASE_LONGPOLL_SERIAL_PARAM = "ser"; -export declare const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = "cb"; -export declare const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg"; -export declare const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts"; -export declare const FIREBASE_LONGPOLL_DATA_PARAM = "d"; -export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = "disconn"; -export declare const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe"; -/** - * This class manages a single long-polling connection. - * - * @constructor - * @implements {Transport} - */ -export declare class BrowserPollConnection implements Transport { - connId: string; - repoInfo: RepoInfo; - transportSessionId: string; - lastSessionId: string; - bytesSent: number; - bytesReceived: number; - urlFn: (params: object) => string; - scriptTagHolder: FirebaseIFrameScriptHolder; - myDisconnFrame: HTMLIFrameElement; - curSegmentNum: number; - myPacketOrderer: PacketReceiver; - id: string; - password: string; - private log_; - private stats_; - private everConnected_; - private isClosed_; - private connectTimeoutTimer_; - private onDisconnect_; - /** - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing - * transport session - * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a - * connection previously - */ - constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); - /** - * - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - open(onMessage: (msg: Object) => void, onDisconnect: (a?: boolean) => void): void; - /** - * Call this when a handshake has completed successfully and we want to consider the connection established - */ - start(): void; - private static forceAllow_; - /** - * Forces long polling to be considered as a potential transport - */ - static forceAllow(): void; - private static forceDisallow_; - /** - * Forces longpolling to not be considered as a potential transport - */ - static forceDisallow(): void; - static isAvailable(): boolean; - /** - * No-op for polling - */ - markConnectionHealthy(): void; - /** - * Stops polling and cleans up the iframe - * @private - */ - private shutdown_(); - /** - * Triggered when this transport is closed - * @private - */ - private onClosed_(); - /** - * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server - * that we've left. - */ - close(): void; - /** - * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then - * broken into chunks (since URLs have a small maximum length). - * @param {!Object} data The JSON data to transmit. - */ - send(data: Object): void; - /** - * This is how we notify the server that we're leaving. - * We aren't able to send requests with DHTML on a window close event, but we can - * trigger XHR requests in some browsers (everything but Opera basically). - * @param {!string} id - * @param {!string} pw - */ - addDisconnectPingFrame(id: string, pw: string): void; - /** - * Used to track the bytes received by this client - * @param {*} args - * @private - */ - private incrementIncomingBytes_(args); -} -export interface IFrameElement extends HTMLIFrameElement { - doc: Document; -} -/********************************************************************************************* - * A wrapper around an iframe that is used as a long-polling script holder. - * @constructor - *********************************************************************************************/ -export declare class FirebaseIFrameScriptHolder { - onDisconnect: () => void; - urlFn: (a: object) => string; - /** - * @type {CountedSet.} - */ - outstandingRequests: CountedSet; - pendingSegs: { - seg: number; - ts: number; - d: any; - }[]; - currentSerial: number; - sendNewPolls: boolean; - uniqueCallbackIdentifier: number; - myIFrame: IFrameElement; - alive: boolean; - myID: string; - myPW: string; - commandCB: (command: string, ...args: any[]) => void; - onMessageCB: (...args: any[]) => void; - /** - * @param commandCB - The callback to be called when control commands are recevied from the server. - * @param onMessageCB - The callback to be triggered when responses arrive from the server. - * @param onDisconnect - The callback to be triggered when this tag holder is closed - * @param urlFn - A function that provides the URL of the endpoint to send data to. - */ - constructor(commandCB: (command: string, ...args: any[]) => void, onMessageCB: (...args: any[]) => void, onDisconnect: () => void, urlFn: (a: object) => string); - /** - * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can - * actually use. - * @private - * @return {Element} - */ - private static createIFrame_(); - /** - * Cancel all outstanding queries and remove the frame. - */ - close(): void; - /** - * Actually start the long-polling session by adding the first script tag(s) to the iframe. - * @param {!string} id - The ID of this connection - * @param {!string} pw - The password for this connection - */ - startLongPoll(id: string, pw: string): void; - /** - * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't - * too many outstanding requests and we are still alive. - * - * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if - * needed. - */ - private newRequest_(); - /** - * Queue a packet for transmission to the server. - * @param segnum - A sequential id for this packet segment used for reassembly - * @param totalsegs - The total number of segments in this packet - * @param data - The data for this segment. - */ - enqueueSegment(segnum: number, totalsegs: number, data: any): void; - /** - * Add a script tag for a regular long-poll request. - * @param {!string} url - The URL of the script tag. - * @param {!number} serial - The serial number of the request. - * @private - */ - private addLongPollTag_(url, serial); - /** - * Add an arbitrary script tag to the iframe. - * @param {!string} url - The URL for the script tag source. - * @param {!function()} loadCB - A callback to be triggered once the script has loaded. - */ - addTag(url: string, loadCB: () => void): void; -} diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts deleted file mode 100644 index 62f5d648..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/Connection.d.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { RepoInfo } from '../core/RepoInfo'; -/** - * Creates a new real-time connection to the server using whichever method works - * best in the current browser. - * - * @constructor - */ -export declare class Connection { - id: string; - private repoInfo_; - private onMessage_; - private onReady_; - private onDisconnect_; - private onKill_; - lastSessionId: string; - connectionCount: number; - pendingDataMessages: any[]; - sessionId: string; - private conn_; - private healthyTimeout_; - private isHealthy_; - private log_; - private primaryResponsesRequired_; - private rx_; - private secondaryConn_; - private secondaryResponsesRequired_; - private state_; - private transportManager_; - private tx_; - /** - * @param {!string} id - an id for this connection - * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to - * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives - * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages. - * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost - * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down. - * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server - */ - constructor(id: string, repoInfo_: RepoInfo, onMessage_: (a: Object) => void, onReady_: (a: number, b: string) => void, onDisconnect_: () => void, onKill_: (a: string) => void, lastSessionId?: string); - /** - * Starts a connection attempt - * @private - */ - private start_(); - /** - * @return {!string} - * @private - */ - private nextTransportId_(); - private disconnReceiver_(conn); - private connReceiver_(conn); - /** - * - * @param {Object} dataMsg An arbitrary data message to be sent to the server - */ - sendRequest(dataMsg: object): void; - tryCleanupConnection(): void; - private onSecondaryControl_(controlData); - private onSecondaryMessageReceived_(parsedData); - private upgradeIfSecondaryHealthy_(); - private proceedWithUpgrade_(); - private onPrimaryMessageReceived_(parsedData); - private onDataMessage_(message); - private onPrimaryResponse_(); - private onControl_(controlData); - /** - * - * @param {Object} handshake The handshake data returned from the server - * @private - */ - private onHandshake_(handshake); - private tryStartUpgrade_(); - private startUpgrade_(conn); - private onReset_(host); - private onConnectionEstablished_(conn, timestamp); - private sendPingOnPrimaryIfNecessary_(); - private onSecondaryConnectionLost_(); - /** - * - * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if - * we should flush the host cache - * @private - */ - private onConnectionLost_(everConnected); - /** - * - * @param {string} reason - * @private - */ - private onConnectionShutdown_(reason); - private sendData_(data); - /** - * Cleans up this connection, calling the appropriate callbacks - */ - close(): void; - /** - * - * @private - */ - private closeConnections_(); -} diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts deleted file mode 100644 index 54774cb6..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/Constants.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export declare const PROTOCOL_VERSION = "5"; -export declare const VERSION_PARAM = "v"; -export declare const TRANSPORT_SESSION_PARAM = "s"; -export declare const REFERER_PARAM = "r"; -export declare const FORGE_REF = "f"; -export declare const FORGE_DOMAIN = "firebaseio.com"; -export declare const LAST_SESSION_PARAM = "ls"; -export declare const WEBSOCKET = "websocket"; -export declare const LONG_POLLING = "long_polling"; diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts deleted file mode 100644 index e3bad3dc..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/Transport.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { RepoInfo } from '../core/RepoInfo'; -export interface TransportConstructor { - new (connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string): Transport; - isAvailable: () => boolean; - responsesRequiredToBeHealthy?: number; - healthyTimeout?: number; -} -export declare abstract class Transport { - /** - * Bytes received since connection started. - * @type {number} - */ - abstract bytesReceived: number; - /** - * Bytes sent since connection started. - * @type {number} - */ - abstract bytesSent: number; - /** - * An identifier for this connection, used for logging - * @type {string} - */ - abstract connId: string; - /** - * - * @param {string} connId An identifier for this connection, used for logging - * @param {RepoInfo} repoInfo The info for the endpoint to send data to. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @interface - */ - constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); - /** - * @param {function(Object)} onMessage Callback when messages arrive - * @param {function()} onDisconnect Callback with connection lost. - */ - abstract open(onMessage: (a: Object) => void, onDisconnect: (a?: boolean) => void): void; - abstract start(): void; - abstract close(): void; - /** - * @param {!Object} data The JSON data to transmit - */ - abstract send(data: Object): void; - abstract markConnectionHealthy(): void; - abstract markConnectionHealthy(): void; -} -export interface TransportConstructor { - new (connId: string, RepoInfo: any, transportSessionId?: string, lastSessionId?: string): any; -} diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts deleted file mode 100644 index fa8ca042..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/TransportManager.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { BrowserPollConnection } from './BrowserPollConnection'; -import { WebSocketConnection } from './WebSocketConnection'; -import { TransportConstructor } from './Transport'; -import { RepoInfo } from '../core/RepoInfo'; -/** - * Currently simplistic, this class manages what transport a Connection should use at various stages of its - * lifecycle. - * - * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if - * they are available. - * @constructor - */ -export declare class TransportManager { - private transports_; - /** - * @const - * @type {!Array.} - */ - static readonly ALL_TRANSPORTS: (typeof BrowserPollConnection | typeof WebSocketConnection)[]; - /** - * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to - */ - constructor(repoInfo: RepoInfo); - /** - * @param {!RepoInfo} repoInfo - * @private - */ - private initTransports_(repoInfo); - /** - * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the - * initial transport to use - */ - initialTransport(): TransportConstructor; - /** - * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next - * transport, or null - */ - upgradeTransport(): TransportConstructor | null; -} diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts deleted file mode 100644 index 76c21237..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/WebSocketConnection.d.ts +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { RepoInfo } from '../core/RepoInfo'; -import { Transport } from './Transport'; -export declare function setWebSocketImpl(impl: any): void; -/** - * Create a new websocket connection with the given callbacks. - * @constructor - * @implements {Transport} - */ -export declare class WebSocketConnection implements Transport { - connId: string; - keepaliveTimer: number | null; - frames: string[] | null; - totalFrames: number; - bytesSent: number; - bytesReceived: number; - connURL: string; - onDisconnect: (a?: boolean) => void; - onMessage: (msg: Object) => void; - mySock: any | null; - private log_; - private stats_; - private everConnected_; - private isClosed_; - /** - * @param {string} connId identifier for this transport - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - */ - constructor(connId: string, repoInfo: RepoInfo, transportSessionId?: string, lastSessionId?: string); - /** - * @param {RepoInfo} repoInfo The info for the websocket endpoint. - * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport - * session - * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection - * @return {string} connection url - * @private - */ - private static connectionURL_(repoInfo, transportSessionId?, lastSessionId?); - /** - * - * @param onMessage Callback when messages arrive - * @param onDisconnect Callback with connection lost. - */ - open(onMessage: (msg: Object) => void, onDisconnect: (a?: boolean) => void): void; - /** - * No-op for websockets, we don't need to do anything once the connection is confirmed as open - */ - start(): void; - static forceDisallow_: Boolean; - static forceDisallow(): void; - static isAvailable(): boolean; - /** - * Number of response before we consider the connection "healthy." - * @type {number} - */ - static responsesRequiredToBeHealthy: number; - /** - * Time to wait for the connection te become healthy before giving up. - * @type {number} - */ - static healthyTimeout: number; - /** - * Returns true if we previously failed to connect with this transport. - * @return {boolean} - */ - static previouslyFailed(): boolean; - markConnectionHealthy(): void; - private appendFrame_(data); - /** - * @param {number} frameCount The number of frames we are expecting from the server - * @private - */ - private handleNewFrameCount_(frameCount); - /** - * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1 - * @param {!String} data - * @return {?String} Any remaining data to be process, or null if there is none - * @private - */ - private extractFrameCount_(data); - /** - * Process a websocket frame that has arrived from the server. - * @param mess The frame data - */ - handleIncomingFrame(mess: { - [k: string]: any; - }): void; - /** - * Send a message to the server - * @param {Object} data The JSON object to transmit - */ - send(data: Object): void; - private shutdown_(); - private onClosed_(); - /** - * External-facing close handler. - * Close the websocket and kill the connection. - */ - close(): void; - /** - * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after - * the last activity. - */ - resetKeepAlive(): void; - /** - * Send a string over the websocket. - * - * @param {string} str String to send. - * @private - */ - private sendString_(str); -} diff --git a/functions/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts b/functions/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts deleted file mode 100644 index 734d6b01..00000000 --- a/functions/node_modules/@firebase/database/dist/src/realtime/polling/PacketReceiver.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * This class ensures the packets from the server arrive in order - * This class takes data from the server and ensures it gets passed into the callbacks in order. - * @constructor - */ -export declare class PacketReceiver { - private onMessage_; - pendingResponses: any[]; - currentResponseNum: number; - closeAfterResponse: number; - onClose: (() => void) | null; - /** - * @param onMessage_ - */ - constructor(onMessage_: (a: Object) => void); - closeAfter(responseNum: number, callback: () => void): void; - /** - * Each message from the server comes with a response number, and an array of data. The responseNumber - * allows us to ensure that we process them in the right order, since we can't be guaranteed that all - * browsers will respond in the same order as the requests we sent - * @param {number} requestNum - * @param {Array} data - */ - handleResponse(requestNum: number, data: any[]): void; -} diff --git a/functions/node_modules/@firebase/database/dist/test/browser/crawler_support.test.d.ts b/functions/node_modules/@firebase/database/dist/test/browser/crawler_support.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/browser/crawler_support.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/compound_write.test.d.ts b/functions/node_modules/@firebase/database/dist/test/compound_write.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/compound_write.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/connection.test.d.ts b/functions/node_modules/@firebase/database/dist/test/connection.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/connection.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/database.test.d.ts b/functions/node_modules/@firebase/database/dist/test/database.test.d.ts deleted file mode 100644 index 872ffe6c..00000000 --- a/functions/node_modules/@firebase/database/dist/test/database.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -import '../index'; diff --git a/functions/node_modules/@firebase/database/dist/test/datasnapshot.test.d.ts b/functions/node_modules/@firebase/database/dist/test/datasnapshot.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/datasnapshot.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts b/functions/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts deleted file mode 100644 index 591e1926..00000000 --- a/functions/node_modules/@firebase/database/dist/test/helpers/EventAccumulator.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export declare const EventAccumulatorFactory: { - waitsForCount: (maxCount: any) => EventAccumulator; -}; -export declare class EventAccumulator { - condition: Function; - eventData: any[]; - promise: any; - resolve: any; - reject: any; - private onResetFxn; - private onEventFxn; - constructor(condition: Function); - addEvent(eventData?: any): void; - reset(condition?: Function): void; - onEvent(cb: Function): void; - onReset(cb: Function): void; - _testCondition(): any; -} diff --git a/functions/node_modules/@firebase/database/dist/test/helpers/events.d.ts b/functions/node_modules/@firebase/database/dist/test/helpers/events.d.ts deleted file mode 100644 index 24f73855..00000000 --- a/functions/node_modules/@firebase/database/dist/test/helpers/events.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * A set of functions to clean up event handlers. - * @type {function()} - */ -export declare let eventCleanupHandlers: any[]; -/** Clean up outstanding event handlers */ -export declare function eventCleanup(): void; -/** - * Creates a struct which waits for many events. - * @param {Array} pathAndEvents an array of tuples of [Firebase, [event type strings]] - * @param {string=} helperName - * @return {{waiter: waiter, watchesInitializedWaiter: watchesInitializedWaiter, unregister: unregister, addExpectedEvents: addExpectedEvents}} - */ -export declare function eventTestHelper(pathAndEvents: any, helperName?: any): { - promise: Promise<{}>; - initPromise: Promise<{}>; - waiter: () => boolean; - watchesInitializedWaiter: () => boolean; - unregister: () => void; - addExpectedEvents: (moreEvents: any) => void; -}; diff --git a/functions/node_modules/@firebase/database/dist/test/helpers/util.d.ts b/functions/node_modules/@firebase/database/dist/test/helpers/util.d.ts deleted file mode 100644 index bde3f4a7..00000000 --- a/functions/node_modules/@firebase/database/dist/test/helpers/util.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import '../../index'; -import { Reference } from '../../src/api/Reference'; -import { Query } from '../../src/api/Query'; -export declare const TEST_PROJECT: any; -export declare const DATABASE_ADDRESS: any; -export declare const DATABASE_URL: any; -/** - * Fake Firebase App Authentication functions for testing. - * @param {!FirebaseApp} app - * @return {!FirebaseApp} - */ -export declare function patchFakeAuthFunctions(app: any): any; -export declare function createTestApp(): FirebaseApp; -/** - * Gets or creates a root node to the test namespace. All calls sharing the - * value of opt_i will share an app context. - * @param {number=} i - * @param {string=} ref - * @return {Reference} - */ -export declare function getRootNode(i?: number, ref?: string): any; -/** - * Create multiple refs to the same top level - * push key - each on it's own Firebase.Context. - * @param {int=} numNodes - * @return {Reference|Array} - */ -export declare function getRandomNode(numNodes?: any): Reference | Array; -export declare function getQueryValue(query: Query): Promise; -export declare function pause(milliseconds: number): Promise<{}>; -export declare function getPath(query: Query): string; -export declare function shuffle(arr: any, randFn?: () => number): void; -export declare function testAuthTokenProvider(app: any): { - setToken: (token: any) => Promise; - setNextToken: (token: any) => void; -}; -export declare function getFreshRepo(path: any): any; -export declare function getFreshRepoFromReference(ref: any): any; -export declare function getSnap(path: any): any; -export declare function getVal(path: any): any; -export declare function canCreateExtraConnections(): boolean; -export declare function buildObjFromKey(key: any): {}; -export declare function testRepoInfo(url: any): RepoInfo; -export declare function repoInfoForConnectionTest(): RepoInfo; diff --git a/functions/node_modules/@firebase/database/dist/test/info.test.d.ts b/functions/node_modules/@firebase/database/dist/test/info.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/info.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/node.test.d.ts b/functions/node_modules/@firebase/database/dist/test/node.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/node.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/order.test.d.ts b/functions/node_modules/@firebase/database/dist/test/order.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/order.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/order_by.test.d.ts b/functions/node_modules/@firebase/database/dist/test/order_by.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/order_by.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/path.test.d.ts b/functions/node_modules/@firebase/database/dist/test/path.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/path.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/promise.test.d.ts b/functions/node_modules/@firebase/database/dist/test/promise.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/promise.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/query.test.d.ts b/functions/node_modules/@firebase/database/dist/test/query.test.d.ts deleted file mode 100644 index 1828cc2d..00000000 --- a/functions/node_modules/@firebase/database/dist/test/query.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -import '../src/core/snap/ChildrenNode'; diff --git a/functions/node_modules/@firebase/database/dist/test/repoinfo.test.d.ts b/functions/node_modules/@firebase/database/dist/test/repoinfo.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/repoinfo.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/sortedmap.test.d.ts b/functions/node_modules/@firebase/database/dist/test/sortedmap.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/sortedmap.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/sparsesnapshottree.test.d.ts b/functions/node_modules/@firebase/database/dist/test/sparsesnapshottree.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/database/dist/test/sparsesnapshottree.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/database/dist/test/transaction.test.d.ts b/functions/node_modules/@firebase/database/dist/test/transaction.test.d.ts deleted file mode 100644 index 872ffe6c..00000000 --- a/functions/node_modules/@firebase/database/dist/test/transaction.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -import '../index'; diff --git a/functions/node_modules/@firebase/database/package.json b/functions/node_modules/@firebase/database/package.json deleted file mode 100644 index 42fa9784..00000000 --- a/functions/node_modules/@firebase/database/package.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "_from": "@firebase/database@^0.3.1", - "_id": "@firebase/database@0.3.8", - "_inBundle": false, - "_integrity": "sha512-y+QJjxC62triL1g6e58sapkGKegvbNIp3hOttE6olYG/zzb+U4Q7lUbYjtMkVpGWKYSsQOPu8JkH3FNhFvX95Q==", - "_location": "/@firebase/database", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@firebase/database@^0.3.1", - "name": "@firebase/database", - "escapedName": "@firebase%2fdatabase", - "scope": "@firebase", - "rawSpec": "^0.3.1", - "saveSpec": null, - "fetchSpec": "^0.3.1" - }, - "_requiredBy": [ - "/firebase-admin" - ], - "_resolved": "https://registry.npmjs.org/@firebase/database/-/database-0.3.8.tgz", - "_shasum": "1ed903aa6efa778f81dab5b01bd6ea33b5c5bc20", - "_spec": "@firebase/database@^0.3.1", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\firebase-admin", - "author": { - "name": "Firebase", - "email": "firebase-support@google.com", - "url": "https://firebase.google.com/" - }, - "browser": "dist/index.cjs.js", - "bugs": { - "url": "https://github.com/firebase/firebase-js-sdk/issues" - }, - "bundleDependencies": false, - "dependencies": { - "@firebase/database-types": "0.3.2", - "@firebase/logger": "0.1.2", - "@firebase/util": "0.2.3", - "faye-websocket": "0.11.1", - "tslib": "1.9.0" - }, - "deprecated": false, - "description": "This is the Firebase Realtime Database component of the Firebase JS SDK.", - "devDependencies": { - "@types/chai": "4.1.2", - "@types/mocha": "5.0.0", - "@types/node": "9.6.4", - "@types/sinon": "4.3.1", - "chai": "4.1.2", - "karma": "2.0.0", - "karma-chrome-launcher": "2.2.0", - "karma-cli": "1.0.1", - "karma-firefox-launcher": "1.1.0", - "karma-mocha": "1.3.0", - "karma-sauce-launcher": "1.2.0", - "karma-sourcemap-loader": "0.3.7", - "karma-spec-reporter": "0.0.32", - "karma-webpack": "2.0.9", - "mocha": "5.2.0", - "npm-run-all": "4.1.2", - "nyc": "11.6.0", - "rollup": "0.57.1", - "rollup-plugin-commonjs": "9.1.0", - "rollup-plugin-node-resolve": "3.3.0", - "rollup-plugin-typescript2": "0.12.0", - "sinon": "4.5.0", - "source-map-loader": "0.2.3", - "ts-loader": "3.5.0", - "ts-node": "5.0.1", - "typescript": "2.8.1", - "webpack": "3.11.0" - }, - "files": [ - "dist" - ], - "license": "Apache-2.0", - "main": "dist/index.node.cjs.js", - "module": "dist/index.esm.js", - "name": "@firebase/database", - "nyc": { - "extension": [ - ".ts" - ], - "reportDir": "./coverage/node" - }, - "peerDependencies": { - "@firebase/app": "0.x", - "@firebase/app-types": "0.x" - }, - "repository": { - "type": "git", - "url": "https://github.com/firebase/firebase-js-sdk/tree/master/packages/database" - }, - "scripts": { - "build": "rollup -c", - "dev": "rollup -c -w", - "prepare": "npm run build", - "test": "run-p test:browser test:node", - "test:browser": "karma start --single-run", - "test:node": "TS_NODE_CACHE=NO nyc --reporter lcovonly -- mocha 'test/{,!(browser)/**/}*.test.ts' --compilers ts:ts-node/register/type-check -r src/nodePatches.ts --retries 5 --timeout 5000 --exit" - }, - "typings": "dist/index.d.ts", - "version": "0.3.8" -} diff --git a/functions/node_modules/@firebase/logger/README.md b/functions/node_modules/@firebase/logger/README.md deleted file mode 100644 index 69c1642e..00000000 --- a/functions/node_modules/@firebase/logger/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# @firebase/logger - -This package serves as the base of all logging in the JS SDK. Any logging that -is intended to be visible to Firebase end developers should go through this -module. - -## Basic Usage - -Firebase components should import the `Logger` class and instantiate a new -instance by passing a component name (e.g. `@firebase/`) to the -constructor. - -_e.g._ - -```typescript -import { Logger } from '@firebase/logger'; - -const logClient = new Logger(`@firebase/`); -``` - -Each `Logger` instance supports 5 log functions each to be used in a specific -instance: - -- `debug`: Internal logs; use this to allow developers to send us their debug - logs for us to be able to diagnose an issue. -- `log`: Use to inform your user about things they may need to know. -- `info`: Use if you have to inform the user about something that they need to - take a concrete action on. Once they take that action, the log should go away. -- `warn`: Use when a product feature may stop functioning correctly; unexpected - scenario. -- `error`: Only use when user App would stop functioning correctly - super rare! - -## Log Format - -Each log will be formatted in the following manner: - -```typescript -`[${new Date()}] ${COMPONENT_NAME}: ${...args}` -``` - diff --git a/functions/node_modules/@firebase/logger/dist/index.cjs.js b/functions/node_modules/@firebase/logger/dist/index.cjs.js deleted file mode 100644 index 56605e43..00000000 --- a/functions/node_modules/@firebase/logger/dist/index.cjs.js +++ /dev/null @@ -1,186 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A container for all of the Logger instances - */ -var instances = []; -(function (LogLevel) { - LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; - LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; - LogLevel[LogLevel["INFO"] = 2] = "INFO"; - LogLevel[LogLevel["WARN"] = 3] = "WARN"; - LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; - LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; -})(exports.LogLevel || (exports.LogLevel = {})); -/** - * The default log level - */ -var defaultLogLevel = exports.LogLevel.INFO; -/** - * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR - * messages on to their corresponding console counterparts (if the log method - * is supported by the current log level) - */ -var defaultLogHandler = function (instance, logType) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - if (logType < instance.logLevel) - return; - var now = new Date().toISOString(); - switch (logType) { - /** - * By default, `console.debug` is not displayed in the developer console (in - * chrome). To avoid forcing users to have to opt-in to these logs twice - * (i.e. once for firebase, and once in the console), we are sending `DEBUG` - * logs to the `console.log` function. - */ - case exports.LogLevel.DEBUG: - console.log.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case exports.LogLevel.VERBOSE: - console.log.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case exports.LogLevel.INFO: - console.info.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case exports.LogLevel.WARN: - console.warn.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case exports.LogLevel.ERROR: - console.error.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - default: - throw new Error("Attempted to log a message with an invalid logType (value: " + logType + ")"); - } -}; -var Logger = /** @class */ (function () { - /** - * Gives you an instance of a Logger to capture messages according to - * Firebase's logging scheme. - * - * @param name The name that the logs will be associated with - */ - function Logger(name) { - this.name = name; - /** - * The log level of the given Logger instance. - */ - this._logLevel = defaultLogLevel; - /** - * The log handler for the Logger instance. - */ - this._logHandler = defaultLogHandler; - /** - * Capture the current instance for later use - */ - instances.push(this); - } - Object.defineProperty(Logger.prototype, "logLevel", { - get: function () { - return this._logLevel; - }, - set: function (val) { - if (!(val in exports.LogLevel)) { - throw new TypeError('Invalid value assigned to `logLevel`'); - } - this._logLevel = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Logger.prototype, "logHandler", { - get: function () { - return this._logHandler; - }, - set: function (val) { - if (typeof val !== 'function') { - throw new TypeError('Value assigned to `logHandler` must be a function'); - } - this._logHandler = val; - }, - enumerable: true, - configurable: true - }); - /** - * The functions below are all based on the `console` interface - */ - Logger.prototype.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, exports.LogLevel.DEBUG].concat(args)); - }; - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, exports.LogLevel.VERBOSE].concat(args)); - }; - Logger.prototype.info = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, exports.LogLevel.INFO].concat(args)); - }; - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, exports.LogLevel.WARN].concat(args)); - }; - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, exports.LogLevel.ERROR].concat(args)); - }; - return Logger; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function setLogLevel(level) { - instances.forEach(function (inst) { - inst.logLevel = level; - }); -} - -exports.setLogLevel = setLogLevel; -exports.Logger = Logger; diff --git a/functions/node_modules/@firebase/logger/dist/index.d.ts b/functions/node_modules/@firebase/logger/dist/index.d.ts deleted file mode 100644 index 7ceee776..00000000 --- a/functions/node_modules/@firebase/logger/dist/index.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { LogLevel } from './src/logger'; -export declare function setLogLevel(level: LogLevel): void; -export { Logger, LogLevel, LogHandler } from './src/logger'; diff --git a/functions/node_modules/@firebase/logger/dist/index.esm.js b/functions/node_modules/@firebase/logger/dist/index.esm.js deleted file mode 100644 index f6e0b66d..00000000 --- a/functions/node_modules/@firebase/logger/dist/index.esm.js +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A container for all of the Logger instances - */ -var instances = []; -/** - * The JS SDK supports 5 log levels and also allows a user the ability to - * silence the logs altogether. - * - * The order is a follows: - * DEBUG < VERBOSE < INFO < WARN < ERROR - * - * All of the log types above the current log level will be captured (i.e. if - * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and - * `VERBOSE` logs will not) - */ -var LogLevel; -(function (LogLevel) { - LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; - LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; - LogLevel[LogLevel["INFO"] = 2] = "INFO"; - LogLevel[LogLevel["WARN"] = 3] = "WARN"; - LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; - LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; -})(LogLevel || (LogLevel = {})); -/** - * The default log level - */ -var defaultLogLevel = LogLevel.INFO; -/** - * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR - * messages on to their corresponding console counterparts (if the log method - * is supported by the current log level) - */ -var defaultLogHandler = function (instance, logType) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - if (logType < instance.logLevel) - return; - var now = new Date().toISOString(); - switch (logType) { - /** - * By default, `console.debug` is not displayed in the developer console (in - * chrome). To avoid forcing users to have to opt-in to these logs twice - * (i.e. once for firebase, and once in the console), we are sending `DEBUG` - * logs to the `console.log` function. - */ - case LogLevel.DEBUG: - console.log.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case LogLevel.VERBOSE: - console.log.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case LogLevel.INFO: - console.info.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case LogLevel.WARN: - console.warn.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - case LogLevel.ERROR: - console.error.apply(console, ["[" + now + "] " + instance.name + ":"].concat(args)); - break; - default: - throw new Error("Attempted to log a message with an invalid logType (value: " + logType + ")"); - } -}; -var Logger = /** @class */ (function () { - /** - * Gives you an instance of a Logger to capture messages according to - * Firebase's logging scheme. - * - * @param name The name that the logs will be associated with - */ - function Logger(name) { - this.name = name; - /** - * The log level of the given Logger instance. - */ - this._logLevel = defaultLogLevel; - /** - * The log handler for the Logger instance. - */ - this._logHandler = defaultLogHandler; - /** - * Capture the current instance for later use - */ - instances.push(this); - } - Object.defineProperty(Logger.prototype, "logLevel", { - get: function () { - return this._logLevel; - }, - set: function (val) { - if (!(val in LogLevel)) { - throw new TypeError('Invalid value assigned to `logLevel`'); - } - this._logLevel = val; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Logger.prototype, "logHandler", { - get: function () { - return this._logHandler; - }, - set: function (val) { - if (typeof val !== 'function') { - throw new TypeError('Value assigned to `logHandler` must be a function'); - } - this._logHandler = val; - }, - enumerable: true, - configurable: true - }); - /** - * The functions below are all based on the `console` interface - */ - Logger.prototype.debug = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, LogLevel.DEBUG].concat(args)); - }; - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, LogLevel.VERBOSE].concat(args)); - }; - Logger.prototype.info = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, LogLevel.INFO].concat(args)); - }; - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, LogLevel.WARN].concat(args)); - }; - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - this._logHandler.apply(this, [this, LogLevel.ERROR].concat(args)); - }; - return Logger; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function setLogLevel(level) { - instances.forEach(function (inst) { - inst.logLevel = level; - }); -} - -export { setLogLevel, Logger, LogLevel }; diff --git a/functions/node_modules/@firebase/logger/dist/src/logger.d.ts b/functions/node_modules/@firebase/logger/dist/src/logger.d.ts deleted file mode 100644 index 20f640b8..00000000 --- a/functions/node_modules/@firebase/logger/dist/src/logger.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * A container for all of the Logger instances - */ -export declare const instances: Logger[]; -/** - * The JS SDK supports 5 log levels and also allows a user the ability to - * silence the logs altogether. - * - * The order is a follows: - * DEBUG < VERBOSE < INFO < WARN < ERROR - * - * All of the log types above the current log level will be captured (i.e. if - * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and - * `VERBOSE` logs will not) - */ -export declare enum LogLevel { - DEBUG = 0, - VERBOSE = 1, - INFO = 2, - WARN = 3, - ERROR = 4, - SILENT = 5, -} -/** - * We allow users the ability to pass their own log handler. We will pass the - * type of log, the current log level, and any other arguments passed (i.e. the - * messages that the user wants to log) to this function. - */ -export declare type LogHandler = (loggerInstance: Logger, logType: LogLevel, ...args: any[]) => void; -export declare class Logger { - name: string; - /** - * Gives you an instance of a Logger to capture messages according to - * Firebase's logging scheme. - * - * @param name The name that the logs will be associated with - */ - constructor(name: string); - /** - * The log level of the given Logger instance. - */ - private _logLevel; - logLevel: LogLevel; - /** - * The log handler for the Logger instance. - */ - private _logHandler; - logHandler: LogHandler; - /** - * The functions below are all based on the `console` interface - */ - debug(...args: any[]): void; - log(...args: any[]): void; - info(...args: any[]): void; - warn(...args: any[]): void; - error(...args: any[]): void; -} diff --git a/functions/node_modules/@firebase/logger/dist/test/logger.test.d.ts b/functions/node_modules/@firebase/logger/dist/test/logger.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/logger/dist/test/logger.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/logger/package.json b/functions/node_modules/@firebase/logger/package.json deleted file mode 100644 index e98c6f08..00000000 --- a/functions/node_modules/@firebase/logger/package.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "_from": "@firebase/logger@0.1.2", - "_id": "@firebase/logger@0.1.2", - "_inBundle": false, - "_integrity": "sha512-4NHGRIbZChg9vDUxynzYrw14G/U/71v0pea+jXPicrpflL0N0PSCULXGGSTmzn9fqZ5W5djEwVLBCVwKndXG8w==", - "_location": "/@firebase/logger", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "@firebase/logger@0.1.2", - "name": "@firebase/logger", - "escapedName": "@firebase%2flogger", - "scope": "@firebase", - "rawSpec": "0.1.2", - "saveSpec": null, - "fetchSpec": "0.1.2" - }, - "_requiredBy": [ - "/@firebase/database" - ], - "_resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.1.2.tgz", - "_shasum": "b8f11c855ce20db792cac583da0b8b8b01418f3a", - "_spec": "@firebase/logger@0.1.2", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@firebase\\database", - "author": { - "name": "Firebase", - "email": "firebase-support@google.com", - "url": "https://firebase.google.com/" - }, - "bugs": { - "url": "https://github.com/firebase/firebase-js-sdk/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "A logger package for use in the Firebase JS SDK", - "devDependencies": { - "@types/chai": "4.1.2", - "@types/mocha": "5.0.0", - "@types/sinon": "4.3.1", - "chai": "4.1.2", - "karma": "2.0.0", - "karma-chrome-launcher": "2.2.0", - "karma-cli": "1.0.1", - "karma-firefox-launcher": "1.1.0", - "karma-mocha": "1.3.0", - "karma-sauce-launcher": "1.2.0", - "karma-spec-reporter": "0.0.32", - "karma-webpack": "2.0.9", - "mocha": "5.2.0", - "npm-run-all": "4.1.2", - "nyc": "11.6.0", - "rollup": "0.57.1", - "rollup-plugin-commonjs": "9.1.0", - "rollup-plugin-node-resolve": "3.3.0", - "rollup-plugin-typescript2": "0.12.0", - "ts-loader": "3.5.0", - "ts-node": "5.0.1", - "typescript": "2.8.1", - "webpack": "3.11.0" - }, - "files": [ - "dist" - ], - "license": "Apache-2.0", - "main": "dist/index.cjs.js", - "module": "dist/index.esm.js", - "name": "@firebase/logger", - "nyc": { - "extension": [ - ".ts" - ], - "reportDir": "./coverage/node" - }, - "repository": { - "type": "git", - "url": "https://github.com/firebase/firebase-js-sdk/tree/master/packages/logger" - }, - "scripts": { - "build": "rollup -c", - "dev": "rollup -c -w", - "prepare": "npm run build", - "test": "run-p test:browser test:node", - "test:browser": "karma start --single-run", - "test:browser:debug": "karma start --browsers Chrome --auto-watch", - "test:node": "nyc --reporter lcovonly -- mocha test/**/*.test.* --compilers ts:ts-node/register --exit" - }, - "typings": "dist/index.d.ts", - "version": "0.1.2" -} diff --git a/functions/node_modules/@firebase/util/README.md b/functions/node_modules/@firebase/util/README.md deleted file mode 100644 index d6786970..00000000 --- a/functions/node_modules/@firebase/util/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# @firebase/util - -_NOTE: This is specifically tailored for Firebase JS SDK usage, if you are not a -member of the Firebase team, please avoid using this package_ - -This is a wrapper of some Webchannel Features for the Firebase JS SDK. - -## Installation - -You can install this wrapper by running the following in your project: - -```bash -$ npm install @firebase/util -``` - -## Usage - -**ES Modules** - -```javascript -import { Deferred } from '@firebase/util'; - -// Do stuff with Deferred or any of the other Utils you import -``` - -**CommonJS Modules** - -```javascript -const utils = require('@firebase/util'); - -// Do stuff with any of the re-exported `utils` -``` diff --git a/functions/node_modules/@firebase/util/dist/index.cjs.js b/functions/node_modules/@firebase/util/dist/index.cjs.js deleted file mode 100644 index 1b35cc98..00000000 --- a/functions/node_modules/@firebase/util/dist/index.cjs.js +++ /dev/null @@ -1,1776 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var tslib_1 = require('tslib'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. - */ -var CONSTANTS = { - /** - * @define {boolean} Whether this is the client Node.js SDK. - */ - NODE_CLIENT: false, - /** - * @define {boolean} Whether this is the Admin Node.js SDK. - */ - NODE_ADMIN: false, - /** - * Firebase SDK Version - */ - SDK_VERSION: '${JSCORE_VERSION}' -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Throws an error if the provided assertion is falsy - * @param {*} assertion The assertion to be tested for falsiness - * @param {!string} message The message to display if the check fails - */ -var assert = function (assertion, message) { - if (!assertion) { - throw assertionError(message); - } -}; -/** - * Returns an Error object suitable for throwing. - * @param {string} message - * @return {!Error} - */ -var assertionError = function (message) { - return new Error('Firebase Database (' + - CONSTANTS.SDK_VERSION + - ') INTERNAL ASSERT FAILED: ' + - message); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var stringToByteArray = function (str) { - // TODO(user): Use native implementations if/when available - var out = [], p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - out[p++] = c; - } - else if (c < 2048) { - out[p++] = (c >> 6) | 192; - out[p++] = (c & 63) | 128; - } - else if ((c & 0xfc00) == 0xd800 && - i + 1 < str.length && - (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00) { - // Surrogate Pair - c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); - out[p++] = (c >> 18) | 240; - out[p++] = ((c >> 12) & 63) | 128; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - else { - out[p++] = (c >> 12) | 224; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - } - return out; -}; -/** - * Turns an array of numbers into the string given by the concatenation of the - * characters to which the numbers correspond. - * @param {Array} bytes Array of numbers representing characters. - * @return {string} Stringification of the array. - */ -var byteArrayToString = function (bytes) { - // TODO(user): Use native implementations if/when available - var out = [], pos = 0, c = 0; - while (pos < bytes.length) { - var c1 = bytes[pos++]; - if (c1 < 128) { - out[c++] = String.fromCharCode(c1); - } - else if (c1 > 191 && c1 < 224) { - var c2 = bytes[pos++]; - out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); - } - else if (c1 > 239 && c1 < 365) { - // Surrogate Pair - var c2 = bytes[pos++]; - var c3 = bytes[pos++]; - var c4 = bytes[pos++]; - var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - - 0x10000; - out[c++] = String.fromCharCode(0xd800 + (u >> 10)); - out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); - } - else { - var c2 = bytes[pos++]; - var c3 = bytes[pos++]; - out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - } - } - return out.join(''); -}; -// Static lookup maps, lazily populated by init_() -var base64 = { - /** - * Maps bytes to characters. - * @type {Object} - * @private - */ - byteToCharMap_: null, - /** - * Maps characters to bytes. - * @type {Object} - * @private - */ - charToByteMap_: null, - /** - * Maps bytes to websafe characters. - * @type {Object} - * @private - */ - byteToCharMapWebSafe_: null, - /** - * Maps websafe characters to bytes. - * @type {Object} - * @private - */ - charToByteMapWebSafe_: null, - /** - * Our default alphabet, shared between - * ENCODED_VALS and ENCODED_VALS_WEBSAFE - * @type {string} - */ - ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', - /** - * Our default alphabet. Value 64 (=) is special; it means "nothing." - * @type {string} - */ - get ENCODED_VALS() { - return this.ENCODED_VALS_BASE + '+/='; - }, - /** - * Our websafe alphabet. - * @type {string} - */ - get ENCODED_VALS_WEBSAFE() { - return this.ENCODED_VALS_BASE + '-_.'; - }, - /** - * Whether this browser supports the atob and btoa functions. This extension - * started at Mozilla but is now implemented by many browsers. We use the - * ASSUME_* variables to avoid pulling in the full useragent detection library - * but still allowing the standard per-browser compilations. - * - * @type {boolean} - */ - HAS_NATIVE_SUPPORT: typeof atob === 'function', - /** - * Base64-encode an array of bytes. - * - * @param {Array|Uint8Array} input An array of bytes (numbers with - * value in [0, 255]) to encode. - * @param {boolean=} opt_webSafe Boolean indicating we should use the - * alternative alphabet. - * @return {string} The base64 encoded string. - */ - encodeByteArray: function (input, opt_webSafe) { - if (!Array.isArray(input)) { - throw Error('encodeByteArray takes an array as a parameter'); - } - this.init_(); - var byteToCharMap = opt_webSafe - ? this.byteToCharMapWebSafe_ - : this.byteToCharMap_; - var output = []; - for (var i = 0; i < input.length; i += 3) { - var byte1 = input[i]; - var haveByte2 = i + 1 < input.length; - var byte2 = haveByte2 ? input[i + 1] : 0; - var haveByte3 = i + 2 < input.length; - var byte3 = haveByte3 ? input[i + 2] : 0; - var outByte1 = byte1 >> 2; - var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); - var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); - var outByte4 = byte3 & 0x3f; - if (!haveByte3) { - outByte4 = 64; - if (!haveByte2) { - outByte3 = 64; - } - } - output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); - } - return output.join(''); - }, - /** - * Base64-encode a string. - * - * @param {string} input A string to encode. - * @param {boolean=} opt_webSafe If true, we should use the - * alternative alphabet. - * @return {string} The base64 encoded string. - */ - encodeString: function (input, opt_webSafe) { - // Shortcut for Mozilla browsers that implement - // a native base64 encoder in the form of "btoa/atob" - if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) { - return btoa(input); - } - return this.encodeByteArray(stringToByteArray(input), opt_webSafe); - }, - /** - * Base64-decode a string. - * - * @param {string} input to decode. - * @param {boolean=} opt_webSafe True if we should use the - * alternative alphabet. - * @return {string} string representing the decoded value. - */ - decodeString: function (input, opt_webSafe) { - // Shortcut for Mozilla browsers that implement - // a native base64 encoder in the form of "btoa/atob" - if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) { - return atob(input); - } - return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe)); - }, - /** - * Base64-decode a string. - * - * In base-64 decoding, groups of four characters are converted into three - * bytes. If the encoder did not apply padding, the input length may not - * be a multiple of 4. - * - * In this case, the last group will have fewer than 4 characters, and - * padding will be inferred. If the group has one or two characters, it decodes - * to one byte. If the group has three characters, it decodes to two bytes. - * - * @param {string} input Input to decode. - * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet. - * @return {!Array} bytes representing the decoded value. - */ - decodeStringToByteArray: function (input, opt_webSafe) { - this.init_(); - var charToByteMap = opt_webSafe - ? this.charToByteMapWebSafe_ - : this.charToByteMap_; - var output = []; - for (var i = 0; i < input.length;) { - var byte1 = charToByteMap[input.charAt(i++)]; - var haveByte2 = i < input.length; - var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; - ++i; - var haveByte3 = i < input.length; - var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; - ++i; - var haveByte4 = i < input.length; - var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; - ++i; - if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { - throw Error(); - } - var outByte1 = (byte1 << 2) | (byte2 >> 4); - output.push(outByte1); - if (byte3 != 64) { - var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); - output.push(outByte2); - if (byte4 != 64) { - var outByte3 = ((byte3 << 6) & 0xc0) | byte4; - output.push(outByte3); - } - } - } - return output; - }, - /** - * Lazy static initialization function. Called before - * accessing any of the static map variables. - * @private - */ - init_: function () { - if (!this.byteToCharMap_) { - this.byteToCharMap_ = {}; - this.charToByteMap_ = {}; - this.byteToCharMapWebSafe_ = {}; - this.charToByteMapWebSafe_ = {}; - // We want quick mappings back and forth, so we precompute two maps. - for (var i = 0; i < this.ENCODED_VALS.length; i++) { - this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); - this.charToByteMap_[this.byteToCharMap_[i]] = i; - this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); - this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; - // Be forgiving when decoding and correctly decode both encodings. - if (i >= this.ENCODED_VALS_BASE.length) { - this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; - this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; - } - } - } - } -}; -/** - * URL-safe base64 encoding - * @param {!string} str - * @return {!string} - */ -var base64Encode = function (str) { - var utf8Bytes = stringToByteArray(str); - return base64.encodeByteArray(utf8Bytes, true); -}; -/** - * URL-safe base64 decoding - * - * NOTE: DO NOT use the global atob() function - it does NOT support the - * base64Url variant encoding. - * - * @param {string} str To be decoded - * @return {?string} Decoded result, if possible - */ -var base64Decode = function (str) { - try { - return base64.decodeString(str, true); - } - catch (e) { - console.error('base64Decode failed: ', e); - } - return null; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Do a deep-copy of basic JavaScript Objects or Arrays. - */ -function deepCopy(value) { - return deepExtend(undefined, value); -} -/** - * Copy properties from source to target (recursively allows extension - * of Objects and Arrays). Scalar values in the target are over-written. - * If target is undefined, an object of the appropriate type will be created - * (and returned). - * - * We recursively copy all child properties of plain Objects in the source- so - * that namespace- like dictionaries are merged. - * - * Note that the target can be a function, in which case the properties in - * the source Object are copied onto it as static properties of the Function. - */ -function deepExtend(target, source) { - if (!(source instanceof Object)) { - return source; - } - switch (source.constructor) { - case Date: - // Treat Dates like scalars; if the target date object had any child - // properties - they will be lost! - var dateValue = source; - return new Date(dateValue.getTime()); - case Object: - if (target === undefined) { - target = {}; - } - break; - case Array: - // Always copy the array source and overwrite the target. - target = []; - break; - default: - // Not a plain Object - treat it as a scalar. - return source; - } - for (var prop in source) { - if (!source.hasOwnProperty(prop)) { - continue; - } - target[prop] = deepExtend(target[prop], source[prop]); - } - return target; -} -// TODO: Really needed (for JSCompiler type checking)? -function patchProperty(obj, prop, value) { - obj[prop] = value; -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Deferred = /** @class */ (function () { - function Deferred() { - var _this = this; - this.promise = new Promise(function (resolve, reject) { - _this.resolve = resolve; - _this.reject = reject; - }); - } - /** - * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around - * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback - * and returns a node-style callback which will resolve or reject the Deferred's promise. - * @param {((?function(?(Error)): (?|undefined))| (?function(?(Error),?=): (?|undefined)))=} callback - * @return {!function(?(Error), ?=)} - */ - Deferred.prototype.wrapCallback = function (callback) { - var _this = this; - return function (error, value) { - if (error) { - _this.reject(error); - } - else { - _this.resolve(value); - } - if (typeof callback === 'function') { - // Attaching noop handler just in case developer wasn't expecting - // promises - _this.promise.catch(function () { }); - // Some of our callbacks don't expect a value and our own tests - // assert that the parameter length is 1 - if (callback.length === 1) { - callback(error); - } - else { - callback(error, value); - } - } - }; - }; - return Deferred; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns navigator.userAgent string or '' if it's not defined. - * @return {string} user agent string - */ -var getUA = function () { - if (typeof navigator !== 'undefined' && - typeof navigator['userAgent'] === 'string') { - return navigator['userAgent']; - } - else { - return ''; - } -}; -/** - * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. - * - * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor - * Cordova `onDeviceReady`, which would normally wait for a callback. - * - * @return {boolean} isMobileCordova - */ -var isMobileCordova = function () { - return (typeof window !== 'undefined' && - !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && - /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); -}; -/** - * Detect React Native. - * - * @return {boolean} True if ReactNative environment is detected. - */ -var isReactNative = function () { - return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); -}; -/** - * Detect Node.js. - * - * @return {boolean} True if Node.js environment is detected. - */ -var isNodeSdk = function () { - return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; -}; - -var ERROR_NAME = 'FirebaseError'; -var captureStackTrace = Error - .captureStackTrace; -// Export for faking in tests -function patchCapture(captureFake) { - var result = captureStackTrace; - captureStackTrace = captureFake; - return result; -} -var FirebaseError = /** @class */ (function () { - function FirebaseError(code, message) { - this.code = code; - this.message = message; - // We want the stack value, if implemented by Error - if (captureStackTrace) { - // Patches this.stack, omitted calls above ErrorFactory#create - captureStackTrace(this, ErrorFactory.prototype.create); - } - else { - try { - // In case of IE11, stack will be set only after error is raised. - // https://docs.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript - throw Error.apply(this, arguments); - } - catch (err) { - this.name = ERROR_NAME; - // Make non-enumerable getter for the property. - Object.defineProperty(this, 'stack', { - get: function () { - return err.stack; - } - }); - } - } - } - return FirebaseError; -}()); -// Back-door inheritance -FirebaseError.prototype = Object.create(Error.prototype); -FirebaseError.prototype.constructor = FirebaseError; -FirebaseError.prototype.name = ERROR_NAME; -var ErrorFactory = /** @class */ (function () { - function ErrorFactory(service, serviceName, errors) { - this.service = service; - this.serviceName = serviceName; - this.errors = errors; - // Matches {$name}, by default. - this.pattern = /\{\$([^}]+)}/g; - // empty - } - ErrorFactory.prototype.create = function (code, data) { - if (data === undefined) { - data = {}; - } - var template = this.errors[code]; - var fullCode = this.service + '/' + code; - var message; - if (template === undefined) { - message = 'Error'; - } - else { - message = template.replace(this.pattern, function (match, key) { - var value = data[key]; - return value !== undefined ? value.toString() : '<' + key + '?>'; - }); - } - // Service: Error message (service/code). - message = this.serviceName + ': ' + message + ' (' + fullCode + ').'; - var err = new FirebaseError(fullCode, message); - // Populate the Error object with message parts for programmatic - // accesses (e.g., e.file). - for (var prop in data) { - if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') { - continue; - } - err[prop] = data[prop]; - } - return err; - }; - return ErrorFactory; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Evaluates a JSON string into a javascript object. - * - * @param {string} str A string containing JSON. - * @return {*} The javascript object representing the specified JSON. - */ -function jsonEval(str) { - return JSON.parse(str); -} -/** - * Returns JSON representing a javascript object. - * @param {*} data Javascript object to be stringified. - * @return {string} The JSON contents of the object. - */ -function stringify(data) { - return JSON.stringify(data); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Decodes a Firebase auth. token into constituent parts. - * - * Notes: - * - May return with invalid / incomplete claims if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {{header: *, claims: *, data: *, signature: string}} - */ -var decode = function (token) { - var header = {}, claims = {}, data = {}, signature = ''; - try { - var parts = token.split('.'); - header = jsonEval(base64Decode(parts[0]) || ''); - claims = jsonEval(base64Decode(parts[1]) || ''); - signature = parts[2]; - data = claims['d'] || {}; - delete claims['d']; - } - catch (e) { } - return { - header: header, - claims: claims, - data: data, - signature: signature - }; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the - * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isValidTimestamp = function (token) { - var claims = decode(token).claims, now = Math.floor(new Date().getTime() / 1000), validSince, validUntil; - if (typeof claims === 'object') { - if (claims.hasOwnProperty('nbf')) { - validSince = claims['nbf']; - } - else if (claims.hasOwnProperty('iat')) { - validSince = claims['iat']; - } - if (claims.hasOwnProperty('exp')) { - validUntil = claims['exp']; - } - else { - // token will expire after 24h by default - validUntil = validSince + 86400; - } - } - return (now && validSince && validUntil && now >= validSince && now <= validUntil); -}; -/** - * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. - * - * Notes: - * - May return null if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {?number} - */ -var issuedAtTime = function (token) { - var claims = decode(token).claims; - if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { - return claims['iat']; - } - return null; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isValidFormat = function (token) { - var decoded = decode(token), claims = decoded.claims; - return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); -}; -/** - * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isAdmin = function (token) { - var claims = decode(token).claims; - return typeof claims === 'object' && claims['admin'] === true; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var safeGet = function (obj, key) { - if (Object.prototype.hasOwnProperty.call(obj, key)) - return obj[key]; - // else return undefined. -}; -/** - * Enumerates the keys/values in an object, excluding keys defined on the prototype. - * - * @param {?Object.} obj Object to enumerate. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -var forEach = function (obj, fn) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn(key, obj[key]); - } - } -}; -/** - * Copies all the (own) properties from one object to another. - * @param {!Object} objTo - * @param {!Object} objFrom - * @return {!Object} objTo - */ -var extend = function (objTo, objFrom) { - forEach(objFrom, function (key, value) { - objTo[key] = value; - }); - return objTo; -}; -/** - * Returns a clone of the specified object. - * @param {!Object} obj - * @return {!Object} cloned obj. - */ -var clone = function (obj) { - return extend({}, obj); -}; -/** - * Returns true if obj has typeof "object" and is not null. Unlike goog.isObject(), does not return true - * for functions. - * - * @param obj {*} A potential object. - * @returns {boolean} True if it's an object. - */ -var isNonNullObject = function (obj) { - return typeof obj === 'object' && obj !== null; -}; -var isEmpty = function (obj) { - for (var key in obj) { - return false; - } - return true; -}; -var getCount = function (obj) { - var rv = 0; - for (var key in obj) { - rv++; - } - return rv; -}; -var map = function (obj, f, opt_obj) { - var res = {}; - for (var key in obj) { - res[key] = f.call(opt_obj, obj[key], key, obj); - } - return res; -}; -var findKey = function (obj, fn, opt_this) { - for (var key in obj) { - if (fn.call(opt_this, obj[key], key, obj)) { - return key; - } - } - return undefined; -}; -var findValue = function (obj, fn, opt_this) { - var key = findKey(obj, fn, opt_this); - return key && obj[key]; -}; -var getAnyKey = function (obj) { - for (var key in obj) { - return key; - } -}; -var getValues = function (obj) { - var res = []; - var i = 0; - for (var key in obj) { - res[i++] = obj[key]; - } - return res; -}; -/** - * Tests whether every key/value pair in an object pass the test implemented - * by the provided function - * - * @param {?Object.} obj Object to test. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -var every = function (obj, fn) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - if (!fn(key, obj[key])) { - return false; - } - } - } - return true; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params - * object (e.g. {arg: 'val', arg2: 'val2'}) - * Note: You must prepend it with ? when adding it to a URL. - * - * @param {!Object} querystringParams - * @return {string} - */ -var querystring = function (querystringParams) { - var params = []; - forEach(querystringParams, function (key, value) { - if (Array.isArray(value)) { - value.forEach(function (arrayVal) { - params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); - }); - } - else { - params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); - } - }); - return params.length ? '&' + params.join('&') : ''; -}; -/** - * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'}) - * - * @param {string} querystring - * @return {!Object} - */ -var querystringDecode = function (querystring) { - var obj = {}; - var tokens = querystring.replace(/^\?/, '').split('&'); - tokens.forEach(function (token) { - if (token) { - var key = token.split('='); - obj[key[0]] = key[1]; - } - }); - return obj; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Copyright 2011 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/** - * @fileoverview Abstract cryptographic hash interface. - * - * See Sha1 and Md5 for sample implementations. - * - */ -/** - * Create a cryptographic hash instance. - * - * @constructor - * @struct - */ -var Hash = /** @class */ (function () { - function Hash() { - /** - * The block size for the hasher. - * @type {number} - */ - this.blockSize = -1; - } - return Hash; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview SHA-1 cryptographic hash. - * Variable names follow the notation in FIPS PUB 180-3: - * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. - * - * Usage: - * var sha1 = new sha1(); - * sha1.update(bytes); - * var hash = sha1.digest(); - * - * Performance: - * Chrome 23: ~400 Mbit/s - * Firefox 16: ~250 Mbit/s - * - */ -/** - * SHA-1 cryptographic hash constructor. - * - * The properties declared here are discussed in the above algorithm document. - * @constructor - * @extends {Hash} - * @final - * @struct - */ -var Sha1 = /** @class */ (function (_super) { - tslib_1.__extends(Sha1, _super); - function Sha1() { - var _this = _super.call(this) || this; - /** - * Holds the previous values of accumulated variables a-e in the compress_ - * function. - * @type {!Array} - * @private - */ - _this.chain_ = []; - /** - * A buffer holding the partially computed hash result. - * @type {!Array} - * @private - */ - _this.buf_ = []; - /** - * An array of 80 bytes, each a part of the message to be hashed. Referred to - * as the message schedule in the docs. - * @type {!Array} - * @private - */ - _this.W_ = []; - /** - * Contains data needed to pad messages less than 64 bytes. - * @type {!Array} - * @private - */ - _this.pad_ = []; - /** - * @private {number} - */ - _this.inbuf_ = 0; - /** - * @private {number} - */ - _this.total_ = 0; - _this.blockSize = 512 / 8; - _this.pad_[0] = 128; - for (var i = 1; i < _this.blockSize; ++i) { - _this.pad_[i] = 0; - } - _this.reset(); - return _this; - } - Sha1.prototype.reset = function () { - this.chain_[0] = 0x67452301; - this.chain_[1] = 0xefcdab89; - this.chain_[2] = 0x98badcfe; - this.chain_[3] = 0x10325476; - this.chain_[4] = 0xc3d2e1f0; - this.inbuf_ = 0; - this.total_ = 0; - }; - /** - * Internal compress helper function. - * @param {!Array|!Uint8Array|string} buf Block to compress. - * @param {number=} opt_offset Offset of the block in the buffer. - * @private - */ - Sha1.prototype.compress_ = function (buf, opt_offset) { - if (!opt_offset) { - opt_offset = 0; - } - var W = this.W_; - // get 16 big endian words - if (typeof buf === 'string') { - for (var i = 0; i < 16; i++) { - // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS - // have a bug that turns the post-increment ++ operator into pre-increment - // during JIT compilation. We have code that depends heavily on SHA-1 for - // correctness and which is affected by this bug, so I've removed all uses - // of post-increment ++ in which the result value is used. We can revert - // this change once the Safari bug - // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and - // most clients have been updated. - W[i] = - (buf.charCodeAt(opt_offset) << 24) | - (buf.charCodeAt(opt_offset + 1) << 16) | - (buf.charCodeAt(opt_offset + 2) << 8) | - buf.charCodeAt(opt_offset + 3); - opt_offset += 4; - } - } - else { - for (var i = 0; i < 16; i++) { - W[i] = - (buf[opt_offset] << 24) | - (buf[opt_offset + 1] << 16) | - (buf[opt_offset + 2] << 8) | - buf[opt_offset + 3]; - opt_offset += 4; - } - } - // expand to 80 words - for (var i = 16; i < 80; i++) { - var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; - } - var a = this.chain_[0]; - var b = this.chain_[1]; - var c = this.chain_[2]; - var d = this.chain_[3]; - var e = this.chain_[4]; - var f, k; - // TODO(user): Try to unroll this loop to speed up the computation. - for (var i = 0; i < 80; i++) { - if (i < 40) { - if (i < 20) { - f = d ^ (b & (c ^ d)); - k = 0x5a827999; - } - else { - f = b ^ c ^ d; - k = 0x6ed9eba1; - } - } - else { - if (i < 60) { - f = (b & c) | (d & (b | c)); - k = 0x8f1bbcdc; - } - else { - f = b ^ c ^ d; - k = 0xca62c1d6; - } - } - var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; - e = d; - d = c; - c = ((b << 30) | (b >>> 2)) & 0xffffffff; - b = a; - a = t; - } - this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; - this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; - this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; - this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; - this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; - }; - Sha1.prototype.update = function (bytes, opt_length) { - // TODO(johnlenz): tighten the function signature and remove this check - if (bytes == null) { - return; - } - if (opt_length === undefined) { - opt_length = bytes.length; - } - var lengthMinusBlock = opt_length - this.blockSize; - var n = 0; - // Using local instead of member variables gives ~5% speedup on Firefox 16. - var buf = this.buf_; - var inbuf = this.inbuf_; - // The outer while loop should execute at most twice. - while (n < opt_length) { - // When we have no data in the block to top up, we can directly process the - // input buffer (assuming it contains sufficient data). This gives ~25% - // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that - // the data is provided in large chunks (or in multiples of 64 bytes). - if (inbuf == 0) { - while (n <= lengthMinusBlock) { - this.compress_(bytes, n); - n += this.blockSize; - } - } - if (typeof bytes === 'string') { - while (n < opt_length) { - buf[inbuf] = bytes.charCodeAt(n); - ++inbuf; - ++n; - if (inbuf == this.blockSize) { - this.compress_(buf); - inbuf = 0; - // Jump to the outer loop so we use the full-block optimization. - break; - } - } - } - else { - while (n < opt_length) { - buf[inbuf] = bytes[n]; - ++inbuf; - ++n; - if (inbuf == this.blockSize) { - this.compress_(buf); - inbuf = 0; - // Jump to the outer loop so we use the full-block optimization. - break; - } - } - } - } - this.inbuf_ = inbuf; - this.total_ += opt_length; - }; - /** @override */ - Sha1.prototype.digest = function () { - var digest = []; - var totalBits = this.total_ * 8; - // Add pad 0x80 0x00*. - if (this.inbuf_ < 56) { - this.update(this.pad_, 56 - this.inbuf_); - } - else { - this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); - } - // Add # bits. - for (var i = this.blockSize - 1; i >= 56; i--) { - this.buf_[i] = totalBits & 255; - totalBits /= 256; // Don't use bit-shifting here! - } - this.compress_(this.buf_); - var n = 0; - for (var i = 0; i < 5; i++) { - for (var j = 24; j >= 0; j -= 8) { - digest[n] = (this.chain_[i] >> j) & 255; - ++n; - } - } - return digest; - }; - return Sha1; -}(Hash)); - -/** - * Helper to make a Subscribe function (just like Promise helps make a - * Thenable). - * - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ -function createSubscribe(executor, onNoObservers) { - var proxy = new ObserverProxy(executor, onNoObservers); - return proxy.subscribe.bind(proxy); -} -/** - * Implement fan-out for any number of Observers attached via a subscribe - * function. - */ -var ObserverProxy = /** @class */ (function () { - /** - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ - function ObserverProxy(executor, onNoObservers) { - var _this = this; - this.observers = []; - this.unsubscribes = []; - this.observerCount = 0; - // Micro-task scheduling by calling task.then(). - this.task = Promise.resolve(); - this.finalized = false; - this.onNoObservers = onNoObservers; - // Call the executor asynchronously so subscribers that are called - // synchronously after the creation of the subscribe function - // can still receive the very first value generated in the executor. - this.task - .then(function () { - executor(_this); - }) - .catch(function (e) { - _this.error(e); - }); - } - ObserverProxy.prototype.next = function (value) { - this.forEachObserver(function (observer) { - observer.next(value); - }); - }; - ObserverProxy.prototype.error = function (error) { - this.forEachObserver(function (observer) { - observer.error(error); - }); - this.close(error); - }; - ObserverProxy.prototype.complete = function () { - this.forEachObserver(function (observer) { - observer.complete(); - }); - this.close(); - }; - /** - * Subscribe function that can be used to add an Observer to the fan-out list. - * - * - We require that no event is sent to a subscriber sychronously to their - * call to subscribe(). - */ - ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) { - var _this = this; - var observer; - if (nextOrObserver === undefined && - error === undefined && - complete === undefined) { - throw new Error('Missing Observer.'); - } - // Assemble an Observer object when passed as callback functions. - if (implementsAnyMethods(nextOrObserver, ['next', 'error', 'complete'])) { - observer = nextOrObserver; - } - else { - observer = { - next: nextOrObserver, - error: error, - complete: complete - }; - } - if (observer.next === undefined) { - observer.next = noop; - } - if (observer.error === undefined) { - observer.error = noop; - } - if (observer.complete === undefined) { - observer.complete = noop; - } - var unsub = this.unsubscribeOne.bind(this, this.observers.length); - // Attempt to subscribe to a terminated Observable - we - // just respond to the Observer with the final error or complete - // event. - if (this.finalized) { - this.task.then(function () { - try { - if (_this.finalError) { - observer.error(_this.finalError); - } - else { - observer.complete(); - } - } - catch (e) { - // nothing - } - return; - }); - } - this.observers.push(observer); - return unsub; - }; - // Unsubscribe is synchronous - we guarantee that no events are sent to - // any unsubscribed Observer. - ObserverProxy.prototype.unsubscribeOne = function (i) { - if (this.observers === undefined || this.observers[i] === undefined) { - return; - } - delete this.observers[i]; - this.observerCount -= 1; - if (this.observerCount === 0 && this.onNoObservers !== undefined) { - this.onNoObservers(this); - } - }; - ObserverProxy.prototype.forEachObserver = function (fn) { - if (this.finalized) { - // Already closed by previous event....just eat the additional values. - return; - } - // Since sendOne calls asynchronously - there is no chance that - // this.observers will become undefined. - for (var i = 0; i < this.observers.length; i++) { - this.sendOne(i, fn); - } - }; - // Call the Observer via one of it's callback function. We are careful to - // confirm that the observe has not been unsubscribed since this asynchronous - // function had been queued. - ObserverProxy.prototype.sendOne = function (i, fn) { - var _this = this; - // Execute the callback asynchronously - this.task.then(function () { - if (_this.observers !== undefined && _this.observers[i] !== undefined) { - try { - fn(_this.observers[i]); - } - catch (e) { - // Ignore exceptions raised in Observers or missing methods of an - // Observer. - // Log error to console. b/31404806 - if (typeof console !== 'undefined' && console.error) { - console.error(e); - } - } - } - }); - }; - ObserverProxy.prototype.close = function (err) { - var _this = this; - if (this.finalized) { - return; - } - this.finalized = true; - if (err !== undefined) { - this.finalError = err; - } - // Proxy is no longer needed - garbage collect references - this.task.then(function () { - _this.observers = undefined; - _this.onNoObservers = undefined; - }); - }; - return ObserverProxy; -}()); -/** Turn synchronous function into one called asynchronously. */ -function async(fn, onError) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - Promise.resolve(true) - .then(function () { - fn.apply(void 0, args); - }) - .catch(function (error) { - if (onError) { - onError(error); - } - }); - }; -} -/** - * Return true if the object passed in implements any of the named methods. - */ -function implementsAnyMethods(obj, methods) { - if (typeof obj !== 'object' || obj === null) { - return false; - } - for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) { - var method = methods_1[_i]; - if (method in obj && typeof obj[method] === 'function') { - return true; - } - } - return false; -} -function noop() { - // do nothing -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Check to make sure the appropriate number of arguments are provided for a public function. - * Throws an error if it fails. - * - * @param {!string} fnName The function name - * @param {!number} minCount The minimum number of arguments to allow for the function call - * @param {!number} maxCount The maximum number of argument to allow for the function call - * @param {!number} argCount The actual number of arguments provided. - */ -var validateArgCount = function (fnName, minCount, maxCount, argCount) { - var argError; - if (argCount < minCount) { - argError = 'at least ' + minCount; - } - else if (argCount > maxCount) { - argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; - } - if (argError) { - var error = fnName + - ' failed: Was called with ' + - argCount + - (argCount === 1 ? ' argument.' : ' arguments.') + - ' Expects ' + - argError + - '.'; - throw new Error(error); - } -}; -/** - * Generates a string to prefix an error message about failed argument validation - * - * @param {!string} fnName The function name - * @param {!number} argumentNumber The index of the argument - * @param {boolean} optional Whether or not the argument is optional - * @return {!string} The prefix to add to the error thrown for validation. - */ -function errorPrefix(fnName, argumentNumber, optional) { - var argName = ''; - switch (argumentNumber) { - case 1: - argName = optional ? 'first' : 'First'; - break; - case 2: - argName = optional ? 'second' : 'Second'; - break; - case 3: - argName = optional ? 'third' : 'Third'; - break; - case 4: - argName = optional ? 'fourth' : 'Fourth'; - break; - default: - throw new Error('errorPrefix called with argumentNumber > 4. Need to update it?'); - } - var error = fnName + ' failed: '; - error += argName + ' argument '; - return error; -} -/** - * @param {!string} fnName - * @param {!number} argumentNumber - * @param {!string} namespace - * @param {boolean} optional - */ -function validateNamespace(fnName, argumentNumber, namespace, optional) { - if (optional && !namespace) - return; - if (typeof namespace !== 'string') { - //TODO: I should do more validation here. We only allow certain chars in namespaces. - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid firebase namespace.'); - } -} -function validateCallback(fnName, argumentNumber, callback, optional) { - if (optional && !callback) - return; - if (typeof callback !== 'function') - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid function.'); -} -function validateContextObject(fnName, argumentNumber, context, optional) { - if (optional && !context) - return; - if (typeof context !== 'object' || context === null) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid context object.'); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they -// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, -// so it's been modified. -// Note that not all Unicode characters appear as single characters in JavaScript strings. -// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters -// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first -// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate -// pair). -// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 -/** - * @param {string} str - * @return {Array} - */ -var stringToByteArray$1 = function (str) { - var out = [], p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - // Is this the lead surrogate in a surrogate pair? - if (c >= 0xd800 && c <= 0xdbff) { - var high = c - 0xd800; // the high 10 bits. - i++; - assert(i < str.length, 'Surrogate pair missing trail surrogate.'); - var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. - c = 0x10000 + (high << 10) + low; - } - if (c < 128) { - out[p++] = c; - } - else if (c < 2048) { - out[p++] = (c >> 6) | 192; - out[p++] = (c & 63) | 128; - } - else if (c < 65536) { - out[p++] = (c >> 12) | 224; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - else { - out[p++] = (c >> 18) | 240; - out[p++] = ((c >> 12) & 63) | 128; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - } - return out; -}; -/** - * Calculate length without actually converting; useful for doing cheaper validation. - * @param {string} str - * @return {number} - */ -var stringLength = function (str) { - var p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - p++; - } - else if (c < 2048) { - p += 2; - } - else if (c >= 0xd800 && c <= 0xdbff) { - // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. - p += 4; - i++; // skip trail surrogate. - } - else { - p += 3; - } - } - return p; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -exports.assert = assert; -exports.assertionError = assertionError; -exports.base64 = base64; -exports.base64Decode = base64Decode; -exports.base64Encode = base64Encode; -exports.CONSTANTS = CONSTANTS; -exports.deepCopy = deepCopy; -exports.deepExtend = deepExtend; -exports.patchProperty = patchProperty; -exports.Deferred = Deferred; -exports.getUA = getUA; -exports.isMobileCordova = isMobileCordova; -exports.isNodeSdk = isNodeSdk; -exports.isReactNative = isReactNative; -exports.ErrorFactory = ErrorFactory; -exports.FirebaseError = FirebaseError; -exports.patchCapture = patchCapture; -exports.jsonEval = jsonEval; -exports.stringify = stringify; -exports.decode = decode; -exports.isAdmin = isAdmin; -exports.issuedAtTime = issuedAtTime; -exports.isValidFormat = isValidFormat; -exports.isValidTimestamp = isValidTimestamp; -exports.clone = clone; -exports.contains = contains; -exports.every = every; -exports.extend = extend; -exports.findKey = findKey; -exports.findValue = findValue; -exports.forEach = forEach; -exports.getAnyKey = getAnyKey; -exports.getCount = getCount; -exports.getValues = getValues; -exports.isEmpty = isEmpty; -exports.isNonNullObject = isNonNullObject; -exports.map = map; -exports.safeGet = safeGet; -exports.querystring = querystring; -exports.querystringDecode = querystringDecode; -exports.Sha1 = Sha1; -exports.async = async; -exports.createSubscribe = createSubscribe; -exports.errorPrefix = errorPrefix; -exports.validateArgCount = validateArgCount; -exports.validateCallback = validateCallback; -exports.validateContextObject = validateContextObject; -exports.validateNamespace = validateNamespace; -exports.stringLength = stringLength; -exports.stringToByteArray = stringToByteArray$1; diff --git a/functions/node_modules/@firebase/util/dist/index.d.ts b/functions/node_modules/@firebase/util/dist/index.d.ts deleted file mode 100644 index fbd1ab34..00000000 --- a/functions/node_modules/@firebase/util/dist/index.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export { assert, assertionError } from './src/assert'; -export { base64, base64Decode, base64Encode } from './src/crypt'; -export { CONSTANTS } from './src/constants'; -export { deepCopy, deepExtend, patchProperty } from './src/deepCopy'; -export { Deferred } from './src/deferred'; -export { getUA, isMobileCordova, isNodeSdk, isReactNative } from './src/environment'; -export { ErrorFactory, ErrorList, FirebaseError, patchCapture, StringLike } from './src/errors'; -export { jsonEval, stringify } from './src/json'; -export { decode, isAdmin, issuedAtTime, isValidFormat, isValidTimestamp } from './src/jwt'; -export { clone, contains, every, extend, findKey, findValue, forEach, getAnyKey, getCount, getValues, isEmpty, isNonNullObject, map, safeGet } from './src/obj'; -export { querystring, querystringDecode } from './src/query'; -export { Sha1 } from './src/sha1'; -export { async, CompleteFn, createSubscribe, ErrorFn, Executor, NextFn, Observable, Observer, PartialObserver, Subscribe, Unsubscribe } from './src/subscribe'; -export { errorPrefix, validateArgCount, validateCallback, validateContextObject, validateNamespace } from './src/validation'; -export { stringLength, stringToByteArray } from './src/utf8'; diff --git a/functions/node_modules/@firebase/util/dist/index.esm.js b/functions/node_modules/@firebase/util/dist/index.esm.js deleted file mode 100644 index 7dc608ed..00000000 --- a/functions/node_modules/@firebase/util/dist/index.esm.js +++ /dev/null @@ -1,1723 +0,0 @@ -import { __extends } from 'tslib'; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. - */ -var CONSTANTS = { - /** - * @define {boolean} Whether this is the client Node.js SDK. - */ - NODE_CLIENT: false, - /** - * @define {boolean} Whether this is the Admin Node.js SDK. - */ - NODE_ADMIN: false, - /** - * Firebase SDK Version - */ - SDK_VERSION: '${JSCORE_VERSION}' -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Throws an error if the provided assertion is falsy - * @param {*} assertion The assertion to be tested for falsiness - * @param {!string} message The message to display if the check fails - */ -var assert = function (assertion, message) { - if (!assertion) { - throw assertionError(message); - } -}; -/** - * Returns an Error object suitable for throwing. - * @param {string} message - * @return {!Error} - */ -var assertionError = function (message) { - return new Error('Firebase Database (' + - CONSTANTS.SDK_VERSION + - ') INTERNAL ASSERT FAILED: ' + - message); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var stringToByteArray = function (str) { - // TODO(user): Use native implementations if/when available - var out = [], p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - out[p++] = c; - } - else if (c < 2048) { - out[p++] = (c >> 6) | 192; - out[p++] = (c & 63) | 128; - } - else if ((c & 0xfc00) == 0xd800 && - i + 1 < str.length && - (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00) { - // Surrogate Pair - c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); - out[p++] = (c >> 18) | 240; - out[p++] = ((c >> 12) & 63) | 128; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - else { - out[p++] = (c >> 12) | 224; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - } - return out; -}; -/** - * Turns an array of numbers into the string given by the concatenation of the - * characters to which the numbers correspond. - * @param {Array} bytes Array of numbers representing characters. - * @return {string} Stringification of the array. - */ -var byteArrayToString = function (bytes) { - // TODO(user): Use native implementations if/when available - var out = [], pos = 0, c = 0; - while (pos < bytes.length) { - var c1 = bytes[pos++]; - if (c1 < 128) { - out[c++] = String.fromCharCode(c1); - } - else if (c1 > 191 && c1 < 224) { - var c2 = bytes[pos++]; - out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); - } - else if (c1 > 239 && c1 < 365) { - // Surrogate Pair - var c2 = bytes[pos++]; - var c3 = bytes[pos++]; - var c4 = bytes[pos++]; - var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - - 0x10000; - out[c++] = String.fromCharCode(0xd800 + (u >> 10)); - out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); - } - else { - var c2 = bytes[pos++]; - var c3 = bytes[pos++]; - out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - } - } - return out.join(''); -}; -// Static lookup maps, lazily populated by init_() -var base64 = { - /** - * Maps bytes to characters. - * @type {Object} - * @private - */ - byteToCharMap_: null, - /** - * Maps characters to bytes. - * @type {Object} - * @private - */ - charToByteMap_: null, - /** - * Maps bytes to websafe characters. - * @type {Object} - * @private - */ - byteToCharMapWebSafe_: null, - /** - * Maps websafe characters to bytes. - * @type {Object} - * @private - */ - charToByteMapWebSafe_: null, - /** - * Our default alphabet, shared between - * ENCODED_VALS and ENCODED_VALS_WEBSAFE - * @type {string} - */ - ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', - /** - * Our default alphabet. Value 64 (=) is special; it means "nothing." - * @type {string} - */ - get ENCODED_VALS() { - return this.ENCODED_VALS_BASE + '+/='; - }, - /** - * Our websafe alphabet. - * @type {string} - */ - get ENCODED_VALS_WEBSAFE() { - return this.ENCODED_VALS_BASE + '-_.'; - }, - /** - * Whether this browser supports the atob and btoa functions. This extension - * started at Mozilla but is now implemented by many browsers. We use the - * ASSUME_* variables to avoid pulling in the full useragent detection library - * but still allowing the standard per-browser compilations. - * - * @type {boolean} - */ - HAS_NATIVE_SUPPORT: typeof atob === 'function', - /** - * Base64-encode an array of bytes. - * - * @param {Array|Uint8Array} input An array of bytes (numbers with - * value in [0, 255]) to encode. - * @param {boolean=} opt_webSafe Boolean indicating we should use the - * alternative alphabet. - * @return {string} The base64 encoded string. - */ - encodeByteArray: function (input, opt_webSafe) { - if (!Array.isArray(input)) { - throw Error('encodeByteArray takes an array as a parameter'); - } - this.init_(); - var byteToCharMap = opt_webSafe - ? this.byteToCharMapWebSafe_ - : this.byteToCharMap_; - var output = []; - for (var i = 0; i < input.length; i += 3) { - var byte1 = input[i]; - var haveByte2 = i + 1 < input.length; - var byte2 = haveByte2 ? input[i + 1] : 0; - var haveByte3 = i + 2 < input.length; - var byte3 = haveByte3 ? input[i + 2] : 0; - var outByte1 = byte1 >> 2; - var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); - var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); - var outByte4 = byte3 & 0x3f; - if (!haveByte3) { - outByte4 = 64; - if (!haveByte2) { - outByte3 = 64; - } - } - output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); - } - return output.join(''); - }, - /** - * Base64-encode a string. - * - * @param {string} input A string to encode. - * @param {boolean=} opt_webSafe If true, we should use the - * alternative alphabet. - * @return {string} The base64 encoded string. - */ - encodeString: function (input, opt_webSafe) { - // Shortcut for Mozilla browsers that implement - // a native base64 encoder in the form of "btoa/atob" - if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) { - return btoa(input); - } - return this.encodeByteArray(stringToByteArray(input), opt_webSafe); - }, - /** - * Base64-decode a string. - * - * @param {string} input to decode. - * @param {boolean=} opt_webSafe True if we should use the - * alternative alphabet. - * @return {string} string representing the decoded value. - */ - decodeString: function (input, opt_webSafe) { - // Shortcut for Mozilla browsers that implement - // a native base64 encoder in the form of "btoa/atob" - if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) { - return atob(input); - } - return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe)); - }, - /** - * Base64-decode a string. - * - * In base-64 decoding, groups of four characters are converted into three - * bytes. If the encoder did not apply padding, the input length may not - * be a multiple of 4. - * - * In this case, the last group will have fewer than 4 characters, and - * padding will be inferred. If the group has one or two characters, it decodes - * to one byte. If the group has three characters, it decodes to two bytes. - * - * @param {string} input Input to decode. - * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet. - * @return {!Array} bytes representing the decoded value. - */ - decodeStringToByteArray: function (input, opt_webSafe) { - this.init_(); - var charToByteMap = opt_webSafe - ? this.charToByteMapWebSafe_ - : this.charToByteMap_; - var output = []; - for (var i = 0; i < input.length;) { - var byte1 = charToByteMap[input.charAt(i++)]; - var haveByte2 = i < input.length; - var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; - ++i; - var haveByte3 = i < input.length; - var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; - ++i; - var haveByte4 = i < input.length; - var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; - ++i; - if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { - throw Error(); - } - var outByte1 = (byte1 << 2) | (byte2 >> 4); - output.push(outByte1); - if (byte3 != 64) { - var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); - output.push(outByte2); - if (byte4 != 64) { - var outByte3 = ((byte3 << 6) & 0xc0) | byte4; - output.push(outByte3); - } - } - } - return output; - }, - /** - * Lazy static initialization function. Called before - * accessing any of the static map variables. - * @private - */ - init_: function () { - if (!this.byteToCharMap_) { - this.byteToCharMap_ = {}; - this.charToByteMap_ = {}; - this.byteToCharMapWebSafe_ = {}; - this.charToByteMapWebSafe_ = {}; - // We want quick mappings back and forth, so we precompute two maps. - for (var i = 0; i < this.ENCODED_VALS.length; i++) { - this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); - this.charToByteMap_[this.byteToCharMap_[i]] = i; - this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); - this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; - // Be forgiving when decoding and correctly decode both encodings. - if (i >= this.ENCODED_VALS_BASE.length) { - this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; - this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; - } - } - } - } -}; -/** - * URL-safe base64 encoding - * @param {!string} str - * @return {!string} - */ -var base64Encode = function (str) { - var utf8Bytes = stringToByteArray(str); - return base64.encodeByteArray(utf8Bytes, true); -}; -/** - * URL-safe base64 decoding - * - * NOTE: DO NOT use the global atob() function - it does NOT support the - * base64Url variant encoding. - * - * @param {string} str To be decoded - * @return {?string} Decoded result, if possible - */ -var base64Decode = function (str) { - try { - return base64.decodeString(str, true); - } - catch (e) { - console.error('base64Decode failed: ', e); - } - return null; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Do a deep-copy of basic JavaScript Objects or Arrays. - */ -function deepCopy(value) { - return deepExtend(undefined, value); -} -/** - * Copy properties from source to target (recursively allows extension - * of Objects and Arrays). Scalar values in the target are over-written. - * If target is undefined, an object of the appropriate type will be created - * (and returned). - * - * We recursively copy all child properties of plain Objects in the source- so - * that namespace- like dictionaries are merged. - * - * Note that the target can be a function, in which case the properties in - * the source Object are copied onto it as static properties of the Function. - */ -function deepExtend(target, source) { - if (!(source instanceof Object)) { - return source; - } - switch (source.constructor) { - case Date: - // Treat Dates like scalars; if the target date object had any child - // properties - they will be lost! - var dateValue = source; - return new Date(dateValue.getTime()); - case Object: - if (target === undefined) { - target = {}; - } - break; - case Array: - // Always copy the array source and overwrite the target. - target = []; - break; - default: - // Not a plain Object - treat it as a scalar. - return source; - } - for (var prop in source) { - if (!source.hasOwnProperty(prop)) { - continue; - } - target[prop] = deepExtend(target[prop], source[prop]); - } - return target; -} -// TODO: Really needed (for JSCompiler type checking)? -function patchProperty(obj, prop, value) { - obj[prop] = value; -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Deferred = /** @class */ (function () { - function Deferred() { - var _this = this; - this.promise = new Promise(function (resolve, reject) { - _this.resolve = resolve; - _this.reject = reject; - }); - } - /** - * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around - * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback - * and returns a node-style callback which will resolve or reject the Deferred's promise. - * @param {((?function(?(Error)): (?|undefined))| (?function(?(Error),?=): (?|undefined)))=} callback - * @return {!function(?(Error), ?=)} - */ - Deferred.prototype.wrapCallback = function (callback) { - var _this = this; - return function (error, value) { - if (error) { - _this.reject(error); - } - else { - _this.resolve(value); - } - if (typeof callback === 'function') { - // Attaching noop handler just in case developer wasn't expecting - // promises - _this.promise.catch(function () { }); - // Some of our callbacks don't expect a value and our own tests - // assert that the parameter length is 1 - if (callback.length === 1) { - callback(error); - } - else { - callback(error, value); - } - } - }; - }; - return Deferred; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns navigator.userAgent string or '' if it's not defined. - * @return {string} user agent string - */ -var getUA = function () { - if (typeof navigator !== 'undefined' && - typeof navigator['userAgent'] === 'string') { - return navigator['userAgent']; - } - else { - return ''; - } -}; -/** - * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. - * - * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor - * Cordova `onDeviceReady`, which would normally wait for a callback. - * - * @return {boolean} isMobileCordova - */ -var isMobileCordova = function () { - return (typeof window !== 'undefined' && - !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && - /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); -}; -/** - * Detect React Native. - * - * @return {boolean} True if ReactNative environment is detected. - */ -var isReactNative = function () { - return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); -}; -/** - * Detect Node.js. - * - * @return {boolean} True if Node.js environment is detected. - */ -var isNodeSdk = function () { - return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; -}; - -var ERROR_NAME = 'FirebaseError'; -var captureStackTrace = Error - .captureStackTrace; -// Export for faking in tests -function patchCapture(captureFake) { - var result = captureStackTrace; - captureStackTrace = captureFake; - return result; -} -var FirebaseError = /** @class */ (function () { - function FirebaseError(code, message) { - this.code = code; - this.message = message; - // We want the stack value, if implemented by Error - if (captureStackTrace) { - // Patches this.stack, omitted calls above ErrorFactory#create - captureStackTrace(this, ErrorFactory.prototype.create); - } - else { - try { - // In case of IE11, stack will be set only after error is raised. - // https://docs.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript - throw Error.apply(this, arguments); - } - catch (err) { - this.name = ERROR_NAME; - // Make non-enumerable getter for the property. - Object.defineProperty(this, 'stack', { - get: function () { - return err.stack; - } - }); - } - } - } - return FirebaseError; -}()); -// Back-door inheritance -FirebaseError.prototype = Object.create(Error.prototype); -FirebaseError.prototype.constructor = FirebaseError; -FirebaseError.prototype.name = ERROR_NAME; -var ErrorFactory = /** @class */ (function () { - function ErrorFactory(service, serviceName, errors) { - this.service = service; - this.serviceName = serviceName; - this.errors = errors; - // Matches {$name}, by default. - this.pattern = /\{\$([^}]+)}/g; - // empty - } - ErrorFactory.prototype.create = function (code, data) { - if (data === undefined) { - data = {}; - } - var template = this.errors[code]; - var fullCode = this.service + '/' + code; - var message; - if (template === undefined) { - message = 'Error'; - } - else { - message = template.replace(this.pattern, function (match, key) { - var value = data[key]; - return value !== undefined ? value.toString() : '<' + key + '?>'; - }); - } - // Service: Error message (service/code). - message = this.serviceName + ': ' + message + ' (' + fullCode + ').'; - var err = new FirebaseError(fullCode, message); - // Populate the Error object with message parts for programmatic - // accesses (e.g., e.file). - for (var prop in data) { - if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') { - continue; - } - err[prop] = data[prop]; - } - return err; - }; - return ErrorFactory; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Evaluates a JSON string into a javascript object. - * - * @param {string} str A string containing JSON. - * @return {*} The javascript object representing the specified JSON. - */ -function jsonEval(str) { - return JSON.parse(str); -} -/** - * Returns JSON representing a javascript object. - * @param {*} data Javascript object to be stringified. - * @return {string} The JSON contents of the object. - */ -function stringify(data) { - return JSON.stringify(data); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Decodes a Firebase auth. token into constituent parts. - * - * Notes: - * - May return with invalid / incomplete claims if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {{header: *, claims: *, data: *, signature: string}} - */ -var decode = function (token) { - var header = {}, claims = {}, data = {}, signature = ''; - try { - var parts = token.split('.'); - header = jsonEval(base64Decode(parts[0]) || ''); - claims = jsonEval(base64Decode(parts[1]) || ''); - signature = parts[2]; - data = claims['d'] || {}; - delete claims['d']; - } - catch (e) { } - return { - header: header, - claims: claims, - data: data, - signature: signature - }; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the - * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isValidTimestamp = function (token) { - var claims = decode(token).claims, now = Math.floor(new Date().getTime() / 1000), validSince, validUntil; - if (typeof claims === 'object') { - if (claims.hasOwnProperty('nbf')) { - validSince = claims['nbf']; - } - else if (claims.hasOwnProperty('iat')) { - validSince = claims['iat']; - } - if (claims.hasOwnProperty('exp')) { - validUntil = claims['exp']; - } - else { - // token will expire after 24h by default - validUntil = validSince + 86400; - } - } - return (now && validSince && validUntil && now >= validSince && now <= validUntil); -}; -/** - * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. - * - * Notes: - * - May return null if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {?number} - */ -var issuedAtTime = function (token) { - var claims = decode(token).claims; - if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { - return claims['iat']; - } - return null; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isValidFormat = function (token) { - var decoded = decode(token), claims = decoded.claims; - return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); -}; -/** - * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isAdmin = function (token) { - var claims = decode(token).claims; - return typeof claims === 'object' && claims['admin'] === true; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var safeGet = function (obj, key) { - if (Object.prototype.hasOwnProperty.call(obj, key)) - return obj[key]; - // else return undefined. -}; -/** - * Enumerates the keys/values in an object, excluding keys defined on the prototype. - * - * @param {?Object.} obj Object to enumerate. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -var forEach = function (obj, fn) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn(key, obj[key]); - } - } -}; -/** - * Copies all the (own) properties from one object to another. - * @param {!Object} objTo - * @param {!Object} objFrom - * @return {!Object} objTo - */ -var extend = function (objTo, objFrom) { - forEach(objFrom, function (key, value) { - objTo[key] = value; - }); - return objTo; -}; -/** - * Returns a clone of the specified object. - * @param {!Object} obj - * @return {!Object} cloned obj. - */ -var clone = function (obj) { - return extend({}, obj); -}; -/** - * Returns true if obj has typeof "object" and is not null. Unlike goog.isObject(), does not return true - * for functions. - * - * @param obj {*} A potential object. - * @returns {boolean} True if it's an object. - */ -var isNonNullObject = function (obj) { - return typeof obj === 'object' && obj !== null; -}; -var isEmpty = function (obj) { - for (var key in obj) { - return false; - } - return true; -}; -var getCount = function (obj) { - var rv = 0; - for (var key in obj) { - rv++; - } - return rv; -}; -var map = function (obj, f, opt_obj) { - var res = {}; - for (var key in obj) { - res[key] = f.call(opt_obj, obj[key], key, obj); - } - return res; -}; -var findKey = function (obj, fn, opt_this) { - for (var key in obj) { - if (fn.call(opt_this, obj[key], key, obj)) { - return key; - } - } - return undefined; -}; -var findValue = function (obj, fn, opt_this) { - var key = findKey(obj, fn, opt_this); - return key && obj[key]; -}; -var getAnyKey = function (obj) { - for (var key in obj) { - return key; - } -}; -var getValues = function (obj) { - var res = []; - var i = 0; - for (var key in obj) { - res[i++] = obj[key]; - } - return res; -}; -/** - * Tests whether every key/value pair in an object pass the test implemented - * by the provided function - * - * @param {?Object.} obj Object to test. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -var every = function (obj, fn) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - if (!fn(key, obj[key])) { - return false; - } - } - } - return true; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params - * object (e.g. {arg: 'val', arg2: 'val2'}) - * Note: You must prepend it with ? when adding it to a URL. - * - * @param {!Object} querystringParams - * @return {string} - */ -var querystring = function (querystringParams) { - var params = []; - forEach(querystringParams, function (key, value) { - if (Array.isArray(value)) { - value.forEach(function (arrayVal) { - params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); - }); - } - else { - params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); - } - }); - return params.length ? '&' + params.join('&') : ''; -}; -/** - * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'}) - * - * @param {string} querystring - * @return {!Object} - */ -var querystringDecode = function (querystring) { - var obj = {}; - var tokens = querystring.replace(/^\?/, '').split('&'); - tokens.forEach(function (token) { - if (token) { - var key = token.split('='); - obj[key[0]] = key[1]; - } - }); - return obj; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Copyright 2011 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/** - * @fileoverview Abstract cryptographic hash interface. - * - * See Sha1 and Md5 for sample implementations. - * - */ -/** - * Create a cryptographic hash instance. - * - * @constructor - * @struct - */ -var Hash = /** @class */ (function () { - function Hash() { - /** - * The block size for the hasher. - * @type {number} - */ - this.blockSize = -1; - } - return Hash; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview SHA-1 cryptographic hash. - * Variable names follow the notation in FIPS PUB 180-3: - * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. - * - * Usage: - * var sha1 = new sha1(); - * sha1.update(bytes); - * var hash = sha1.digest(); - * - * Performance: - * Chrome 23: ~400 Mbit/s - * Firefox 16: ~250 Mbit/s - * - */ -/** - * SHA-1 cryptographic hash constructor. - * - * The properties declared here are discussed in the above algorithm document. - * @constructor - * @extends {Hash} - * @final - * @struct - */ -var Sha1 = /** @class */ (function (_super) { - __extends(Sha1, _super); - function Sha1() { - var _this = _super.call(this) || this; - /** - * Holds the previous values of accumulated variables a-e in the compress_ - * function. - * @type {!Array} - * @private - */ - _this.chain_ = []; - /** - * A buffer holding the partially computed hash result. - * @type {!Array} - * @private - */ - _this.buf_ = []; - /** - * An array of 80 bytes, each a part of the message to be hashed. Referred to - * as the message schedule in the docs. - * @type {!Array} - * @private - */ - _this.W_ = []; - /** - * Contains data needed to pad messages less than 64 bytes. - * @type {!Array} - * @private - */ - _this.pad_ = []; - /** - * @private {number} - */ - _this.inbuf_ = 0; - /** - * @private {number} - */ - _this.total_ = 0; - _this.blockSize = 512 / 8; - _this.pad_[0] = 128; - for (var i = 1; i < _this.blockSize; ++i) { - _this.pad_[i] = 0; - } - _this.reset(); - return _this; - } - Sha1.prototype.reset = function () { - this.chain_[0] = 0x67452301; - this.chain_[1] = 0xefcdab89; - this.chain_[2] = 0x98badcfe; - this.chain_[3] = 0x10325476; - this.chain_[4] = 0xc3d2e1f0; - this.inbuf_ = 0; - this.total_ = 0; - }; - /** - * Internal compress helper function. - * @param {!Array|!Uint8Array|string} buf Block to compress. - * @param {number=} opt_offset Offset of the block in the buffer. - * @private - */ - Sha1.prototype.compress_ = function (buf, opt_offset) { - if (!opt_offset) { - opt_offset = 0; - } - var W = this.W_; - // get 16 big endian words - if (typeof buf === 'string') { - for (var i = 0; i < 16; i++) { - // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS - // have a bug that turns the post-increment ++ operator into pre-increment - // during JIT compilation. We have code that depends heavily on SHA-1 for - // correctness and which is affected by this bug, so I've removed all uses - // of post-increment ++ in which the result value is used. We can revert - // this change once the Safari bug - // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and - // most clients have been updated. - W[i] = - (buf.charCodeAt(opt_offset) << 24) | - (buf.charCodeAt(opt_offset + 1) << 16) | - (buf.charCodeAt(opt_offset + 2) << 8) | - buf.charCodeAt(opt_offset + 3); - opt_offset += 4; - } - } - else { - for (var i = 0; i < 16; i++) { - W[i] = - (buf[opt_offset] << 24) | - (buf[opt_offset + 1] << 16) | - (buf[opt_offset + 2] << 8) | - buf[opt_offset + 3]; - opt_offset += 4; - } - } - // expand to 80 words - for (var i = 16; i < 80; i++) { - var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; - } - var a = this.chain_[0]; - var b = this.chain_[1]; - var c = this.chain_[2]; - var d = this.chain_[3]; - var e = this.chain_[4]; - var f, k; - // TODO(user): Try to unroll this loop to speed up the computation. - for (var i = 0; i < 80; i++) { - if (i < 40) { - if (i < 20) { - f = d ^ (b & (c ^ d)); - k = 0x5a827999; - } - else { - f = b ^ c ^ d; - k = 0x6ed9eba1; - } - } - else { - if (i < 60) { - f = (b & c) | (d & (b | c)); - k = 0x8f1bbcdc; - } - else { - f = b ^ c ^ d; - k = 0xca62c1d6; - } - } - var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; - e = d; - d = c; - c = ((b << 30) | (b >>> 2)) & 0xffffffff; - b = a; - a = t; - } - this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; - this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; - this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; - this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; - this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; - }; - Sha1.prototype.update = function (bytes, opt_length) { - // TODO(johnlenz): tighten the function signature and remove this check - if (bytes == null) { - return; - } - if (opt_length === undefined) { - opt_length = bytes.length; - } - var lengthMinusBlock = opt_length - this.blockSize; - var n = 0; - // Using local instead of member variables gives ~5% speedup on Firefox 16. - var buf = this.buf_; - var inbuf = this.inbuf_; - // The outer while loop should execute at most twice. - while (n < opt_length) { - // When we have no data in the block to top up, we can directly process the - // input buffer (assuming it contains sufficient data). This gives ~25% - // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that - // the data is provided in large chunks (or in multiples of 64 bytes). - if (inbuf == 0) { - while (n <= lengthMinusBlock) { - this.compress_(bytes, n); - n += this.blockSize; - } - } - if (typeof bytes === 'string') { - while (n < opt_length) { - buf[inbuf] = bytes.charCodeAt(n); - ++inbuf; - ++n; - if (inbuf == this.blockSize) { - this.compress_(buf); - inbuf = 0; - // Jump to the outer loop so we use the full-block optimization. - break; - } - } - } - else { - while (n < opt_length) { - buf[inbuf] = bytes[n]; - ++inbuf; - ++n; - if (inbuf == this.blockSize) { - this.compress_(buf); - inbuf = 0; - // Jump to the outer loop so we use the full-block optimization. - break; - } - } - } - } - this.inbuf_ = inbuf; - this.total_ += opt_length; - }; - /** @override */ - Sha1.prototype.digest = function () { - var digest = []; - var totalBits = this.total_ * 8; - // Add pad 0x80 0x00*. - if (this.inbuf_ < 56) { - this.update(this.pad_, 56 - this.inbuf_); - } - else { - this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); - } - // Add # bits. - for (var i = this.blockSize - 1; i >= 56; i--) { - this.buf_[i] = totalBits & 255; - totalBits /= 256; // Don't use bit-shifting here! - } - this.compress_(this.buf_); - var n = 0; - for (var i = 0; i < 5; i++) { - for (var j = 24; j >= 0; j -= 8) { - digest[n] = (this.chain_[i] >> j) & 255; - ++n; - } - } - return digest; - }; - return Sha1; -}(Hash)); - -/** - * Helper to make a Subscribe function (just like Promise helps make a - * Thenable). - * - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ -function createSubscribe(executor, onNoObservers) { - var proxy = new ObserverProxy(executor, onNoObservers); - return proxy.subscribe.bind(proxy); -} -/** - * Implement fan-out for any number of Observers attached via a subscribe - * function. - */ -var ObserverProxy = /** @class */ (function () { - /** - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ - function ObserverProxy(executor, onNoObservers) { - var _this = this; - this.observers = []; - this.unsubscribes = []; - this.observerCount = 0; - // Micro-task scheduling by calling task.then(). - this.task = Promise.resolve(); - this.finalized = false; - this.onNoObservers = onNoObservers; - // Call the executor asynchronously so subscribers that are called - // synchronously after the creation of the subscribe function - // can still receive the very first value generated in the executor. - this.task - .then(function () { - executor(_this); - }) - .catch(function (e) { - _this.error(e); - }); - } - ObserverProxy.prototype.next = function (value) { - this.forEachObserver(function (observer) { - observer.next(value); - }); - }; - ObserverProxy.prototype.error = function (error) { - this.forEachObserver(function (observer) { - observer.error(error); - }); - this.close(error); - }; - ObserverProxy.prototype.complete = function () { - this.forEachObserver(function (observer) { - observer.complete(); - }); - this.close(); - }; - /** - * Subscribe function that can be used to add an Observer to the fan-out list. - * - * - We require that no event is sent to a subscriber sychronously to their - * call to subscribe(). - */ - ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) { - var _this = this; - var observer; - if (nextOrObserver === undefined && - error === undefined && - complete === undefined) { - throw new Error('Missing Observer.'); - } - // Assemble an Observer object when passed as callback functions. - if (implementsAnyMethods(nextOrObserver, ['next', 'error', 'complete'])) { - observer = nextOrObserver; - } - else { - observer = { - next: nextOrObserver, - error: error, - complete: complete - }; - } - if (observer.next === undefined) { - observer.next = noop; - } - if (observer.error === undefined) { - observer.error = noop; - } - if (observer.complete === undefined) { - observer.complete = noop; - } - var unsub = this.unsubscribeOne.bind(this, this.observers.length); - // Attempt to subscribe to a terminated Observable - we - // just respond to the Observer with the final error or complete - // event. - if (this.finalized) { - this.task.then(function () { - try { - if (_this.finalError) { - observer.error(_this.finalError); - } - else { - observer.complete(); - } - } - catch (e) { - // nothing - } - return; - }); - } - this.observers.push(observer); - return unsub; - }; - // Unsubscribe is synchronous - we guarantee that no events are sent to - // any unsubscribed Observer. - ObserverProxy.prototype.unsubscribeOne = function (i) { - if (this.observers === undefined || this.observers[i] === undefined) { - return; - } - delete this.observers[i]; - this.observerCount -= 1; - if (this.observerCount === 0 && this.onNoObservers !== undefined) { - this.onNoObservers(this); - } - }; - ObserverProxy.prototype.forEachObserver = function (fn) { - if (this.finalized) { - // Already closed by previous event....just eat the additional values. - return; - } - // Since sendOne calls asynchronously - there is no chance that - // this.observers will become undefined. - for (var i = 0; i < this.observers.length; i++) { - this.sendOne(i, fn); - } - }; - // Call the Observer via one of it's callback function. We are careful to - // confirm that the observe has not been unsubscribed since this asynchronous - // function had been queued. - ObserverProxy.prototype.sendOne = function (i, fn) { - var _this = this; - // Execute the callback asynchronously - this.task.then(function () { - if (_this.observers !== undefined && _this.observers[i] !== undefined) { - try { - fn(_this.observers[i]); - } - catch (e) { - // Ignore exceptions raised in Observers or missing methods of an - // Observer. - // Log error to console. b/31404806 - if (typeof console !== 'undefined' && console.error) { - console.error(e); - } - } - } - }); - }; - ObserverProxy.prototype.close = function (err) { - var _this = this; - if (this.finalized) { - return; - } - this.finalized = true; - if (err !== undefined) { - this.finalError = err; - } - // Proxy is no longer needed - garbage collect references - this.task.then(function () { - _this.observers = undefined; - _this.onNoObservers = undefined; - }); - }; - return ObserverProxy; -}()); -/** Turn synchronous function into one called asynchronously. */ -function async(fn, onError) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - Promise.resolve(true) - .then(function () { - fn.apply(void 0, args); - }) - .catch(function (error) { - if (onError) { - onError(error); - } - }); - }; -} -/** - * Return true if the object passed in implements any of the named methods. - */ -function implementsAnyMethods(obj, methods) { - if (typeof obj !== 'object' || obj === null) { - return false; - } - for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) { - var method = methods_1[_i]; - if (method in obj && typeof obj[method] === 'function') { - return true; - } - } - return false; -} -function noop() { - // do nothing -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Check to make sure the appropriate number of arguments are provided for a public function. - * Throws an error if it fails. - * - * @param {!string} fnName The function name - * @param {!number} minCount The minimum number of arguments to allow for the function call - * @param {!number} maxCount The maximum number of argument to allow for the function call - * @param {!number} argCount The actual number of arguments provided. - */ -var validateArgCount = function (fnName, minCount, maxCount, argCount) { - var argError; - if (argCount < minCount) { - argError = 'at least ' + minCount; - } - else if (argCount > maxCount) { - argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; - } - if (argError) { - var error = fnName + - ' failed: Was called with ' + - argCount + - (argCount === 1 ? ' argument.' : ' arguments.') + - ' Expects ' + - argError + - '.'; - throw new Error(error); - } -}; -/** - * Generates a string to prefix an error message about failed argument validation - * - * @param {!string} fnName The function name - * @param {!number} argumentNumber The index of the argument - * @param {boolean} optional Whether or not the argument is optional - * @return {!string} The prefix to add to the error thrown for validation. - */ -function errorPrefix(fnName, argumentNumber, optional) { - var argName = ''; - switch (argumentNumber) { - case 1: - argName = optional ? 'first' : 'First'; - break; - case 2: - argName = optional ? 'second' : 'Second'; - break; - case 3: - argName = optional ? 'third' : 'Third'; - break; - case 4: - argName = optional ? 'fourth' : 'Fourth'; - break; - default: - throw new Error('errorPrefix called with argumentNumber > 4. Need to update it?'); - } - var error = fnName + ' failed: '; - error += argName + ' argument '; - return error; -} -/** - * @param {!string} fnName - * @param {!number} argumentNumber - * @param {!string} namespace - * @param {boolean} optional - */ -function validateNamespace(fnName, argumentNumber, namespace, optional) { - if (optional && !namespace) - return; - if (typeof namespace !== 'string') { - //TODO: I should do more validation here. We only allow certain chars in namespaces. - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid firebase namespace.'); - } -} -function validateCallback(fnName, argumentNumber, callback, optional) { - if (optional && !callback) - return; - if (typeof callback !== 'function') - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid function.'); -} -function validateContextObject(fnName, argumentNumber, context, optional) { - if (optional && !context) - return; - if (typeof context !== 'object' || context === null) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid context object.'); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they -// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, -// so it's been modified. -// Note that not all Unicode characters appear as single characters in JavaScript strings. -// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters -// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first -// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate -// pair). -// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 -/** - * @param {string} str - * @return {Array} - */ -var stringToByteArray$1 = function (str) { - var out = [], p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - // Is this the lead surrogate in a surrogate pair? - if (c >= 0xd800 && c <= 0xdbff) { - var high = c - 0xd800; // the high 10 bits. - i++; - assert(i < str.length, 'Surrogate pair missing trail surrogate.'); - var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. - c = 0x10000 + (high << 10) + low; - } - if (c < 128) { - out[p++] = c; - } - else if (c < 2048) { - out[p++] = (c >> 6) | 192; - out[p++] = (c & 63) | 128; - } - else if (c < 65536) { - out[p++] = (c >> 12) | 224; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - else { - out[p++] = (c >> 18) | 240; - out[p++] = ((c >> 12) & 63) | 128; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - } - return out; -}; -/** - * Calculate length without actually converting; useful for doing cheaper validation. - * @param {string} str - * @return {number} - */ -var stringLength = function (str) { - var p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - p++; - } - else if (c < 2048) { - p += 2; - } - else if (c >= 0xd800 && c <= 0xdbff) { - // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. - p += 4; - i++; // skip trail surrogate. - } - else { - p += 3; - } - } - return p; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { assert, assertionError, base64, base64Decode, base64Encode, CONSTANTS, deepCopy, deepExtend, patchProperty, Deferred, getUA, isMobileCordova, isNodeSdk, isReactNative, ErrorFactory, FirebaseError, patchCapture, jsonEval, stringify, decode, isAdmin, issuedAtTime, isValidFormat, isValidTimestamp, clone, contains, every, extend, findKey, findValue, forEach, getAnyKey, getCount, getValues, isEmpty, isNonNullObject, map, safeGet, querystring, querystringDecode, Sha1, async, createSubscribe, errorPrefix, validateArgCount, validateCallback, validateContextObject, validateNamespace, stringLength, stringToByteArray$1 as stringToByteArray }; diff --git a/functions/node_modules/@firebase/util/dist/index.node.cjs.js b/functions/node_modules/@firebase/util/dist/index.node.cjs.js deleted file mode 100644 index 0415d13c..00000000 --- a/functions/node_modules/@firebase/util/dist/index.node.cjs.js +++ /dev/null @@ -1,1778 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var tslib_1 = require('tslib'); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. - */ -var CONSTANTS = { - /** - * @define {boolean} Whether this is the client Node.js SDK. - */ - NODE_CLIENT: false, - /** - * @define {boolean} Whether this is the Admin Node.js SDK. - */ - NODE_ADMIN: false, - /** - * Firebase SDK Version - */ - SDK_VERSION: '${JSCORE_VERSION}' -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Throws an error if the provided assertion is falsy - * @param {*} assertion The assertion to be tested for falsiness - * @param {!string} message The message to display if the check fails - */ -var assert = function (assertion, message) { - if (!assertion) { - throw assertionError(message); - } -}; -/** - * Returns an Error object suitable for throwing. - * @param {string} message - * @return {!Error} - */ -var assertionError = function (message) { - return new Error('Firebase Database (' + - CONSTANTS.SDK_VERSION + - ') INTERNAL ASSERT FAILED: ' + - message); -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var stringToByteArray = function (str) { - // TODO(user): Use native implementations if/when available - var out = [], p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - out[p++] = c; - } - else if (c < 2048) { - out[p++] = (c >> 6) | 192; - out[p++] = (c & 63) | 128; - } - else if ((c & 0xfc00) == 0xd800 && - i + 1 < str.length && - (str.charCodeAt(i + 1) & 0xfc00) == 0xdc00) { - // Surrogate Pair - c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff); - out[p++] = (c >> 18) | 240; - out[p++] = ((c >> 12) & 63) | 128; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - else { - out[p++] = (c >> 12) | 224; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - } - return out; -}; -/** - * Turns an array of numbers into the string given by the concatenation of the - * characters to which the numbers correspond. - * @param {Array} bytes Array of numbers representing characters. - * @return {string} Stringification of the array. - */ -var byteArrayToString = function (bytes) { - // TODO(user): Use native implementations if/when available - var out = [], pos = 0, c = 0; - while (pos < bytes.length) { - var c1 = bytes[pos++]; - if (c1 < 128) { - out[c++] = String.fromCharCode(c1); - } - else if (c1 > 191 && c1 < 224) { - var c2 = bytes[pos++]; - out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); - } - else if (c1 > 239 && c1 < 365) { - // Surrogate Pair - var c2 = bytes[pos++]; - var c3 = bytes[pos++]; - var c4 = bytes[pos++]; - var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) - - 0x10000; - out[c++] = String.fromCharCode(0xd800 + (u >> 10)); - out[c++] = String.fromCharCode(0xdc00 + (u & 1023)); - } - else { - var c2 = bytes[pos++]; - var c3 = bytes[pos++]; - out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - } - } - return out.join(''); -}; -// Static lookup maps, lazily populated by init_() -var base64 = { - /** - * Maps bytes to characters. - * @type {Object} - * @private - */ - byteToCharMap_: null, - /** - * Maps characters to bytes. - * @type {Object} - * @private - */ - charToByteMap_: null, - /** - * Maps bytes to websafe characters. - * @type {Object} - * @private - */ - byteToCharMapWebSafe_: null, - /** - * Maps websafe characters to bytes. - * @type {Object} - * @private - */ - charToByteMapWebSafe_: null, - /** - * Our default alphabet, shared between - * ENCODED_VALS and ENCODED_VALS_WEBSAFE - * @type {string} - */ - ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789', - /** - * Our default alphabet. Value 64 (=) is special; it means "nothing." - * @type {string} - */ - get ENCODED_VALS() { - return this.ENCODED_VALS_BASE + '+/='; - }, - /** - * Our websafe alphabet. - * @type {string} - */ - get ENCODED_VALS_WEBSAFE() { - return this.ENCODED_VALS_BASE + '-_.'; - }, - /** - * Whether this browser supports the atob and btoa functions. This extension - * started at Mozilla but is now implemented by many browsers. We use the - * ASSUME_* variables to avoid pulling in the full useragent detection library - * but still allowing the standard per-browser compilations. - * - * @type {boolean} - */ - HAS_NATIVE_SUPPORT: typeof atob === 'function', - /** - * Base64-encode an array of bytes. - * - * @param {Array|Uint8Array} input An array of bytes (numbers with - * value in [0, 255]) to encode. - * @param {boolean=} opt_webSafe Boolean indicating we should use the - * alternative alphabet. - * @return {string} The base64 encoded string. - */ - encodeByteArray: function (input, opt_webSafe) { - if (!Array.isArray(input)) { - throw Error('encodeByteArray takes an array as a parameter'); - } - this.init_(); - var byteToCharMap = opt_webSafe - ? this.byteToCharMapWebSafe_ - : this.byteToCharMap_; - var output = []; - for (var i = 0; i < input.length; i += 3) { - var byte1 = input[i]; - var haveByte2 = i + 1 < input.length; - var byte2 = haveByte2 ? input[i + 1] : 0; - var haveByte3 = i + 2 < input.length; - var byte3 = haveByte3 ? input[i + 2] : 0; - var outByte1 = byte1 >> 2; - var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); - var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6); - var outByte4 = byte3 & 0x3f; - if (!haveByte3) { - outByte4 = 64; - if (!haveByte2) { - outByte3 = 64; - } - } - output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]); - } - return output.join(''); - }, - /** - * Base64-encode a string. - * - * @param {string} input A string to encode. - * @param {boolean=} opt_webSafe If true, we should use the - * alternative alphabet. - * @return {string} The base64 encoded string. - */ - encodeString: function (input, opt_webSafe) { - // Shortcut for Mozilla browsers that implement - // a native base64 encoder in the form of "btoa/atob" - if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) { - return btoa(input); - } - return this.encodeByteArray(stringToByteArray(input), opt_webSafe); - }, - /** - * Base64-decode a string. - * - * @param {string} input to decode. - * @param {boolean=} opt_webSafe True if we should use the - * alternative alphabet. - * @return {string} string representing the decoded value. - */ - decodeString: function (input, opt_webSafe) { - // Shortcut for Mozilla browsers that implement - // a native base64 encoder in the form of "btoa/atob" - if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) { - return atob(input); - } - return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe)); - }, - /** - * Base64-decode a string. - * - * In base-64 decoding, groups of four characters are converted into three - * bytes. If the encoder did not apply padding, the input length may not - * be a multiple of 4. - * - * In this case, the last group will have fewer than 4 characters, and - * padding will be inferred. If the group has one or two characters, it decodes - * to one byte. If the group has three characters, it decodes to two bytes. - * - * @param {string} input Input to decode. - * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet. - * @return {!Array} bytes representing the decoded value. - */ - decodeStringToByteArray: function (input, opt_webSafe) { - this.init_(); - var charToByteMap = opt_webSafe - ? this.charToByteMapWebSafe_ - : this.charToByteMap_; - var output = []; - for (var i = 0; i < input.length;) { - var byte1 = charToByteMap[input.charAt(i++)]; - var haveByte2 = i < input.length; - var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0; - ++i; - var haveByte3 = i < input.length; - var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64; - ++i; - var haveByte4 = i < input.length; - var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64; - ++i; - if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) { - throw Error(); - } - var outByte1 = (byte1 << 2) | (byte2 >> 4); - output.push(outByte1); - if (byte3 != 64) { - var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2); - output.push(outByte2); - if (byte4 != 64) { - var outByte3 = ((byte3 << 6) & 0xc0) | byte4; - output.push(outByte3); - } - } - } - return output; - }, - /** - * Lazy static initialization function. Called before - * accessing any of the static map variables. - * @private - */ - init_: function () { - if (!this.byteToCharMap_) { - this.byteToCharMap_ = {}; - this.charToByteMap_ = {}; - this.byteToCharMapWebSafe_ = {}; - this.charToByteMapWebSafe_ = {}; - // We want quick mappings back and forth, so we precompute two maps. - for (var i = 0; i < this.ENCODED_VALS.length; i++) { - this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i); - this.charToByteMap_[this.byteToCharMap_[i]] = i; - this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i); - this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i; - // Be forgiving when decoding and correctly decode both encodings. - if (i >= this.ENCODED_VALS_BASE.length) { - this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i; - this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i; - } - } - } - } -}; -/** - * URL-safe base64 encoding - * @param {!string} str - * @return {!string} - */ -var base64Encode = function (str) { - var utf8Bytes = stringToByteArray(str); - return base64.encodeByteArray(utf8Bytes, true); -}; -/** - * URL-safe base64 decoding - * - * NOTE: DO NOT use the global atob() function - it does NOT support the - * base64Url variant encoding. - * - * @param {string} str To be decoded - * @return {?string} Decoded result, if possible - */ -var base64Decode = function (str) { - try { - return base64.decodeString(str, true); - } - catch (e) { - console.error('base64Decode failed: ', e); - } - return null; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Do a deep-copy of basic JavaScript Objects or Arrays. - */ -function deepCopy(value) { - return deepExtend(undefined, value); -} -/** - * Copy properties from source to target (recursively allows extension - * of Objects and Arrays). Scalar values in the target are over-written. - * If target is undefined, an object of the appropriate type will be created - * (and returned). - * - * We recursively copy all child properties of plain Objects in the source- so - * that namespace- like dictionaries are merged. - * - * Note that the target can be a function, in which case the properties in - * the source Object are copied onto it as static properties of the Function. - */ -function deepExtend(target, source) { - if (!(source instanceof Object)) { - return source; - } - switch (source.constructor) { - case Date: - // Treat Dates like scalars; if the target date object had any child - // properties - they will be lost! - var dateValue = source; - return new Date(dateValue.getTime()); - case Object: - if (target === undefined) { - target = {}; - } - break; - case Array: - // Always copy the array source and overwrite the target. - target = []; - break; - default: - // Not a plain Object - treat it as a scalar. - return source; - } - for (var prop in source) { - if (!source.hasOwnProperty(prop)) { - continue; - } - target[prop] = deepExtend(target[prop], source[prop]); - } - return target; -} -// TODO: Really needed (for JSCompiler type checking)? -function patchProperty(obj, prop, value) { - obj[prop] = value; -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Deferred = /** @class */ (function () { - function Deferred() { - var _this = this; - this.promise = new Promise(function (resolve, reject) { - _this.resolve = resolve; - _this.reject = reject; - }); - } - /** - * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around - * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback - * and returns a node-style callback which will resolve or reject the Deferred's promise. - * @param {((?function(?(Error)): (?|undefined))| (?function(?(Error),?=): (?|undefined)))=} callback - * @return {!function(?(Error), ?=)} - */ - Deferred.prototype.wrapCallback = function (callback) { - var _this = this; - return function (error, value) { - if (error) { - _this.reject(error); - } - else { - _this.resolve(value); - } - if (typeof callback === 'function') { - // Attaching noop handler just in case developer wasn't expecting - // promises - _this.promise.catch(function () { }); - // Some of our callbacks don't expect a value and our own tests - // assert that the parameter length is 1 - if (callback.length === 1) { - callback(error); - } - else { - callback(error, value); - } - } - }; - }; - return Deferred; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns navigator.userAgent string or '' if it's not defined. - * @return {string} user agent string - */ -var getUA = function () { - if (typeof navigator !== 'undefined' && - typeof navigator['userAgent'] === 'string') { - return navigator['userAgent']; - } - else { - return ''; - } -}; -/** - * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. - * - * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor - * Cordova `onDeviceReady`, which would normally wait for a callback. - * - * @return {boolean} isMobileCordova - */ -var isMobileCordova = function () { - return (typeof window !== 'undefined' && - !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) && - /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())); -}; -/** - * Detect React Native. - * - * @return {boolean} True if ReactNative environment is detected. - */ -var isReactNative = function () { - return (typeof navigator === 'object' && navigator['product'] === 'ReactNative'); -}; -/** - * Detect Node.js. - * - * @return {boolean} True if Node.js environment is detected. - */ -var isNodeSdk = function () { - return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true; -}; - -var ERROR_NAME = 'FirebaseError'; -var captureStackTrace = Error - .captureStackTrace; -// Export for faking in tests -function patchCapture(captureFake) { - var result = captureStackTrace; - captureStackTrace = captureFake; - return result; -} -var FirebaseError = /** @class */ (function () { - function FirebaseError(code, message) { - this.code = code; - this.message = message; - // We want the stack value, if implemented by Error - if (captureStackTrace) { - // Patches this.stack, omitted calls above ErrorFactory#create - captureStackTrace(this, ErrorFactory.prototype.create); - } - else { - try { - // In case of IE11, stack will be set only after error is raised. - // https://docs.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript - throw Error.apply(this, arguments); - } - catch (err) { - this.name = ERROR_NAME; - // Make non-enumerable getter for the property. - Object.defineProperty(this, 'stack', { - get: function () { - return err.stack; - } - }); - } - } - } - return FirebaseError; -}()); -// Back-door inheritance -FirebaseError.prototype = Object.create(Error.prototype); -FirebaseError.prototype.constructor = FirebaseError; -FirebaseError.prototype.name = ERROR_NAME; -var ErrorFactory = /** @class */ (function () { - function ErrorFactory(service, serviceName, errors) { - this.service = service; - this.serviceName = serviceName; - this.errors = errors; - // Matches {$name}, by default. - this.pattern = /\{\$([^}]+)}/g; - // empty - } - ErrorFactory.prototype.create = function (code, data) { - if (data === undefined) { - data = {}; - } - var template = this.errors[code]; - var fullCode = this.service + '/' + code; - var message; - if (template === undefined) { - message = 'Error'; - } - else { - message = template.replace(this.pattern, function (match, key) { - var value = data[key]; - return value !== undefined ? value.toString() : '<' + key + '?>'; - }); - } - // Service: Error message (service/code). - message = this.serviceName + ': ' + message + ' (' + fullCode + ').'; - var err = new FirebaseError(fullCode, message); - // Populate the Error object with message parts for programmatic - // accesses (e.g., e.file). - for (var prop in data) { - if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') { - continue; - } - err[prop] = data[prop]; - } - return err; - }; - return ErrorFactory; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Evaluates a JSON string into a javascript object. - * - * @param {string} str A string containing JSON. - * @return {*} The javascript object representing the specified JSON. - */ -function jsonEval(str) { - return JSON.parse(str); -} -/** - * Returns JSON representing a javascript object. - * @param {*} data Javascript object to be stringified. - * @return {string} The JSON contents of the object. - */ -function stringify(data) { - return JSON.stringify(data); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Decodes a Firebase auth. token into constituent parts. - * - * Notes: - * - May return with invalid / incomplete claims if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {{header: *, claims: *, data: *, signature: string}} - */ -var decode = function (token) { - var header = {}, claims = {}, data = {}, signature = ''; - try { - var parts = token.split('.'); - header = jsonEval(base64Decode(parts[0]) || ''); - claims = jsonEval(base64Decode(parts[1]) || ''); - signature = parts[2]; - data = claims['d'] || {}; - delete claims['d']; - } - catch (e) { } - return { - header: header, - claims: claims, - data: data, - signature: signature - }; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the - * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isValidTimestamp = function (token) { - var claims = decode(token).claims, now = Math.floor(new Date().getTime() / 1000), validSince, validUntil; - if (typeof claims === 'object') { - if (claims.hasOwnProperty('nbf')) { - validSince = claims['nbf']; - } - else if (claims.hasOwnProperty('iat')) { - validSince = claims['iat']; - } - if (claims.hasOwnProperty('exp')) { - validUntil = claims['exp']; - } - else { - // token will expire after 24h by default - validUntil = validSince + 86400; - } - } - return (now && validSince && validUntil && now >= validSince && now <= validUntil); -}; -/** - * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. - * - * Notes: - * - May return null if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {?number} - */ -var issuedAtTime = function (token) { - var claims = decode(token).claims; - if (typeof claims === 'object' && claims.hasOwnProperty('iat')) { - return claims['iat']; - } - return null; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isValidFormat = function (token) { - var decoded = decode(token), claims = decoded.claims; - return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat'); -}; -/** - * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -var isAdmin = function (token) { - var claims = decode(token).claims; - return typeof claims === 'object' && claims['admin'] === true; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ -var contains = function (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -}; -var safeGet = function (obj, key) { - if (Object.prototype.hasOwnProperty.call(obj, key)) - return obj[key]; - // else return undefined. -}; -/** - * Enumerates the keys/values in an object, excluding keys defined on the prototype. - * - * @param {?Object.} obj Object to enumerate. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -var forEach = function (obj, fn) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn(key, obj[key]); - } - } -}; -/** - * Copies all the (own) properties from one object to another. - * @param {!Object} objTo - * @param {!Object} objFrom - * @return {!Object} objTo - */ -var extend = function (objTo, objFrom) { - forEach(objFrom, function (key, value) { - objTo[key] = value; - }); - return objTo; -}; -/** - * Returns a clone of the specified object. - * @param {!Object} obj - * @return {!Object} cloned obj. - */ -var clone = function (obj) { - return extend({}, obj); -}; -/** - * Returns true if obj has typeof "object" and is not null. Unlike goog.isObject(), does not return true - * for functions. - * - * @param obj {*} A potential object. - * @returns {boolean} True if it's an object. - */ -var isNonNullObject = function (obj) { - return typeof obj === 'object' && obj !== null; -}; -var isEmpty = function (obj) { - for (var key in obj) { - return false; - } - return true; -}; -var getCount = function (obj) { - var rv = 0; - for (var key in obj) { - rv++; - } - return rv; -}; -var map = function (obj, f, opt_obj) { - var res = {}; - for (var key in obj) { - res[key] = f.call(opt_obj, obj[key], key, obj); - } - return res; -}; -var findKey = function (obj, fn, opt_this) { - for (var key in obj) { - if (fn.call(opt_this, obj[key], key, obj)) { - return key; - } - } - return undefined; -}; -var findValue = function (obj, fn, opt_this) { - var key = findKey(obj, fn, opt_this); - return key && obj[key]; -}; -var getAnyKey = function (obj) { - for (var key in obj) { - return key; - } -}; -var getValues = function (obj) { - var res = []; - var i = 0; - for (var key in obj) { - res[i++] = obj[key]; - } - return res; -}; -/** - * Tests whether every key/value pair in an object pass the test implemented - * by the provided function - * - * @param {?Object.} obj Object to test. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -var every = function (obj, fn) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - if (!fn(key, obj[key])) { - return false; - } - } - } - return true; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params - * object (e.g. {arg: 'val', arg2: 'val2'}) - * Note: You must prepend it with ? when adding it to a URL. - * - * @param {!Object} querystringParams - * @return {string} - */ -var querystring = function (querystringParams) { - var params = []; - forEach(querystringParams, function (key, value) { - if (Array.isArray(value)) { - value.forEach(function (arrayVal) { - params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)); - }); - } - else { - params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); - } - }); - return params.length ? '&' + params.join('&') : ''; -}; -/** - * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'}) - * - * @param {string} querystring - * @return {!Object} - */ -var querystringDecode = function (querystring) { - var obj = {}; - var tokens = querystring.replace(/^\?/, '').split('&'); - tokens.forEach(function (token) { - if (token) { - var key = token.split('='); - obj[key[0]] = key[1]; - } - }); - return obj; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Copyright 2011 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/** - * @fileoverview Abstract cryptographic hash interface. - * - * See Sha1 and Md5 for sample implementations. - * - */ -/** - * Create a cryptographic hash instance. - * - * @constructor - * @struct - */ -var Hash = /** @class */ (function () { - function Hash() { - /** - * The block size for the hasher. - * @type {number} - */ - this.blockSize = -1; - } - return Hash; -}()); - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview SHA-1 cryptographic hash. - * Variable names follow the notation in FIPS PUB 180-3: - * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. - * - * Usage: - * var sha1 = new sha1(); - * sha1.update(bytes); - * var hash = sha1.digest(); - * - * Performance: - * Chrome 23: ~400 Mbit/s - * Firefox 16: ~250 Mbit/s - * - */ -/** - * SHA-1 cryptographic hash constructor. - * - * The properties declared here are discussed in the above algorithm document. - * @constructor - * @extends {Hash} - * @final - * @struct - */ -var Sha1 = /** @class */ (function (_super) { - tslib_1.__extends(Sha1, _super); - function Sha1() { - var _this = _super.call(this) || this; - /** - * Holds the previous values of accumulated variables a-e in the compress_ - * function. - * @type {!Array} - * @private - */ - _this.chain_ = []; - /** - * A buffer holding the partially computed hash result. - * @type {!Array} - * @private - */ - _this.buf_ = []; - /** - * An array of 80 bytes, each a part of the message to be hashed. Referred to - * as the message schedule in the docs. - * @type {!Array} - * @private - */ - _this.W_ = []; - /** - * Contains data needed to pad messages less than 64 bytes. - * @type {!Array} - * @private - */ - _this.pad_ = []; - /** - * @private {number} - */ - _this.inbuf_ = 0; - /** - * @private {number} - */ - _this.total_ = 0; - _this.blockSize = 512 / 8; - _this.pad_[0] = 128; - for (var i = 1; i < _this.blockSize; ++i) { - _this.pad_[i] = 0; - } - _this.reset(); - return _this; - } - Sha1.prototype.reset = function () { - this.chain_[0] = 0x67452301; - this.chain_[1] = 0xefcdab89; - this.chain_[2] = 0x98badcfe; - this.chain_[3] = 0x10325476; - this.chain_[4] = 0xc3d2e1f0; - this.inbuf_ = 0; - this.total_ = 0; - }; - /** - * Internal compress helper function. - * @param {!Array|!Uint8Array|string} buf Block to compress. - * @param {number=} opt_offset Offset of the block in the buffer. - * @private - */ - Sha1.prototype.compress_ = function (buf, opt_offset) { - if (!opt_offset) { - opt_offset = 0; - } - var W = this.W_; - // get 16 big endian words - if (typeof buf === 'string') { - for (var i = 0; i < 16; i++) { - // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS - // have a bug that turns the post-increment ++ operator into pre-increment - // during JIT compilation. We have code that depends heavily on SHA-1 for - // correctness and which is affected by this bug, so I've removed all uses - // of post-increment ++ in which the result value is used. We can revert - // this change once the Safari bug - // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and - // most clients have been updated. - W[i] = - (buf.charCodeAt(opt_offset) << 24) | - (buf.charCodeAt(opt_offset + 1) << 16) | - (buf.charCodeAt(opt_offset + 2) << 8) | - buf.charCodeAt(opt_offset + 3); - opt_offset += 4; - } - } - else { - for (var i = 0; i < 16; i++) { - W[i] = - (buf[opt_offset] << 24) | - (buf[opt_offset + 1] << 16) | - (buf[opt_offset + 2] << 8) | - buf[opt_offset + 3]; - opt_offset += 4; - } - } - // expand to 80 words - for (var i = 16; i < 80; i++) { - var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; - } - var a = this.chain_[0]; - var b = this.chain_[1]; - var c = this.chain_[2]; - var d = this.chain_[3]; - var e = this.chain_[4]; - var f, k; - // TODO(user): Try to unroll this loop to speed up the computation. - for (var i = 0; i < 80; i++) { - if (i < 40) { - if (i < 20) { - f = d ^ (b & (c ^ d)); - k = 0x5a827999; - } - else { - f = b ^ c ^ d; - k = 0x6ed9eba1; - } - } - else { - if (i < 60) { - f = (b & c) | (d & (b | c)); - k = 0x8f1bbcdc; - } - else { - f = b ^ c ^ d; - k = 0xca62c1d6; - } - } - var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; - e = d; - d = c; - c = ((b << 30) | (b >>> 2)) & 0xffffffff; - b = a; - a = t; - } - this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; - this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; - this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; - this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; - this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; - }; - Sha1.prototype.update = function (bytes, opt_length) { - // TODO(johnlenz): tighten the function signature and remove this check - if (bytes == null) { - return; - } - if (opt_length === undefined) { - opt_length = bytes.length; - } - var lengthMinusBlock = opt_length - this.blockSize; - var n = 0; - // Using local instead of member variables gives ~5% speedup on Firefox 16. - var buf = this.buf_; - var inbuf = this.inbuf_; - // The outer while loop should execute at most twice. - while (n < opt_length) { - // When we have no data in the block to top up, we can directly process the - // input buffer (assuming it contains sufficient data). This gives ~25% - // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that - // the data is provided in large chunks (or in multiples of 64 bytes). - if (inbuf == 0) { - while (n <= lengthMinusBlock) { - this.compress_(bytes, n); - n += this.blockSize; - } - } - if (typeof bytes === 'string') { - while (n < opt_length) { - buf[inbuf] = bytes.charCodeAt(n); - ++inbuf; - ++n; - if (inbuf == this.blockSize) { - this.compress_(buf); - inbuf = 0; - // Jump to the outer loop so we use the full-block optimization. - break; - } - } - } - else { - while (n < opt_length) { - buf[inbuf] = bytes[n]; - ++inbuf; - ++n; - if (inbuf == this.blockSize) { - this.compress_(buf); - inbuf = 0; - // Jump to the outer loop so we use the full-block optimization. - break; - } - } - } - } - this.inbuf_ = inbuf; - this.total_ += opt_length; - }; - /** @override */ - Sha1.prototype.digest = function () { - var digest = []; - var totalBits = this.total_ * 8; - // Add pad 0x80 0x00*. - if (this.inbuf_ < 56) { - this.update(this.pad_, 56 - this.inbuf_); - } - else { - this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); - } - // Add # bits. - for (var i = this.blockSize - 1; i >= 56; i--) { - this.buf_[i] = totalBits & 255; - totalBits /= 256; // Don't use bit-shifting here! - } - this.compress_(this.buf_); - var n = 0; - for (var i = 0; i < 5; i++) { - for (var j = 24; j >= 0; j -= 8) { - digest[n] = (this.chain_[i] >> j) & 255; - ++n; - } - } - return digest; - }; - return Sha1; -}(Hash)); - -/** - * Helper to make a Subscribe function (just like Promise helps make a - * Thenable). - * - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ -function createSubscribe(executor, onNoObservers) { - var proxy = new ObserverProxy(executor, onNoObservers); - return proxy.subscribe.bind(proxy); -} -/** - * Implement fan-out for any number of Observers attached via a subscribe - * function. - */ -var ObserverProxy = /** @class */ (function () { - /** - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ - function ObserverProxy(executor, onNoObservers) { - var _this = this; - this.observers = []; - this.unsubscribes = []; - this.observerCount = 0; - // Micro-task scheduling by calling task.then(). - this.task = Promise.resolve(); - this.finalized = false; - this.onNoObservers = onNoObservers; - // Call the executor asynchronously so subscribers that are called - // synchronously after the creation of the subscribe function - // can still receive the very first value generated in the executor. - this.task - .then(function () { - executor(_this); - }) - .catch(function (e) { - _this.error(e); - }); - } - ObserverProxy.prototype.next = function (value) { - this.forEachObserver(function (observer) { - observer.next(value); - }); - }; - ObserverProxy.prototype.error = function (error) { - this.forEachObserver(function (observer) { - observer.error(error); - }); - this.close(error); - }; - ObserverProxy.prototype.complete = function () { - this.forEachObserver(function (observer) { - observer.complete(); - }); - this.close(); - }; - /** - * Subscribe function that can be used to add an Observer to the fan-out list. - * - * - We require that no event is sent to a subscriber sychronously to their - * call to subscribe(). - */ - ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) { - var _this = this; - var observer; - if (nextOrObserver === undefined && - error === undefined && - complete === undefined) { - throw new Error('Missing Observer.'); - } - // Assemble an Observer object when passed as callback functions. - if (implementsAnyMethods(nextOrObserver, ['next', 'error', 'complete'])) { - observer = nextOrObserver; - } - else { - observer = { - next: nextOrObserver, - error: error, - complete: complete - }; - } - if (observer.next === undefined) { - observer.next = noop; - } - if (observer.error === undefined) { - observer.error = noop; - } - if (observer.complete === undefined) { - observer.complete = noop; - } - var unsub = this.unsubscribeOne.bind(this, this.observers.length); - // Attempt to subscribe to a terminated Observable - we - // just respond to the Observer with the final error or complete - // event. - if (this.finalized) { - this.task.then(function () { - try { - if (_this.finalError) { - observer.error(_this.finalError); - } - else { - observer.complete(); - } - } - catch (e) { - // nothing - } - return; - }); - } - this.observers.push(observer); - return unsub; - }; - // Unsubscribe is synchronous - we guarantee that no events are sent to - // any unsubscribed Observer. - ObserverProxy.prototype.unsubscribeOne = function (i) { - if (this.observers === undefined || this.observers[i] === undefined) { - return; - } - delete this.observers[i]; - this.observerCount -= 1; - if (this.observerCount === 0 && this.onNoObservers !== undefined) { - this.onNoObservers(this); - } - }; - ObserverProxy.prototype.forEachObserver = function (fn) { - if (this.finalized) { - // Already closed by previous event....just eat the additional values. - return; - } - // Since sendOne calls asynchronously - there is no chance that - // this.observers will become undefined. - for (var i = 0; i < this.observers.length; i++) { - this.sendOne(i, fn); - } - }; - // Call the Observer via one of it's callback function. We are careful to - // confirm that the observe has not been unsubscribed since this asynchronous - // function had been queued. - ObserverProxy.prototype.sendOne = function (i, fn) { - var _this = this; - // Execute the callback asynchronously - this.task.then(function () { - if (_this.observers !== undefined && _this.observers[i] !== undefined) { - try { - fn(_this.observers[i]); - } - catch (e) { - // Ignore exceptions raised in Observers or missing methods of an - // Observer. - // Log error to console. b/31404806 - if (typeof console !== 'undefined' && console.error) { - console.error(e); - } - } - } - }); - }; - ObserverProxy.prototype.close = function (err) { - var _this = this; - if (this.finalized) { - return; - } - this.finalized = true; - if (err !== undefined) { - this.finalError = err; - } - // Proxy is no longer needed - garbage collect references - this.task.then(function () { - _this.observers = undefined; - _this.onNoObservers = undefined; - }); - }; - return ObserverProxy; -}()); -/** Turn synchronous function into one called asynchronously. */ -function async(fn, onError) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - Promise.resolve(true) - .then(function () { - fn.apply(void 0, args); - }) - .catch(function (error) { - if (onError) { - onError(error); - } - }); - }; -} -/** - * Return true if the object passed in implements any of the named methods. - */ -function implementsAnyMethods(obj, methods) { - if (typeof obj !== 'object' || obj === null) { - return false; - } - for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) { - var method = methods_1[_i]; - if (method in obj && typeof obj[method] === 'function') { - return true; - } - } - return false; -} -function noop() { - // do nothing -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Check to make sure the appropriate number of arguments are provided for a public function. - * Throws an error if it fails. - * - * @param {!string} fnName The function name - * @param {!number} minCount The minimum number of arguments to allow for the function call - * @param {!number} maxCount The maximum number of argument to allow for the function call - * @param {!number} argCount The actual number of arguments provided. - */ -var validateArgCount = function (fnName, minCount, maxCount, argCount) { - var argError; - if (argCount < minCount) { - argError = 'at least ' + minCount; - } - else if (argCount > maxCount) { - argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount; - } - if (argError) { - var error = fnName + - ' failed: Was called with ' + - argCount + - (argCount === 1 ? ' argument.' : ' arguments.') + - ' Expects ' + - argError + - '.'; - throw new Error(error); - } -}; -/** - * Generates a string to prefix an error message about failed argument validation - * - * @param {!string} fnName The function name - * @param {!number} argumentNumber The index of the argument - * @param {boolean} optional Whether or not the argument is optional - * @return {!string} The prefix to add to the error thrown for validation. - */ -function errorPrefix(fnName, argumentNumber, optional) { - var argName = ''; - switch (argumentNumber) { - case 1: - argName = optional ? 'first' : 'First'; - break; - case 2: - argName = optional ? 'second' : 'Second'; - break; - case 3: - argName = optional ? 'third' : 'Third'; - break; - case 4: - argName = optional ? 'fourth' : 'Fourth'; - break; - default: - throw new Error('errorPrefix called with argumentNumber > 4. Need to update it?'); - } - var error = fnName + ' failed: '; - error += argName + ' argument '; - return error; -} -/** - * @param {!string} fnName - * @param {!number} argumentNumber - * @param {!string} namespace - * @param {boolean} optional - */ -function validateNamespace(fnName, argumentNumber, namespace, optional) { - if (optional && !namespace) - return; - if (typeof namespace !== 'string') { - //TODO: I should do more validation here. We only allow certain chars in namespaces. - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid firebase namespace.'); - } -} -function validateCallback(fnName, argumentNumber, callback, optional) { - if (optional && !callback) - return; - if (typeof callback !== 'function') - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid function.'); -} -function validateContextObject(fnName, argumentNumber, context, optional) { - if (optional && !context) - return; - if (typeof context !== 'object' || context === null) - throw new Error(errorPrefix(fnName, argumentNumber, optional) + - 'must be a valid context object.'); -} - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they -// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs, -// so it's been modified. -// Note that not all Unicode characters appear as single characters in JavaScript strings. -// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters -// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first -// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate -// pair). -// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 -/** - * @param {string} str - * @return {Array} - */ -var stringToByteArray$1 = function (str) { - var out = [], p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - // Is this the lead surrogate in a surrogate pair? - if (c >= 0xd800 && c <= 0xdbff) { - var high = c - 0xd800; // the high 10 bits. - i++; - assert(i < str.length, 'Surrogate pair missing trail surrogate.'); - var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits. - c = 0x10000 + (high << 10) + low; - } - if (c < 128) { - out[p++] = c; - } - else if (c < 2048) { - out[p++] = (c >> 6) | 192; - out[p++] = (c & 63) | 128; - } - else if (c < 65536) { - out[p++] = (c >> 12) | 224; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - else { - out[p++] = (c >> 18) | 240; - out[p++] = ((c >> 12) & 63) | 128; - out[p++] = ((c >> 6) & 63) | 128; - out[p++] = (c & 63) | 128; - } - } - return out; -}; -/** - * Calculate length without actually converting; useful for doing cheaper validation. - * @param {string} str - * @return {number} - */ -var stringLength = function (str) { - var p = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - p++; - } - else if (c < 2048) { - p += 2; - } - else if (c >= 0xd800 && c <= 0xdbff) { - // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent. - p += 4; - i++; // skip trail surrogate. - } - else { - p += 3; - } - } - return p; -}; - -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Overriding the constant (we should be the only ones doing this) -CONSTANTS.NODE_CLIENT = true; - -exports.assert = assert; -exports.assertionError = assertionError; -exports.base64 = base64; -exports.base64Encode = base64Encode; -exports.base64Decode = base64Decode; -exports.CONSTANTS = CONSTANTS; -exports.deepCopy = deepCopy; -exports.deepExtend = deepExtend; -exports.patchProperty = patchProperty; -exports.Deferred = Deferred; -exports.getUA = getUA; -exports.isMobileCordova = isMobileCordova; -exports.isReactNative = isReactNative; -exports.isNodeSdk = isNodeSdk; -exports.patchCapture = patchCapture; -exports.FirebaseError = FirebaseError; -exports.ErrorFactory = ErrorFactory; -exports.jsonEval = jsonEval; -exports.stringify = stringify; -exports.decode = decode; -exports.isValidTimestamp = isValidTimestamp; -exports.issuedAtTime = issuedAtTime; -exports.isValidFormat = isValidFormat; -exports.isAdmin = isAdmin; -exports.contains = contains; -exports.safeGet = safeGet; -exports.forEach = forEach; -exports.extend = extend; -exports.clone = clone; -exports.isNonNullObject = isNonNullObject; -exports.isEmpty = isEmpty; -exports.getCount = getCount; -exports.map = map; -exports.findKey = findKey; -exports.findValue = findValue; -exports.getAnyKey = getAnyKey; -exports.getValues = getValues; -exports.every = every; -exports.querystring = querystring; -exports.querystringDecode = querystringDecode; -exports.Sha1 = Sha1; -exports.createSubscribe = createSubscribe; -exports.async = async; -exports.validateArgCount = validateArgCount; -exports.errorPrefix = errorPrefix; -exports.validateNamespace = validateNamespace; -exports.validateCallback = validateCallback; -exports.validateContextObject = validateContextObject; -exports.stringToByteArray = stringToByteArray$1; -exports.stringLength = stringLength; diff --git a/functions/node_modules/@firebase/util/dist/index.node.d.ts b/functions/node_modules/@firebase/util/dist/index.node.d.ts deleted file mode 100644 index 71ea6fa1..00000000 --- a/functions/node_modules/@firebase/util/dist/index.node.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -export * from './src/assert'; -export * from './src/crypt'; -export * from './src/constants'; -export * from './src/deepCopy'; -export * from './src/deferred'; -export * from './src/environment'; -export * from './src/errors'; -export * from './src/json'; -export * from './src/jwt'; -export * from './src/obj'; -export * from './src/query'; -export * from './src/sha1'; -export * from './src/subscribe'; -export * from './src/validation'; -export * from './src/utf8'; diff --git a/functions/node_modules/@firebase/util/dist/src/assert.d.ts b/functions/node_modules/@firebase/util/dist/src/assert.d.ts deleted file mode 100644 index 79e8f7ca..00000000 --- a/functions/node_modules/@firebase/util/dist/src/assert.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Throws an error if the provided assertion is falsy - * @param {*} assertion The assertion to be tested for falsiness - * @param {!string} message The message to display if the check fails - */ -export declare const assert: (assertion: any, message: any) => void; -/** - * Returns an Error object suitable for throwing. - * @param {string} message - * @return {!Error} - */ -export declare const assertionError: (message: any) => Error; diff --git a/functions/node_modules/@firebase/util/dist/src/constants.d.ts b/functions/node_modules/@firebase/util/dist/src/constants.d.ts deleted file mode 100644 index 94dacf45..00000000 --- a/functions/node_modules/@firebase/util/dist/src/constants.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time. - */ -export declare const CONSTANTS: { - NODE_CLIENT: boolean; - NODE_ADMIN: boolean; - SDK_VERSION: string; -}; diff --git a/functions/node_modules/@firebase/util/dist/src/crypt.d.ts b/functions/node_modules/@firebase/util/dist/src/crypt.d.ts deleted file mode 100644 index 0fea6d2c..00000000 --- a/functions/node_modules/@firebase/util/dist/src/crypt.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -export declare const base64: { - byteToCharMap_: any; - charToByteMap_: any; - byteToCharMapWebSafe_: any; - charToByteMapWebSafe_: any; - ENCODED_VALS_BASE: string; - readonly ENCODED_VALS: string; - readonly ENCODED_VALS_WEBSAFE: string; - HAS_NATIVE_SUPPORT: boolean; - encodeByteArray(input: any, opt_webSafe?: any): string; - encodeString(input: any, opt_webSafe: any): any; - decodeString(input: any, opt_webSafe: any): string; - decodeStringToByteArray(input: any, opt_webSafe: any): any[]; - init_(): void; -}; -/** - * URL-safe base64 encoding - * @param {!string} str - * @return {!string} - */ -export declare const base64Encode: (str: string) => string; -/** - * URL-safe base64 decoding - * - * NOTE: DO NOT use the global atob() function - it does NOT support the - * base64Url variant encoding. - * - * @param {string} str To be decoded - * @return {?string} Decoded result, if possible - */ -export declare const base64Decode: (str: string) => string; diff --git a/functions/node_modules/@firebase/util/dist/src/deepCopy.d.ts b/functions/node_modules/@firebase/util/dist/src/deepCopy.d.ts deleted file mode 100644 index 49439647..00000000 --- a/functions/node_modules/@firebase/util/dist/src/deepCopy.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Do a deep-copy of basic JavaScript Objects or Arrays. - */ -export declare function deepCopy(value: T): T; -/** - * Copy properties from source to target (recursively allows extension - * of Objects and Arrays). Scalar values in the target are over-written. - * If target is undefined, an object of the appropriate type will be created - * (and returned). - * - * We recursively copy all child properties of plain Objects in the source- so - * that namespace- like dictionaries are merged. - * - * Note that the target can be a function, in which case the properties in - * the source Object are copied onto it as static properties of the Function. - */ -export declare function deepExtend(target: any, source: any): any; -export declare function patchProperty(obj: any, prop: string, value: any): void; diff --git a/functions/node_modules/@firebase/util/dist/src/deferred.d.ts b/functions/node_modules/@firebase/util/dist/src/deferred.d.ts deleted file mode 100644 index 0f9be25d..00000000 --- a/functions/node_modules/@firebase/util/dist/src/deferred.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export declare class Deferred { - promise: Promise; - reject: any; - resolve: any; - constructor(); - /** - * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around - * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback - * and returns a node-style callback which will resolve or reject the Deferred's promise. - * @param {((?function(?(Error)): (?|undefined))| (?function(?(Error),?=): (?|undefined)))=} callback - * @return {!function(?(Error), ?=)} - */ - wrapCallback(callback?: any): (error: any, value?: any) => void; -} diff --git a/functions/node_modules/@firebase/util/dist/src/environment.d.ts b/functions/node_modules/@firebase/util/dist/src/environment.d.ts deleted file mode 100644 index 62e7d37c..00000000 --- a/functions/node_modules/@firebase/util/dist/src/environment.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Returns navigator.userAgent string or '' if it's not defined. - * @return {string} user agent string - */ -export declare const getUA: () => string; -/** - * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device. - * - * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor - * Cordova `onDeviceReady`, which would normally wait for a callback. - * - * @return {boolean} isMobileCordova - */ -export declare const isMobileCordova: () => boolean; -/** - * Detect React Native. - * - * @return {boolean} True if ReactNative environment is detected. - */ -export declare const isReactNative: () => boolean; -/** - * Detect Node.js. - * - * @return {boolean} True if Node.js environment is detected. - */ -export declare const isNodeSdk: () => boolean; diff --git a/functions/node_modules/@firebase/util/dist/src/errors.d.ts b/functions/node_modules/@firebase/util/dist/src/errors.d.ts deleted file mode 100644 index 9898e68b..00000000 --- a/functions/node_modules/@firebase/util/dist/src/errors.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Standardized Firebase Error. - * - * Usage: - * - * // Typescript string literals for type-safe codes - * type Err = - * 'unknown' | - * 'object-not-found' - * ; - * - * // Closure enum for type-safe error codes - * // at-enum {string} - * var Err = { - * UNKNOWN: 'unknown', - * OBJECT_NOT_FOUND: 'object-not-found', - * } - * - * let errors: Map = { - * 'generic-error': "Unknown error", - * 'file-not-found': "Could not find file: {$file}", - * }; - * - * // Type-safe function - must pass a valid error code as param. - * let error = new ErrorFactory('service', 'Service', errors); - * - * ... - * throw error.create(Err.GENERIC); - * ... - * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName}); - * ... - * // Service: Could not file file: foo.txt (service/file-not-found). - * - * catch (e) { - * assert(e.message === "Could not find file: foo.txt."); - * if (e.code === 'service/file-not-found') { - * console.log("Could not read file: " + e['file']); - * } - * } - */ -export declare type ErrorList = { - [code: string]: string; -}; -export interface StringLike { - toString: () => string; -} -export declare function patchCapture(captureFake?: any): any; -export interface FirebaseError { - code: string; - message: string; - name: string; - stack: string; -} -export declare class FirebaseError implements FirebaseError { - code: string; - message: string; - stack: string; - name: string; - constructor(code: string, message: string); -} -export declare class ErrorFactory { - private service; - private serviceName; - private errors; - pattern: RegExp; - constructor(service: string, serviceName: string, errors: ErrorList); - create(code: T, data?: { - [prop: string]: StringLike; - }): FirebaseError; -} diff --git a/functions/node_modules/@firebase/util/dist/src/hash.d.ts b/functions/node_modules/@firebase/util/dist/src/hash.d.ts deleted file mode 100644 index b2a51260..00000000 --- a/functions/node_modules/@firebase/util/dist/src/hash.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @fileoverview Abstract cryptographic hash interface. - * - * See Sha1 and Md5 for sample implementations. - * - */ -/** - * Create a cryptographic hash instance. - * - * @constructor - * @struct - */ -export declare class Hash { - /** - * The block size for the hasher. - * @type {number} - */ - blockSize: number; - constructor(); -} diff --git a/functions/node_modules/@firebase/util/dist/src/json.d.ts b/functions/node_modules/@firebase/util/dist/src/json.d.ts deleted file mode 100644 index 73aa0293..00000000 --- a/functions/node_modules/@firebase/util/dist/src/json.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Evaluates a JSON string into a javascript object. - * - * @param {string} str A string containing JSON. - * @return {*} The javascript object representing the specified JSON. - */ -export declare function jsonEval(str: any): any; -/** - * Returns JSON representing a javascript object. - * @param {*} data Javascript object to be stringified. - * @return {string} The JSON contents of the object. - */ -export declare function stringify(data: any): string; diff --git a/functions/node_modules/@firebase/util/dist/src/jwt.d.ts b/functions/node_modules/@firebase/util/dist/src/jwt.d.ts deleted file mode 100644 index d77023ce..00000000 --- a/functions/node_modules/@firebase/util/dist/src/jwt.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Decodes a Firebase auth. token into constituent parts. - * - * Notes: - * - May return with invalid / incomplete claims if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {{header: *, claims: *, data: *, signature: string}} - */ -export declare const decode: (token: any) => { - header: {}; - claims: {}; - data: {}; - signature: string; -}; -/** - * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the - * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -export declare const isValidTimestamp: (token: any) => boolean; -/** - * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise. - * - * Notes: - * - May return null if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {?number} - */ -export declare const issuedAtTime: (token: any) => any; -/** - * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -export declare const isValidFormat: (token: any) => boolean; -/** - * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion. - * - * Notes: - * - May return a false negative if there's no native base64 decoding support. - * - Doesn't check if the token is actually valid. - * - * @param {?string} token - * @return {boolean} - */ -export declare const isAdmin: (token: any) => boolean; diff --git a/functions/node_modules/@firebase/util/dist/src/obj.d.ts b/functions/node_modules/@firebase/util/dist/src/obj.d.ts deleted file mode 100644 index f613bdb7..00000000 --- a/functions/node_modules/@firebase/util/dist/src/obj.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export declare const contains: (obj: any, key: any) => any; -export declare const safeGet: (obj: any, key: any) => any; -/** - * Enumerates the keys/values in an object, excluding keys defined on the prototype. - * - * @param {?Object.} obj Object to enumerate. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -export declare const forEach: (obj: any, fn: any) => void; -/** - * Copies all the (own) properties from one object to another. - * @param {!Object} objTo - * @param {!Object} objFrom - * @return {!Object} objTo - */ -export declare const extend: (objTo: any, objFrom: any) => any; -/** - * Returns a clone of the specified object. - * @param {!Object} obj - * @return {!Object} cloned obj. - */ -export declare const clone: (obj: any) => any; -/** - * Returns true if obj has typeof "object" and is not null. Unlike goog.isObject(), does not return true - * for functions. - * - * @param obj {*} A potential object. - * @returns {boolean} True if it's an object. - */ -export declare const isNonNullObject: (obj: any) => boolean; -export declare const isEmpty: (obj: any) => boolean; -export declare const getCount: (obj: any) => number; -export declare const map: (obj: any, f: any, opt_obj?: any) => {}; -export declare const findKey: (obj: any, fn: any, opt_this?: any) => string; -export declare const findValue: (obj: any, fn: any, opt_this?: any) => any; -export declare const getAnyKey: (obj: any) => string; -export declare const getValues: (obj: any) => any[]; -/** - * Tests whether every key/value pair in an object pass the test implemented - * by the provided function - * - * @param {?Object.} obj Object to test. - * @param {!function(K, V)} fn Function to call for each key and value. - * @template K,V - */ -export declare const every: (obj: Object, fn: (k: string, v?: V) => boolean) => boolean; diff --git a/functions/node_modules/@firebase/util/dist/src/query.d.ts b/functions/node_modules/@firebase/util/dist/src/query.d.ts deleted file mode 100644 index cb319232..00000000 --- a/functions/node_modules/@firebase/util/dist/src/query.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params - * object (e.g. {arg: 'val', arg2: 'val2'}) - * Note: You must prepend it with ? when adding it to a URL. - * - * @param {!Object} querystringParams - * @return {string} - */ -export declare const querystring: (querystringParams: any) => string; -/** - * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'}) - * - * @param {string} querystring - * @return {!Object} - */ -export declare const querystringDecode: (querystring: any) => {}; diff --git a/functions/node_modules/@firebase/util/dist/src/sha1.d.ts b/functions/node_modules/@firebase/util/dist/src/sha1.d.ts deleted file mode 100644 index f73c0731..00000000 --- a/functions/node_modules/@firebase/util/dist/src/sha1.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { Hash } from './hash'; -/** - * @fileoverview SHA-1 cryptographic hash. - * Variable names follow the notation in FIPS PUB 180-3: - * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf. - * - * Usage: - * var sha1 = new sha1(); - * sha1.update(bytes); - * var hash = sha1.digest(); - * - * Performance: - * Chrome 23: ~400 Mbit/s - * Firefox 16: ~250 Mbit/s - * - */ -/** - * SHA-1 cryptographic hash constructor. - * - * The properties declared here are discussed in the above algorithm document. - * @constructor - * @extends {Hash} - * @final - * @struct - */ -export declare class Sha1 extends Hash { - /** - * Holds the previous values of accumulated variables a-e in the compress_ - * function. - * @type {!Array} - * @private - */ - private chain_; - /** - * A buffer holding the partially computed hash result. - * @type {!Array} - * @private - */ - private buf_; - /** - * An array of 80 bytes, each a part of the message to be hashed. Referred to - * as the message schedule in the docs. - * @type {!Array} - * @private - */ - private W_; - /** - * Contains data needed to pad messages less than 64 bytes. - * @type {!Array} - * @private - */ - private pad_; - /** - * @private {number} - */ - private inbuf_; - /** - * @private {number} - */ - private total_; - constructor(); - reset(): void; - /** - * Internal compress helper function. - * @param {!Array|!Uint8Array|string} buf Block to compress. - * @param {number=} opt_offset Offset of the block in the buffer. - * @private - */ - compress_(buf: any, opt_offset?: any): void; - update(bytes: any, opt_length?: any): void; - /** @override */ - digest(): any[]; -} diff --git a/functions/node_modules/@firebase/util/dist/src/subscribe.d.ts b/functions/node_modules/@firebase/util/dist/src/subscribe.d.ts deleted file mode 100644 index 0e3f4bb7..00000000 --- a/functions/node_modules/@firebase/util/dist/src/subscribe.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export declare type NextFn = (value: T) => void; -export declare type ErrorFn = (error: Error) => void; -export declare type CompleteFn = () => void; -export interface Observer { - next: NextFn; - error: ErrorFn; - complete: CompleteFn; -} -export declare type PartialObserver = Partial>; -export declare type Unsubscribe = () => void; -/** - * The Subscribe interface has two forms - passing the inline function - * callbacks, or a object interface with callback properties. - */ -export interface Subscribe { - (next?: NextFn, error?: ErrorFn, complete?: CompleteFn): Unsubscribe; - (observer: PartialObserver): Unsubscribe; -} -export interface Observable { - subscribe: Subscribe; -} -export declare type Executor = (observer: Observer) => void; -/** - * Helper to make a Subscribe function (just like Promise helps make a - * Thenable). - * - * @param executor Function which can make calls to a single Observer - * as a proxy. - * @param onNoObservers Callback when count of Observers goes to zero. - */ -export declare function createSubscribe(executor: Executor, onNoObservers?: Executor): Subscribe; -/** Turn synchronous function into one called asynchronously. */ -export declare function async(fn: Function, onError?: ErrorFn): Function; diff --git a/functions/node_modules/@firebase/util/dist/src/utf8.d.ts b/functions/node_modules/@firebase/util/dist/src/utf8.d.ts deleted file mode 100644 index 2bc20369..00000000 --- a/functions/node_modules/@firebase/util/dist/src/utf8.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @param {string} str - * @return {Array} - */ -export declare const stringToByteArray: (str: any) => any[]; -/** - * Calculate length without actually converting; useful for doing cheaper validation. - * @param {string} str - * @return {number} - */ -export declare const stringLength: (str: any) => number; diff --git a/functions/node_modules/@firebase/util/dist/src/validation.d.ts b/functions/node_modules/@firebase/util/dist/src/validation.d.ts deleted file mode 100644 index ef542789..00000000 --- a/functions/node_modules/@firebase/util/dist/src/validation.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright 2017 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Check to make sure the appropriate number of arguments are provided for a public function. - * Throws an error if it fails. - * - * @param {!string} fnName The function name - * @param {!number} minCount The minimum number of arguments to allow for the function call - * @param {!number} maxCount The maximum number of argument to allow for the function call - * @param {!number} argCount The actual number of arguments provided. - */ -export declare const validateArgCount: (fnName: any, minCount: any, maxCount: any, argCount: any) => void; -/** - * Generates a string to prefix an error message about failed argument validation - * - * @param {!string} fnName The function name - * @param {!number} argumentNumber The index of the argument - * @param {boolean} optional Whether or not the argument is optional - * @return {!string} The prefix to add to the error thrown for validation. - */ -export declare function errorPrefix(fnName: any, argumentNumber: any, optional: any): string; -/** - * @param {!string} fnName - * @param {!number} argumentNumber - * @param {!string} namespace - * @param {boolean} optional - */ -export declare function validateNamespace(fnName: any, argumentNumber: any, namespace: any, optional: any): void; -export declare function validateCallback(fnName: any, argumentNumber: any, callback: any, optional: any): void; -export declare function validateContextObject(fnName: any, argumentNumber: any, context: any, optional: any): void; diff --git a/functions/node_modules/@firebase/util/dist/test/base64.test.d.ts b/functions/node_modules/@firebase/util/dist/test/base64.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/util/dist/test/base64.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts b/functions/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/util/dist/test/deepCopy.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/util/dist/test/errors.test.d.ts b/functions/node_modules/@firebase/util/dist/test/errors.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/util/dist/test/errors.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/util/dist/test/subscribe.test.d.ts b/functions/node_modules/@firebase/util/dist/test/subscribe.test.d.ts deleted file mode 100644 index cb0ff5c3..00000000 --- a/functions/node_modules/@firebase/util/dist/test/subscribe.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/functions/node_modules/@firebase/util/package.json b/functions/node_modules/@firebase/util/package.json deleted file mode 100644 index dce43b34..00000000 --- a/functions/node_modules/@firebase/util/package.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "_from": "@firebase/util@0.2.3", - "_id": "@firebase/util@0.2.3", - "_inBundle": false, - "_integrity": "sha512-ngAG4qYpcnnshUKbBlEiR9+j37U7dTrTVJlS4v7ahW1ROuyLT9xj6cWyHQANzcTR2yKLmEv3yfwoZwedz7V0oQ==", - "_location": "/@firebase/util", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "@firebase/util@0.2.3", - "name": "@firebase/util", - "escapedName": "@firebase%2futil", - "scope": "@firebase", - "rawSpec": "0.2.3", - "saveSpec": null, - "fetchSpec": "0.2.3" - }, - "_requiredBy": [ - "/@firebase/app", - "/@firebase/database" - ], - "_resolved": "https://registry.npmjs.org/@firebase/util/-/util-0.2.3.tgz", - "_shasum": "ad5513cb35eeecabae5169e439d4e200f0d180ae", - "_spec": "@firebase/util@0.2.3", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@firebase\\app", - "author": { - "name": "Firebase", - "email": "firebase-support@google.com", - "url": "https://firebase.google.com/" - }, - "browser": "dist/index.cjs.js", - "bugs": { - "url": "https://github.com/firebase/firebase-js-sdk/issues" - }, - "bundleDependencies": false, - "dependencies": { - "tslib": "1.9.0" - }, - "deprecated": false, - "description": "_NOTE: This is specifically tailored for Firebase JS SDK usage, if you are not a member of the Firebase team, please avoid using this package_", - "devDependencies": { - "@types/chai": "4.1.2", - "@types/mocha": "5.0.0", - "@types/sinon": "4.3.1", - "chai": "4.1.2", - "karma": "2.0.0", - "karma-chrome-launcher": "2.2.0", - "karma-cli": "1.0.1", - "karma-firefox-launcher": "1.1.0", - "karma-mocha": "1.3.0", - "karma-sauce-launcher": "1.2.0", - "karma-spec-reporter": "0.0.32", - "karma-webpack": "2.0.9", - "mocha": "5.2.0", - "npm-run-all": "4.1.2", - "nyc": "11.6.0", - "rollup": "0.57.1", - "rollup-plugin-commonjs": "9.1.0", - "rollup-plugin-node-resolve": "3.3.0", - "rollup-plugin-typescript2": "0.12.0", - "ts-loader": "3.5.0", - "ts-node": "5.0.1", - "typescript": "2.8.1", - "webpack": "3.11.0" - }, - "files": [ - "dist" - ], - "license": "Apache-2.0", - "main": "dist/index.node.cjs.js", - "module": "dist/index.esm.js", - "name": "@firebase/util", - "nyc": { - "extension": [ - ".ts" - ], - "reportDir": "./coverage/node" - }, - "repository": { - "type": "git", - "url": "https://github.com/firebase/firebase-js-sdk/tree/master/packages/util" - }, - "scripts": { - "build": "rollup -c", - "dev": "rollup -c -w", - "prepare": "npm run build", - "test": "run-p test:browser test:node", - "test:browser": "karma start --single-run", - "test:node": "TS_NODE_CACHE=NO nyc --reporter lcovonly -- mocha test/**/*.test.* --compilers ts:ts-node/register/type-check --exit" - }, - "typings": "dist/index.d.ts", - "version": "0.2.3" -} diff --git a/functions/node_modules/@google-cloud/common/CONTRIBUTORS b/functions/node_modules/@google-cloud/common/CONTRIBUTORS deleted file mode 100644 index 0c2a77ae..00000000 --- a/functions/node_modules/@google-cloud/common/CONTRIBUTORS +++ /dev/null @@ -1,19 +0,0 @@ -# The names of individuals who have contributed to this project. -# -# Names are formatted as: -# name -# -Ali Ijaz Sheikh -Austin Peterson -Dave Gramlich -Eric Uldall -Ernest Landrito -Jason Dobry -Justin King -Karolis Narkevicius -Kelvin Jin -Luke Sneeringer -Matthew Loring -Michael Prentice -Stephen Sawchuk -Tim Swast diff --git a/functions/node_modules/@google-cloud/common/LICENSE b/functions/node_modules/@google-cloud/common/LICENSE deleted file mode 100644 index 7a4a3ea2..00000000 --- a/functions/node_modules/@google-cloud/common/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/functions/node_modules/@google-cloud/common/README.md b/functions/node_modules/@google-cloud/common/README.md deleted file mode 100644 index 73527bc6..00000000 --- a/functions/node_modules/@google-cloud/common/README.md +++ /dev/null @@ -1,79 +0,0 @@ -Google Cloud Platform logo - -# [Google Cloud Common Module: Node.js Client](https://github.com/googlecloudplatform/google-cloud-node) - -[![release level](https://img.shields.io/badge/release%20level-alpha-orange.svg?style=flat)](https://cloud.google.com/terms/launch-stages) -[![CircleCI](https://img.shields.io/circleci/project/github/googleapis/nodejs-common.svg?style=flat)](https://circleci.com/gh/googleapis/nodejs-common) -[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/googleapis/nodejs-common?branch=master&svg=true)](https://ci.appveyor.com/project/googleapis/nodejs-common) -[![codecov](https://img.shields.io/codecov/c/github/googleapis/nodejs-common/master.svg?style=flat)](https://codecov.io/gh/googleapis/nodejs-common) - -> Node.js Common package - -Google Cloud Common node.js module contains stuff used by other Cloud API modules. - -* [github.com/googlecloudplatform/google-cloud-node](https://github.com/googlecloudplatform/google-cloud-node) - -Read more about the client libraries for Cloud APIs, including the older -Google APIs Client Libraries, in [Client Libraries Explained][explained]. - -[explained]: https://cloud.google.com/apis/docs/client-libraries-explained - -**Table of contents:** - -* [Quickstart](#quickstart) - * [Before you begin](#before-you-begin) - * [Installing the client library](#installing-the-client-library) - * [Using the client library](#using-the-client-library) -* [Versioning](#versioning) -* [Contributing](#contributing) -* [License](#license) - -## Quickstart - -### Before you begin - -1. Select or create a Cloud Platform project. - - [Go to the projects page][projects] - -1. Enable billing for your project. - - [Enable billing][billing] - -1. [Set up authentication with a service account][auth] so you can access the - API from your local workstation. - -[projects]: https://console.cloud.google.com/project -[billing]: https://support.google.com/cloud/answer/6293499#enable-billing -[auth]: https://cloud.google.com/docs/authentication/getting-started - -### Installing the package - - npm install --save @google-cloud/common - -It's unlikely you will need to install this package directly, as it will be -installed as a dependency when you install other `@google-cloud` packages. - -## Versioning - -This library follows [Semantic Versioning](http://semver.org/). - -This library is considered to be in **alpha**. This means it is still a -work-in-progress and under active development. Any release is subject to -backwards-incompatible changes at any time. - -More Information: [Google Cloud Platform Launch Stages][launch_stages] - -[launch_stages]: https://cloud.google.com/terms/launch-stages - -## Contributing - -Contributions welcome! See the [Contributing Guide](https://github.com/googlecloudplatform/google-cloud-node/blob/master/.github/CONTRIBUTING.md). - -## License - -Apache Version 2.0 - -See [LICENSE](https://github.com/googlecloudplatform/google-cloud-node/blob/master/LICENSE) - -[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png diff --git a/functions/node_modules/@google-cloud/common/node_modules/retry-request/index.d.ts b/functions/node_modules/@google-cloud/common/node_modules/retry-request/index.d.ts deleted file mode 100644 index 2fdb9e92..00000000 --- a/functions/node_modules/@google-cloud/common/node_modules/retry-request/index.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -declare module 'retry-request' { - import * as request from 'request'; - - namespace retryRequest { - function getNextRetryDelay(retryNumber: number): void; - interface Options { - objectMode?: boolean, - request?: typeof request, - retries?: number, - noResponseRetries?: number, - currentRetryAttempt?: number, - shouldRetryFn?: (response: request.RequestResponse) => boolean - } - } - - function retryRequest(requestOpts: request.Options, opts: retryRequest.Options, callback?: request.RequestCallback) - : { abort: () => void }; - function retryRequest(requestOpts: request.Options, callback?: request.RequestCallback) - : { abort: () => void }; - - export = retryRequest; -} diff --git a/functions/node_modules/@google-cloud/common/node_modules/retry-request/index.js b/functions/node_modules/@google-cloud/common/node_modules/retry-request/index.js deleted file mode 100644 index 125876a3..00000000 --- a/functions/node_modules/@google-cloud/common/node_modules/retry-request/index.js +++ /dev/null @@ -1,209 +0,0 @@ -'use strict'; - -var request = require('request'); -var through = require('through2'); - -var DEFAULTS = { - objectMode: false, - request: request, - retries: 2, - noResponseRetries: 2, - currentRetryAttempt: 0, - shouldRetryFn: function (response) { - var retryRanges = [ - // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes - // 1xx - Retry (Informational, request still processing) - // 2xx - Do not retry (Success) - // 3xx - Do not retry (Redirect) - // 4xx - Do not retry (Client errors) - // 429 - Retry ("Too Many Requests") - // 5xx - Retry (Server errors) - [100, 199], - [429, 429], - [500, 599] - ]; - - var statusCode = response.statusCode; - - var range; - while ((range = retryRanges.shift())) { - if (statusCode >= range[0] && statusCode <= range[1]) { - // Not a successful status or redirect. - return true; - } - } - } -}; - -function retryRequest(requestOpts, opts, callback) { - var streamMode = typeof arguments[arguments.length - 1] !== 'function'; - - if (typeof opts === 'function') { - callback = opts; - } - - opts = opts || DEFAULTS; - - if (typeof opts.objectMode === 'undefined') { - opts.objectMode = DEFAULTS.objectMode; - } - if (typeof opts.request === 'undefined') { - opts.request = DEFAULTS.request; - } - if (typeof opts.retries !== 'number') { - opts.retries = DEFAULTS.retries; - } - if (typeof opts.currentRetryAttempt !== 'number') { - opts.currentRetryAttempt = DEFAULTS.currentRetryAttempt; - } - if (typeof opts.noResponseRetries !== 'number') { - opts.noResponseRetries = DEFAULTS.noResponseRetries; - } - if (typeof opts.shouldRetryFn !== 'function') { - opts.shouldRetryFn = DEFAULTS.shouldRetryFn; - } - - var currentRetryAttempt = opts.currentRetryAttempt; - - var numNoResponseAttempts = 0; - var streamResponseHandled = false; - - var retryStream; - var requestStream; - var delayStream; - - var activeRequest; - var retryRequest = { - abort: function () { - if (activeRequest && activeRequest.abort) { - activeRequest.abort(); - } - } - }; - - if (streamMode) { - retryStream = through({ objectMode: opts.objectMode }); - retryStream.abort = resetStreams; - } - - if (currentRetryAttempt > 0) { - retryAfterDelay(currentRetryAttempt); - } else { - makeRequest(); - } - - if (streamMode) { - return retryStream; - } else { - return retryRequest; - } - - function resetStreams() { - delayStream = null; - - if (requestStream) { - requestStream.abort && requestStream.abort(); - requestStream.cancel && requestStream.cancel(); - - if (requestStream.destroy) { - requestStream.destroy(); - } else if (requestStream.end) { - requestStream.end(); - } - } - } - - function makeRequest() { - currentRetryAttempt++; - - if (streamMode) { - streamResponseHandled = false; - - delayStream = through({ objectMode: opts.objectMode }); - requestStream = opts.request(requestOpts); - - setImmediate(function () { - retryStream.emit('request'); - }); - - requestStream - // gRPC via google-cloud-node can emit an `error` as well as a `response` - // Whichever it emits, we run with-- we can't run with both. That's what - // is up with the `streamResponseHandled` tracking. - .on('error', function (err) { - if (streamResponseHandled) { - return; - } - - streamResponseHandled = true; - onResponse(err); - }) - .on('response', function (resp, body) { - if (streamResponseHandled) { - return; - } - - streamResponseHandled = true; - onResponse(null, resp, body); - }) - .on('complete', retryStream.emit.bind(retryStream, 'complete')); - - requestStream.pipe(delayStream); - } else { - activeRequest = opts.request(requestOpts, onResponse); - } - } - - function retryAfterDelay(currentRetryAttempt) { - if (streamMode) { - resetStreams(); - } - - setTimeout(makeRequest, getNextRetryDelay(currentRetryAttempt)); - } - - function onResponse(err, response, body) { - // An error such as DNS resolution. - if (err) { - numNoResponseAttempts++; - - if (numNoResponseAttempts <= opts.noResponseRetries) { - retryAfterDelay(numNoResponseAttempts); - } else { - if (streamMode) { - retryStream.emit('error', err); - retryStream.end(); - } else { - callback(err, response, body); - } - } - - return; - } - - // Send the response to see if we should try again. - if (currentRetryAttempt <= opts.retries && opts.shouldRetryFn(response)) { - retryAfterDelay(currentRetryAttempt); - return; - } - - // No more attempts need to be made, just continue on. - if (streamMode) { - retryStream.emit('response', response); - delayStream.pipe(retryStream); - requestStream.on('error', function (err) { - retryStream.destroy(err); - }); - } else { - callback(err, response, body); - } - } -} - -module.exports = retryRequest; - -function getNextRetryDelay(retryNumber) { - return (Math.pow(2, retryNumber) * 1000) + Math.floor(Math.random() * 1000); -} - -module.exports.getNextRetryDelay = getNextRetryDelay; diff --git a/functions/node_modules/@google-cloud/common/node_modules/retry-request/license b/functions/node_modules/@google-cloud/common/node_modules/retry-request/license deleted file mode 100644 index df6eeb55..00000000 --- a/functions/node_modules/@google-cloud/common/node_modules/retry-request/license +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Stephen Sawchuk - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/functions/node_modules/@google-cloud/common/node_modules/retry-request/package.json b/functions/node_modules/@google-cloud/common/node_modules/retry-request/package.json deleted file mode 100644 index 740a0545..00000000 --- a/functions/node_modules/@google-cloud/common/node_modules/retry-request/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "_from": "retry-request@^3.0.0", - "_id": "retry-request@3.3.2", - "_inBundle": false, - "_integrity": "sha512-WIiGp37XXDC6e7ku3LFoi7LCL/Gs9luGeeqvbPRb+Zl6OQMw4RCRfSaW+aLfE6lhz1R941UavE6Svl3Dm5xGIQ==", - "_location": "/@google-cloud/common/retry-request", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "retry-request@^3.0.0", - "name": "retry-request", - "escapedName": "retry-request", - "rawSpec": "^3.0.0", - "saveSpec": null, - "fetchSpec": "^3.0.0" - }, - "_requiredBy": [ - "/@google-cloud/common" - ], - "_resolved": "https://registry.npmjs.org/retry-request/-/retry-request-3.3.2.tgz", - "_shasum": "fd8e0079e7b0dfc7056e500b6f089437db0da4df", - "_spec": "retry-request@^3.0.0", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@google-cloud\\common", - "author": { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - }, - "bugs": { - "url": "https://github.com/stephenplusplus/retry-request/issues" - }, - "bundleDependencies": false, - "dependencies": { - "request": "^2.81.0", - "through2": "^2.0.0" - }, - "deprecated": false, - "description": "Retry a request.", - "devDependencies": { - "async": "^2.5.0", - "lodash.range": "^3.2.0", - "mocha": "^2.2.5" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "index.d.ts", - "license" - ], - "homepage": "https://github.com/stephenplusplus/retry-request#readme", - "keywords": [ - "request", - "retry", - "stream" - ], - "license": "MIT", - "main": "index.js", - "name": "retry-request", - "repository": { - "type": "git", - "url": "git+https://github.com/stephenplusplus/retry-request.git" - }, - "scripts": { - "test": "mocha --timeout 0" - }, - "types": "index.d.ts", - "version": "3.3.2" -} diff --git a/functions/node_modules/@google-cloud/common/node_modules/retry-request/readme.md b/functions/node_modules/@google-cloud/common/node_modules/retry-request/readme.md deleted file mode 100644 index 62feabd2..00000000 --- a/functions/node_modules/@google-cloud/common/node_modules/retry-request/readme.md +++ /dev/null @@ -1,152 +0,0 @@ -|![retry-request](logo.png) -|:-: -|Retry a [request][request] with built-in [exponential backoff](https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors#backoff). - -```sh -$ npm install --save retry-request -``` -```js -var request = require('retry-request'); -``` - -It should work the same as `request` in both callback mode and stream mode. - -Note: This module only works when used as a readable stream, i.e. POST requests aren't supported ([#3](https://github.com/stephenplusplus/retry-request/issues/3)). - -#### Callback - -`urlThatReturns503` will be requested 3 total times before giving up and executing the callback. - -```js -request(urlThatReturns503, function (err, resp, body) {}); -``` - -#### Stream - -`urlThatReturns503` will be requested 3 total times before giving up and emitting the `response` and `complete` event as usual. - -```js -request(urlThatReturns503) - .on('error', function () {}) - .on('response', function () {}) - .on('complete', function () {}); -``` - -## request(requestOptions, [opts], [cb]) - -### requestOptions - -Passed directly to `request`. See the list of options supported: https://github.com/request/request/#requestoptions-callback. - -### opts *(optional)* - -#### `opts.noResponseRetries` - -Type: `Number` - -Default: `2` - -The number of times to retry after a response fails to come through, such as a DNS resolution error or a socket hangup. - -```js -var opts = { - noResponseRetries: 0 -}; - -request(url, opts, function (err, resp, body) { - // url was requested 1 time before giving up and - // executing this callback. -}); -``` - -#### `opts.objectMode` - -Type: `Boolean` - -Default: `false` - -Set to `true` if your custom `opts.request` function returns a stream in object mode. - -#### `opts.retries` - -Type: `Number` - -Default: `2` - -```js -var opts = { - retries: 4 -}; - -request(urlThatReturns503, opts, function (err, resp, body) { - // urlThatReturns503 was requested a total of 5 times - // before giving up and executing this callback. -}); -``` - -#### `opts.currentRetryAttempt` - -Type: `Number` - -Default: `0` - -```js -var opts = { - currentRetryAttempt: 1 -}; - -request(urlThatReturns503, opts, function (err, resp, body) { - // urlThatReturns503 was requested as if it already failed once. -}); -``` - -#### `opts.shouldRetryFn` - -Type: `Function` - -Default: Returns `true` if [http.incomingMessage](https://nodejs.org/api/http.html#http_http_incomingmessage).statusCode is < 200 or >= 400. - -```js -var opts = { - shouldRetryFn: function (incomingHttpMessage) { - return incomingHttpMessage.statusMessage !== 'OK'; - } -}; - -request(urlThatReturnsNonOKStatusMessage, opts, function (err, resp, body) { - // urlThatReturnsNonOKStatusMessage was requested a - // total of 3 times, each time using `opts.shouldRetryFn` - // to decide if it should continue before giving up and - // executing this callback. -}); -``` - -#### `opts.request` - -Type: `Function` - -Default: [`request`][request] - -*NOTE: If you override the request function, and it returns a stream in object mode, be sure to set `opts.objectMode` to `true`.* - -```js -var originalRequest = require('request').defaults({ - pool: { - maxSockets: Infinity - } -}); - -var opts = { - request: originalRequest -}; - -request(urlThatReturns503, opts, function (err, resp, body) { - // Your provided `originalRequest` instance was used. -}); -``` - -### cb *(optional)* - -Passed directly to `request`. See the callback section: https://github.com/request/request/#requestoptions-callback. - -[request]: https://github.com/request/request diff --git a/functions/node_modules/@google-cloud/common/package.json b/functions/node_modules/@google-cloud/common/package.json deleted file mode 100644 index 02090733..00000000 --- a/functions/node_modules/@google-cloud/common/package.json +++ /dev/null @@ -1,166 +0,0 @@ -{ - "_from": "@google-cloud/common@^0.17.0", - "_id": "@google-cloud/common@0.17.0", - "_inBundle": false, - "_integrity": "sha512-HRZLSU762E6HaKoGfJGa8W95yRjb9rY7LePhjaHK9ILAnFacMuUGVamDbTHu1csZomm1g3tZTtXfX/aAhtie/Q==", - "_location": "/@google-cloud/common", - "_phantomChildren": { - "request": "2.88.0", - "through2": "2.0.5" - }, - "_requested": { - "type": "range", - "registry": true, - "raw": "@google-cloud/common@^0.17.0", - "name": "@google-cloud/common", - "escapedName": "@google-cloud%2fcommon", - "scope": "@google-cloud", - "rawSpec": "^0.17.0", - "saveSpec": null, - "fetchSpec": "^0.17.0" - }, - "_requiredBy": [ - "/@google-cloud/storage" - ], - "_resolved": "https://registry.npmjs.org/@google-cloud/common/-/common-0.17.0.tgz", - "_shasum": "8ef558750db481fc10a13757a49479ab9a1c8c07", - "_spec": "@google-cloud/common@^0.17.0", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@google-cloud\\storage", - "author": { - "name": "Google Inc." - }, - "bugs": { - "url": "https://github.com/googleapis/nodejs-common/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Ali Ijaz Sheikh", - "email": "ofrobots@google.com" - }, - { - "name": "Austin Peterson", - "email": "austin@akpwebdesign.com" - }, - { - "name": "Dave Gramlich", - "email": "callmehiphop@gmail.com" - }, - { - "name": "Eric Uldall", - "email": "ericuldall@gmail.com" - }, - { - "name": "Ernest Landrito", - "email": "landrito@google.com" - }, - { - "name": "Jason Dobry", - "email": "jdobry@google.com" - }, - { - "name": "Justin King", - "email": "jcking@mtu.edu" - }, - { - "name": "Karolis Narkevicius", - "email": "karolis.n@gmail.com" - }, - { - "name": "Kelvin Jin", - "email": "kelvinjin@google.com" - }, - { - "name": "Luke Sneeringer", - "email": "lukesneeringer@google.com" - }, - { - "name": "Matthew Loring", - "email": "matthewloring@users.noreply.github.com" - }, - { - "name": "Michael Prentice", - "email": "splaktar@gmail.com" - }, - { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - }, - { - "name": "Tim Swast", - "email": "swast@google.com" - } - ], - "dependencies": { - "array-uniq": "^1.0.3", - "arrify": "^1.0.1", - "concat-stream": "^1.6.0", - "create-error-class": "^3.0.2", - "duplexify": "^3.5.0", - "ent": "^2.2.0", - "extend": "^3.0.1", - "google-auto-auth": "^0.10.0", - "is": "^3.2.0", - "log-driver": "1.2.7", - "methmeth": "^1.1.0", - "modelo": "^4.2.0", - "request": "^2.79.0", - "retry-request": "^3.0.0", - "split-array-stream": "^1.0.0", - "stream-events": "^1.0.1", - "string-format-obj": "^1.1.0", - "through2": "^2.0.3" - }, - "deprecated": false, - "description": "Common components for Cloud APIs Node.js Client Libraries", - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "^2.1.1", - "async": "^2.6.0", - "codecov": "^3.0.0", - "eslint": "^4.10.0", - "eslint-config-prettier": "^2.7.0", - "eslint-plugin-node": "^6.0.0", - "eslint-plugin-prettier": "^2.3.1", - "ink-docstrap": "^1.3.0", - "intelli-espower-loader": "^1.0.1", - "js-green-licenses": "^0.5.0", - "jsdoc": "^3.5.5", - "mocha": "^5.0.0", - "nyc": "^11.3.0", - "power-assert": "^1.4.4", - "prettier": "^1.11.1", - "proxyquire": "^2.0.0", - "uuid": "^3.0.1" - }, - "engines": { - "node": ">=4.0.0" - }, - "files": [ - "src", - "AUTHORS", - "CONTRIBUTORS", - "LICENSE" - ], - "homepage": "https://github.com/googleapis/nodejs-common#readme", - "license": "Apache-2.0", - "main": "./src/index.js", - "name": "@google-cloud/common", - "repository": { - "type": "git", - "url": "git+https://github.com/googleapis/nodejs-common.git" - }, - "scripts": { - "cover": "nyc --reporter=lcov mocha --require intelli-espower-loader test/*.js && nyc report", - "docs": "repo-tools exec -- jsdoc -c .jsdoc.js", - "generate-scaffolding": "repo-tools generate all", - "license-check": "jsgl --local .", - "lint": "repo-tools lint --cmd eslint -- src/ samples/ system-test/ test/", - "posttest": "npm run license-check", - "prettier": "repo-tools exec -- prettier --write src/*.js src/*/*.js samples/*.js samples/*/*.js test/*.js test/*/*.js system-test/*.js system-test/*/*.js", - "publish-module": "node ../../scripts/publish.js common", - "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", - "test": "repo-tools test run --cmd npm -- run cover", - "test-no-cover": "repo-tools test run --cmd mocha -- test/*.js --no-timeouts" - }, - "version": "0.17.0" -} diff --git a/functions/node_modules/@google-cloud/common/src/index.js b/functions/node_modules/@google-cloud/common/src/index.js deleted file mode 100644 index f27cd73b..00000000 --- a/functions/node_modules/@google-cloud/common/src/index.js +++ /dev/null @@ -1,51 +0,0 @@ -/*! - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @type {module:common/logger} - * @private - */ -exports.logger = require('./logger.js'); - -/** - * @type {module:common/operation} - * @private - */ -exports.Operation = require('./operation.js'); - -/** - * @type {module:common/paginator} - * @private - */ -exports.paginator = require('./paginator.js'); - -/** - * @type {module:common/service} - * @private - */ -exports.Service = require('./service.js'); - -/** - * @type {module:common/serviceObject} - * @private - */ -exports.ServiceObject = require('./service-object.js'); - -/** - * @type {module:common/util} - * @private - */ -exports.util = require('./util.js'); diff --git a/functions/node_modules/@google-cloud/common/src/logger.js b/functions/node_modules/@google-cloud/common/src/logger.js deleted file mode 100644 index 3206aca5..00000000 --- a/functions/node_modules/@google-cloud/common/src/logger.js +++ /dev/null @@ -1,71 +0,0 @@ -/*! - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -/*! - * @module common/logger - */ - -const format = require('string-format-obj'); -const is = require('is'); -const logDriver = require('log-driver'); - -/** - * The default list of log levels. - * @type {string[]} - */ -const LEVELS = ['silent', 'error', 'warn', 'info', 'debug', 'silly']; - -/** - * Create a logger to print output to the console. - * - * @param {string=|object=} options - Configuration object. If a string, it is - * treated as `options.level`. - * @param {string=} options.level - The minimum log level that will print to the - * console. (Default: `error`) - * @param {Array.=} options.levels - The list of levels to use. (Default: - * logger.LEVELS) - * @param {string=} options.tag - A tag to use in log messages. - */ -function logger(options) { - if (is.string(options)) { - options = { - level: options, - }; - } - - options = options || {}; - - return logDriver({ - levels: options.levels || LEVELS, - - level: options.level || 'error', - - format: function() { - const args = [].slice.call(arguments); - - return format('{level}{tag} {message}', { - level: args.shift().toUpperCase(), - tag: options.tag ? ':' + options.tag + ':' : '', - message: args.join(' '), - }); - }, - }); -} - -module.exports = logger; -module.exports.LEVELS = LEVELS; diff --git a/functions/node_modules/@google-cloud/common/src/operation.js b/functions/node_modules/@google-cloud/common/src/operation.js deleted file mode 100644 index 978b972f..00000000 --- a/functions/node_modules/@google-cloud/common/src/operation.js +++ /dev/null @@ -1,193 +0,0 @@ -/*! - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*! - * @module common/operation - */ - -'use strict'; - -const events = require('events'); -const extend = require('extend'); -const modelo = require('modelo'); - -/** - * @type {module:common/serviceObject} - * @private - */ -const ServiceObject = require('./service-object.js'); - -// jscs:disable maximumLineLength -/** - * An Operation object allows you to interact with APIs that take longer to - * process things. - * - * @constructor - * @alias module:common/operation - * - * @param {object} config - Configuration object. - * @param {module:common/service|module:common/serviceObject|module:common/grpcService|module:common/grpcServiceObject} config.parent - The - * parent object. - * @param {string} id - The operation ID. - */ -// jscs:enable maximumLineLength -function Operation(config) { - const methods = { - /** - * Checks to see if an operation exists. - */ - exists: true, - - /** - * Retrieves the operation. - */ - get: true, - - /** - * Retrieves metadata for the operation. - */ - getMetadata: { - reqOpts: { - name: config.id, - }, - }, - }; - - config = extend( - { - baseUrl: '', - }, - config - ); - - config.methods = config.methods || methods; - - ServiceObject.call(this, config); - events.EventEmitter.call(this); - - this.completeListeners = 0; - this.hasActiveListeners = false; - - this.listenForEvents_(); -} - -modelo.inherits(Operation, ServiceObject, events.EventEmitter); - -/** - * Wraps the `complete` and `error` events in a Promise. - * - * @return {promise} - */ -Operation.prototype.promise = function() { - const self = this; - - return new self.Promise(function(resolve, reject) { - self.on('error', reject).on('complete', function(metadata) { - resolve([metadata]); - }); - }); -}; - -/** - * Begin listening for events on the operation. This method keeps track of how - * many "complete" listeners are registered and removed, making sure polling is - * handled automatically. - * - * As long as there is one active "complete" listener, the connection is open. - * When there are no more listeners, the polling stops. - * - * @private - */ -Operation.prototype.listenForEvents_ = function() { - const self = this; - - this.on('newListener', function(event) { - if (event === 'complete') { - self.completeListeners++; - - if (!self.hasActiveListeners) { - self.hasActiveListeners = true; - self.startPolling_(); - } - } - }); - - this.on('removeListener', function(event) { - if (event === 'complete' && --self.completeListeners === 0) { - self.hasActiveListeners = false; - } - }); -}; - -/** - * Poll for a status update. Execute the callback: - * - * - callback(err): Operation failed - * - callback(): Operation incomplete - * - callback(null, metadata): Operation complete - * - * @private - * - * @param {function} callback - */ -Operation.prototype.poll_ = function(callback) { - this.getMetadata(function(err, resp) { - if (err || resp.error) { - callback(err || resp.error); - return; - } - - if (!resp.done) { - callback(); - return; - } - - callback(null, resp); - }); -}; - -/** - * Poll `getMetadata` to check the operation's status. This runs a loop to ping - * the API on an interval. - * - * Note: This method is automatically called once a "complete" event handler is - * registered on the operation. - * - * @private - */ -Operation.prototype.startPolling_ = function() { - const self = this; - - if (!this.hasActiveListeners) { - return; - } - - this.poll_(function(err, metadata) { - if (err) { - self.emit('error', err); - return; - } - - if (!metadata) { - setTimeout(self.startPolling_.bind(self), 500); - return; - } - - self.emit('complete', metadata); - }); -}; - -module.exports = Operation; diff --git a/functions/node_modules/@google-cloud/common/src/paginator.js b/functions/node_modules/@google-cloud/common/src/paginator.js deleted file mode 100644 index 732e9f01..00000000 --- a/functions/node_modules/@google-cloud/common/src/paginator.js +++ /dev/null @@ -1,267 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*! - * @module common/paginator - */ - -'use strict'; - -const arrify = require('arrify'); -const concat = require('concat-stream'); -const extend = require('extend'); -const is = require('is'); -const split = require('split-array-stream'); - -/** - * @type {module:common/util} - * @private - */ -const util = require('./util.js'); - -/*! Developer Documentation - * - * paginator is used to auto-paginate `nextQuery` methods as well as - * streamifying them. - * - * Before: - * - * search.query('done=true', function(err, results, nextQuery) { - * search.query(nextQuery, function(err, results, nextQuery) {}); - * }); - * - * After: - * - * search.query('done=true', function(err, results) {}); - * - * Methods to extend should be written to accept callbacks and return a - * `nextQuery`. - */ -const paginator = {}; - -/** - * Cache the original method, then overwrite it on the Class's prototype. - * - * @param {function} Class - The parent class of the methods to extend. - * @param {string|string[]} methodNames - Name(s) of the methods to extend. - */ -paginator.extend = function(Class, methodNames) { - methodNames = arrify(methodNames); - - methodNames.forEach(function(methodName) { - const originalMethod = Class.prototype[methodName]; - - // map the original method to a private member - Class.prototype[methodName + '_'] = originalMethod; - - // overwrite the original to auto-paginate - Class.prototype[methodName] = function() { - const parsedArguments = paginator.parseArguments_(arguments); - return paginator.run_(parsedArguments, originalMethod.bind(this)); - }; - }); -}; - -/** - * Wraps paginated API calls in a readable object stream. - * - * This method simply calls the nextQuery recursively, emitting results to a - * stream. The stream ends when `nextQuery` is null. - * - * `maxResults` will act as a cap for how many results are fetched and emitted - * to the stream. - * - * @param {string} methodName - Name of the method to streamify. - * @return {function} - Wrapped function. - */ -paginator.streamify = function(methodName) { - return function() { - const parsedArguments = paginator.parseArguments_(arguments); - const originalMethod = this[methodName + '_'] || this[methodName]; - - return paginator.runAsStream_(parsedArguments, originalMethod.bind(this)); - }; -}; - -/** - * Parse a pseudo-array `arguments` for a query and callback. - * - * @param {array} args - The original `arguments` pseduo-array that the original - * method received. - */ -paginator.parseArguments_ = function(args) { - let query; - let autoPaginate = true; - let maxApiCalls = -1; - let maxResults = -1; - let callback; - - const firstArgument = args[0]; - const lastArgument = args[args.length - 1]; - - if (is.fn(firstArgument)) { - callback = firstArgument; - } else { - query = firstArgument; - } - - if (is.fn(lastArgument)) { - callback = lastArgument; - } - - if (is.object(query)) { - query = extend(true, {}, query); - - // Check if the user only asked for a certain amount of results. - if (is.number(query.maxResults)) { - // `maxResults` is used API-wide. - maxResults = query.maxResults; - } else if (is.number(query.pageSize)) { - // `pageSize` is Pub/Sub's `maxResults`. - maxResults = query.pageSize; - } - - if (is.number(query.maxApiCalls)) { - maxApiCalls = query.maxApiCalls; - delete query.maxApiCalls; - } - - if ( - callback && - (maxResults !== -1 || // The user specified a limit. - query.autoPaginate === false) - ) { - autoPaginate = false; - } - } - - const parsedArguments = { - query: query || {}, - autoPaginate: autoPaginate, - maxApiCalls: maxApiCalls, - maxResults: maxResults, - callback: callback, - }; - - parsedArguments.streamOptions = extend(true, {}, parsedArguments.query); - delete parsedArguments.streamOptions.autoPaginate; - delete parsedArguments.streamOptions.maxResults; - delete parsedArguments.streamOptions.pageSize; - - return parsedArguments; -}; - -/** - * This simply checks to see if `autoPaginate` is set or not, if it's true - * then we buffer all results, otherwise simply call the original method. - * - * @param {array} parsedArguments - Parsed arguments from the original method - * call. - * @param {object=|string=} parsedArguments.query - Query object. This is most - * commonly an object, but to make the API more simple, it can also be a - * string in some places. - * @param {function=} parsedArguments.callback - Callback function. - * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. - * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. - * @param {number} parsedArguments.maxResults - Maximum results to return. - * @param {function} originalMethod - The cached method that accepts a callback - * and returns `nextQuery` to receive more results. - */ -paginator.run_ = function(parsedArguments, originalMethod) { - const query = parsedArguments.query; - const callback = parsedArguments.callback; - const autoPaginate = parsedArguments.autoPaginate; - - if (autoPaginate) { - this.runAsStream_(parsedArguments, originalMethod) - .on('error', callback) - .pipe( - concat(function(results) { - callback(null, results); - }) - ); - } else { - originalMethod(query, callback); - } -}; - -/** - * This method simply calls the nextQuery recursively, emitting results to a - * stream. The stream ends when `nextQuery` is null. - * - * `maxResults` will act as a cap for how many results are fetched and emitted - * to the stream. - * - * @param {object=|string=} parsedArguments.query - Query object. This is most - * commonly an object, but to make the API more simple, it can also be a - * string in some places. - * @param {function=} parsedArguments.callback - Callback function. - * @param {boolean} parsedArguments.autoPaginate - Auto-pagination enabled. - * @param {boolean} parsedArguments.maxApiCalls - Maximum API calls to make. - * @param {number} parsedArguments.maxResults - Maximum results to return. - * @param {function} originalMethod - The cached method that accepts a callback - * and returns `nextQuery` to receive more results. - * @return {stream} - Readable object stream. - */ -paginator.runAsStream_ = function(parsedArguments, originalMethod) { - let query = parsedArguments.query; - let resultsToSend = parsedArguments.maxResults; - - const limiter = util.createLimiter(makeRequest, { - maxApiCalls: parsedArguments.maxApiCalls, - streamOptions: parsedArguments.streamOptions, - }); - - const stream = limiter.stream; - - stream.once('reading', function() { - makeRequest(query); - }); - - function makeRequest(query) { - originalMethod(query, onResultSet); - } - - function onResultSet(err, results, nextQuery) { - if (err) { - stream.destroy(err); - return; - } - - if (resultsToSend >= 0 && results.length > resultsToSend) { - results = results.splice(0, resultsToSend); - } - - resultsToSend -= results.length; - - split(results, stream, function(streamEnded) { - if (streamEnded) { - return; - } - - if (nextQuery && resultsToSend !== 0) { - limiter.makeRequest(nextQuery); - return; - } - - stream.push(null); - }); - } - - return limiter.stream; -}; - -module.exports = paginator; diff --git a/functions/node_modules/@google-cloud/common/src/service-object.js b/functions/node_modules/@google-cloud/common/src/service-object.js deleted file mode 100644 index 0fe9b1c9..00000000 --- a/functions/node_modules/@google-cloud/common/src/service-object.js +++ /dev/null @@ -1,392 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*! - * @module common/service-object - */ - -'use strict'; - -const arrify = require('arrify'); -const exec = require('methmeth'); -const extend = require('extend'); -const is = require('is'); - -/** - * @type {module:common/util} - * @private - */ -const util = require('./util.js'); - -/** - * ServiceObject is a base class, meant to be inherited from by a "service - * object," like a BigQuery dataset or Storage bucket. - * - * Most of the time, these objects share common functionality; they can be - * created or deleted, and you can get or set their metadata. - * - * By inheriting from this class, a service object will be extended with these - * shared behaviors. Note that any method can be overridden when the service - * object requires specific behavior. - * - * @constructor - * @alias module:common/service-object - * - * @private - * - * @param {object} config - Configuration object. - * @param {string} config.baseUrl - The base URL to make API requests to. - * @param {string} config.createMethod - The method which creates this object. - * @param {string=} config.id - The identifier of the object. For example, the - * name of a Storage bucket or Pub/Sub topic. - * @param {object=} config.methods - A map of each method name that should be - * inherited. - * @param {object} config.methods[].reqOpts - Default request options for this - * particular method. A common use case is when `setMetadata` requires a - * `PUT` method to override the default `PATCH`. - * @param {object} config.parent - The parent service instance. For example, an - * instance of Storage if the object is Bucket. - */ -function ServiceObject(config) { - const self = this; - - util.privatize(this, 'metadata', {}); - - util.privatize(this, 'baseUrl', config.baseUrl); - util.privatize(this, 'parent', config.parent); // Parent class. - util.privatize(this, 'id', config.id); // Name or ID (e.g. dataset ID, bucket name, etc.) - util.privatize(this, 'createMethod', config.createMethod); - util.privatize(this, 'methods', config.methods || {}); - util.privatize(this, 'interceptors', []); - util.privatize(this, 'Promise', this.parent.Promise); - - if (config.methods) { - const allMethodNames = Object.keys(ServiceObject.prototype); - allMethodNames - .filter(function(methodName) { - return ( - // All ServiceObjects need `request`. - !/^request/.test(methodName) && - // The ServiceObject didn't redefine the method. - self[methodName] === ServiceObject.prototype[methodName] && - // This method isn't wanted. - !config.methods[methodName] - ); - }) - .forEach(function(methodName) { - self[methodName] = undefined; - }); - } -} - -/** - * Create the object. - * - * @param {object=} options - Configuration object. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {object} callback.instance - The instance. - * @param {object} callback.apiResponse - The full API response. - */ -ServiceObject.prototype.create = function(options, callback) { - const self = this; - const args = [this.id]; - - if (is.fn(options)) { - callback = options; - } - - if (is.object(options)) { - args.push(options); - } - - // Wrap the callback to return *this* instance of the object, not the newly- - // created one. - function onCreate(err, instance) { - const args = [].slice.call(arguments); - - if (!err) { - self.metadata = instance.metadata; - args[1] = self; // replace the created `instance` with this one. - } - - callback.apply(null, args); - } - - args.push(onCreate); - - this.createMethod.apply(null, args); -}; - -/** - * Delete the object. - * - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {object} callback.apiResponse - The full API response. - */ -ServiceObject.prototype.delete = function(callback) { - const methodConfig = this.methods.delete || {}; - callback = callback || util.noop; - - const reqOpts = extend( - { - method: 'DELETE', - uri: '', - }, - methodConfig.reqOpts - ); - - // The `request` method may have been overridden to hold any special behavior. - // Ensure we call the original `request` method. - ServiceObject.prototype.request.call(this, reqOpts, function(err, resp) { - callback(err, resp); - }); -}; - -/** - * Check if the object exists. - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {boolean} callback.exists - Whether the object exists or not. - */ -ServiceObject.prototype.exists = function(callback) { - this.get(function(err) { - if (err) { - if (err.code === 404) { - callback(null, false); - } else { - callback(err); - } - - return; - } - - callback(null, true); - }); -}; - -/** - * Get the object if it exists. Optionally have the object created if an options - * object is provided with `autoCreate: true`. - * - * @param {object=} config - The configuration object that will be used to - * create the object if necessary. - * @param {boolean} config.autoCreate - Create the object if it doesn't already - * exist. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {object} callback.instance - The instance. - * @param {object} callback.apiResponse - The full API response. - */ -ServiceObject.prototype.get = function(config, callback) { - const self = this; - - if (is.fn(config)) { - callback = config; - config = {}; - } - - config = config || {}; - - const autoCreate = config.autoCreate && is.fn(this.create); - delete config.autoCreate; - - function onCreate(err, instance, apiResponse) { - if (err) { - if (err.code === 409) { - self.get(config, callback); - return; - } - - callback(err, null, apiResponse); - return; - } - - callback(null, instance, apiResponse); - } - - this.getMetadata(function(err, metadata) { - if (err) { - if (err.code === 404 && autoCreate) { - const args = []; - - if (!is.empty(config)) { - args.push(config); - } - - args.push(onCreate); - - self.create.apply(self, args); - return; - } - - callback(err, null, metadata); - return; - } - - callback(null, self, metadata); - }); -}; - -/** - * Get the metadata of this object. - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {object} callback.metadata - The metadata for this object. - * @param {object} callback.apiResponse - The full API response. - */ -ServiceObject.prototype.getMetadata = function(callback) { - const self = this; - - const methodConfig = this.methods.getMetadata || {}; - - const reqOpts = extend( - { - uri: '', - }, - methodConfig.reqOpts - ); - - // The `request` method may have been overridden to hold any special behavior. - // Ensure we call the original `request` method. - ServiceObject.prototype.request.call(this, reqOpts, function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - self.metadata = resp; - - callback(null, self.metadata, resp); - }); -}; - -/** - * Set the metadata for this object. - * - * @param {object} metadata - The metadata to set on this object. - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {object} callback.instance - The instance. - * @param {object} callback.apiResponse - The full API response. - */ -ServiceObject.prototype.setMetadata = function(metadata, callback) { - const self = this; - - callback = callback || util.noop; - - const methodConfig = this.methods.setMetadata || {}; - - const reqOpts = extend( - true, - { - method: 'PATCH', - uri: '', - json: metadata, - }, - methodConfig.reqOpts - ); - - // The `request` method may have been overridden to hold any special behavior. - // Ensure we call the original `request` method. - ServiceObject.prototype.request.call(this, reqOpts, function(err, resp) { - if (err) { - callback(err, resp); - return; - } - - self.metadata = resp; - - callback(null, resp); - }); -}; - -/** - * Make an authenticated API request. - * - * @private - * - * @param {object} reqOpts - Request options that are passed to `request`. - * @param {string} reqOpts.uri - A URI relative to the baseUrl. - * @param {function} callback - The callback function passed to `request`. - */ -ServiceObject.prototype.request_ = function(reqOpts, callback) { - reqOpts = extend(true, {}, reqOpts); - - const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; - - const uriComponents = [this.baseUrl, this.id || '', reqOpts.uri]; - - if (isAbsoluteUrl) { - uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); - } - - reqOpts.uri = uriComponents - .filter(exec('trim')) // Limit to non-empty strings. - .map(function(uriComponent) { - const trimSlashesRegex = /^\/*|\/*$/g; - return uriComponent.replace(trimSlashesRegex, ''); - }) - .join('/'); - - const childInterceptors = arrify(reqOpts.interceptors_); - const localInterceptors = [].slice.call(this.interceptors); - - reqOpts.interceptors_ = childInterceptors.concat(localInterceptors); - - if (!callback) { - return this.parent.requestStream(reqOpts); - } - - this.parent.request(reqOpts, callback); -}; - -/** - * Make an authenticated API request. - * - * @private - * - * @param {object} reqOpts - Request options that are passed to `request`. - * @param {string} reqOpts.uri - A URI relative to the baseUrl. - * @param {function} callback - The callback function passed to `request`. - */ -ServiceObject.prototype.request = function(reqOpts, callback) { - ServiceObject.prototype.request_.call(this, reqOpts, callback); -}; - -/** - * Make an authenticated API request. - * - * @private - * - * @param {object} reqOpts - Request options that are passed to `request`. - * @param {string} reqOpts.uri - A URI relative to the baseUrl. - */ -ServiceObject.prototype.requestStream = function(reqOpts) { - return ServiceObject.prototype.request_.call(this, reqOpts); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -util.promisifyAll(ServiceObject); - -module.exports = ServiceObject; diff --git a/functions/node_modules/@google-cloud/common/src/service.js b/functions/node_modules/@google-cloud/common/src/service.js deleted file mode 100644 index c6f3348c..00000000 --- a/functions/node_modules/@google-cloud/common/src/service.js +++ /dev/null @@ -1,200 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*! - * @module common/service - */ - -'use strict'; - -const arrify = require('arrify'); -const extend = require('extend'); - -/** - * @type {module:common/util} - * @private - */ -const util = require('./util.js'); - -const PROJECT_ID_TOKEN = '{{projectId}}'; - -/** - * Service is a base class, meant to be inherited from by a "service," like - * BigQuery or Storage. - * - * This handles making authenticated requests by exposing a `makeReq_` function. - * - * @constructor - * @alias module:common/service - * - * @param {object} config - Configuration object. - * @param {string} config.baseUrl - The base URL to make API requests to. - * @param {string[]} config.scopes - The scopes required for the request. - * @param {object=} options - [Configuration object](#/docs). - */ -function Service(config, options) { - options = options || {}; - - util.privatize(this, 'baseUrl', config.baseUrl); - util.privatize(this, 'globalInterceptors', arrify(options.interceptors_)); - util.privatize(this, 'interceptors', []); - util.privatize(this, 'packageJson', config.packageJson); - util.privatize(this, 'projectId', options.projectId || PROJECT_ID_TOKEN); - util.privatize(this, 'projectIdRequired', config.projectIdRequired !== false); - util.privatize(this, 'Promise', options.promise || Promise); - - const reqCfg = extend({}, config, { - projectIdRequired: this.projectIdRequired, - projectId: this.projectId, - credentials: options.credentials, - keyFile: options.keyFilename, - email: options.email, - token: options.token, - }); - - util.privatize( - this, - 'makeAuthenticatedRequest', - util.makeAuthenticatedRequestFactory(reqCfg) - ); - util.privatize(this, 'authClient', this.makeAuthenticatedRequest.authClient); - util.privatize( - this, - 'getCredentials', - this.makeAuthenticatedRequest.getCredentials - ); - - const isCloudFunctionEnv = !!process.env.FUNCTION_NAME; - - if (isCloudFunctionEnv) { - this.interceptors.push({ - request: function(reqOpts) { - reqOpts.forever = false; - return reqOpts; - }, - }); - } -} - -/** - * Get and update the Service's project ID. - * - * @param {function} callback - The callback function. - */ -Service.prototype.getProjectId = function(callback) { - const self = this; - - this.authClient.getProjectId(function(err, projectId) { - if (err) { - callback(err); - return; - } - - if (self.projectId === PROJECT_ID_TOKEN && projectId) { - self.projectId = projectId; - } - - callback(null, self.projectId); - }); -}; - -/** - * Make an authenticated API request. - * - * @private - * - * @param {object} reqOpts - Request options that are passed to `request`. - * @param {string} reqOpts.uri - A URI relative to the baseUrl. - * @param {function} callback - The callback function passed to `request`. - */ -Service.prototype.request_ = function(reqOpts, callback) { - reqOpts = extend(true, {}, reqOpts); - - const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; - - const uriComponents = [this.baseUrl]; - - if (this.projectIdRequired) { - uriComponents.push('projects'); - uriComponents.push(this.projectId); - } - - uriComponents.push(reqOpts.uri); - - if (isAbsoluteUrl) { - uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); - } - - reqOpts.uri = uriComponents - .map(function(uriComponent) { - const trimSlashesRegex = /^\/*|\/*$/g; - return uriComponent.replace(trimSlashesRegex, ''); - }) - .join('/') - // Some URIs have colon separators. - // Bad: https://.../projects/:list - // Good: https://.../projects:list - .replace(/\/:/g, ':'); - - // Interceptors should be called in the order they were assigned. - const combinedInterceptors = [].slice - .call(this.globalInterceptors) - .concat(this.interceptors) - .concat(arrify(reqOpts.interceptors_)); - - let interceptor; - - while ((interceptor = combinedInterceptors.shift()) && interceptor.request) { - reqOpts = interceptor.request(reqOpts); - } - - delete reqOpts.interceptors_; - - const pkg = this.packageJson; - reqOpts.headers = extend({}, reqOpts.headers, { - 'User-Agent': util.getUserAgentFromPackageJson(pkg), - 'x-goog-api-client': `gl-node/${process.versions.node} gccl/${pkg.version}`, - }); - - return this.makeAuthenticatedRequest(reqOpts, callback); -}; - -/** - * Make an authenticated API request. - * - * @private - * - * @param {object} reqOpts - Request options that are passed to `request`. - * @param {string} reqOpts.uri - A URI relative to the baseUrl. - * @param {function} callback - The callback function passed to `request`. - */ -Service.prototype.request = function(reqOpts, callback) { - Service.prototype.request_.call(this, reqOpts, callback); -}; - -/** - * Make an authenticated API request. - * - * @private - * - * @param {object} reqOpts - Request options that are passed to `request`. - * @param {string} reqOpts.uri - A URI relative to the baseUrl. - */ -Service.prototype.requestStream = function(reqOpts) { - return Service.prototype.request_.call(this, reqOpts); -}; - -module.exports = Service; diff --git a/functions/node_modules/@google-cloud/common/src/util.js b/functions/node_modules/@google-cloud/common/src/util.js deleted file mode 100644 index 7178f528..00000000 --- a/functions/node_modules/@google-cloud/common/src/util.js +++ /dev/null @@ -1,830 +0,0 @@ -/** - * Copyright 2014 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*! - * @module common/util - */ - -'use strict'; - -const createErrorClass = require('create-error-class'); -const duplexify = require('duplexify'); -const ent = require('ent'); -const extend = require('extend'); -const googleAuth = require('google-auto-auth'); -const is = require('is'); -const request = require('request').defaults({ - timeout: 60000, - gzip: true, - forever: true, - pool: { - maxSockets: Infinity, - }, -}); -const retryRequest = require('retry-request'); -const streamEvents = require('stream-events'); -const through = require('through2'); -const uniq = require('array-uniq'); - -const util = module.exports; - -/** - * Custom error type for missing project ID errors. - */ -util.MissingProjectIdError = createErrorClass( - 'MissingProjectIdError', - function() { - this.message = `Sorry, we cannot connect to Cloud Services without a project - ID. You may specify one with an environment variable named - "GOOGLE_CLOUD_PROJECT".`.replace(/ +/g, ' '); - } -); - -/** - * No op. - * - * @example - * function doSomething(callback) { - * callback = callback || noop; - * } - */ -function noop() {} - -util.noop = noop; - -/** - * Custom error type for API errors. - * - * @param {object} errorBody - Error object. - */ -util.ApiError = createErrorClass('ApiError', function(errorBody) { - this.code = errorBody.code; - this.errors = errorBody.errors; - this.response = errorBody.response; - - try { - this.errors = JSON.parse(this.response.body).error.errors; - } catch (e) { - this.errors = errorBody.errors; - } - - const messages = []; - - if (errorBody.message) { - messages.push(errorBody.message); - } - - if (this.errors && this.errors.length === 1) { - messages.push(this.errors[0].message); - } else if (this.response && this.response.body) { - messages.push(ent.decode(errorBody.response.body.toString())); - } else if (!errorBody.message) { - messages.push('Error during request.'); - } - - this.message = uniq(messages).join(' - '); -}); - -/** - * Custom error type for partial errors returned from the API. - * - * @param {object} b - Error object. - */ -util.PartialFailureError = createErrorClass('PartialFailureError', function(b) { - const errorObject = b; - - this.errors = errorObject.errors; - this.response = errorObject.response; - - const defaultErrorMessage = 'A failure occurred during this request.'; - this.message = errorObject.message || defaultErrorMessage; -}); - -/** - * Uniformly process an API response. - * - * @param {*} err - Error value. - * @param {*} resp - Response value. - * @param {*} body - Body value. - * @param {function} callback - The callback function. - */ -function handleResp(err, resp, body, callback) { - callback = callback || util.noop; - - const parsedResp = extend( - true, - {err: err || null}, - resp && util.parseHttpRespMessage(resp), - body && util.parseHttpRespBody(body) - ); - - callback(parsedResp.err, parsedResp.body, parsedResp.resp); -} - -util.handleResp = handleResp; - -/** - * Sniff an incoming HTTP response message for errors. - * - * @param {object} httpRespMessage - An incoming HTTP response message from - * `request`. - * @return {object} parsedHttpRespMessage - The parsed response. - * @param {?error} parsedHttpRespMessage.err - An error detected. - * @param {object} parsedHttpRespMessage.resp - The original response object. - */ -function parseHttpRespMessage(httpRespMessage) { - const parsedHttpRespMessage = { - resp: httpRespMessage, - }; - - if (httpRespMessage.statusCode < 200 || httpRespMessage.statusCode > 299) { - // Unknown error. Format according to ApiError standard. - parsedHttpRespMessage.err = new util.ApiError({ - errors: [], - code: httpRespMessage.statusCode, - message: httpRespMessage.statusMessage, - response: httpRespMessage, - }); - } - - return parsedHttpRespMessage; -} - -util.parseHttpRespMessage = parseHttpRespMessage; - -/** - * Parse the response body from an HTTP request. - * - * @param {object} body - The response body. - * @return {object} parsedHttpRespMessage - The parsed response. - * @param {?error} parsedHttpRespMessage.err - An error detected. - * @param {object} parsedHttpRespMessage.body - The original body value provided - * will try to be JSON.parse'd. If it's successful, the parsed value will be - * returned here, otherwise the original value. - */ -function parseHttpRespBody(body) { - const parsedHttpRespBody = { - body: body, - }; - - if (is.string(body)) { - try { - parsedHttpRespBody.body = JSON.parse(body); - } catch (err) { - parsedHttpRespBody.err = new util.ApiError('Cannot parse JSON response'); - } - } - - if (parsedHttpRespBody.body && parsedHttpRespBody.body.error) { - // Error from JSON API. - parsedHttpRespBody.err = new util.ApiError(parsedHttpRespBody.body.error); - } - - return parsedHttpRespBody; -} - -util.parseHttpRespBody = parseHttpRespBody; - -/** - * Take a Duplexify stream, fetch an authenticated connection header, and create - * an outgoing writable stream. - * - * @param {Duplexify} dup - Duplexify stream. - * @param {object} options - Configuration object. - * @param {module:common/connection} options.connection - A connection instance, - * used to get a token with and send the request through. - * @param {object} options.metadata - Metadata to send at the head of the - * request. - * @param {object} options.request - Request object, in the format of a standard - * Node.js http.request() object. - * @param {string=} options.request.method - Default: "POST". - * @param {string=} options.request.qs.uploadType - Default: "multipart". - * @param {string=} options.streamContentType - Default: - * "application/octet-stream". - * @param {function} onComplete - Callback, executed after the writable Request - * stream has completed. - */ -function makeWritableStream(dup, options, onComplete) { - onComplete = onComplete || util.noop; - - const writeStream = through(); - dup.setWritable(writeStream); - - const defaultReqOpts = { - method: 'POST', - qs: { - uploadType: 'multipart', - }, - }; - - const metadata = options.metadata || {}; - - const reqOpts = extend(true, defaultReqOpts, options.request, { - multipart: [ - { - 'Content-Type': 'application/json', - body: JSON.stringify(metadata), - }, - { - 'Content-Type': metadata.contentType || 'application/octet-stream', - body: writeStream, - }, - ], - }); - - options.makeAuthenticatedRequest(reqOpts, { - onAuthenticated: function(err, authenticatedReqOpts) { - if (err) { - dup.destroy(err); - return; - } - - request(authenticatedReqOpts, function(err, resp, body) { - util.handleResp(err, resp, body, function(err, data) { - if (err) { - dup.destroy(err); - return; - } - - dup.emit('response', resp); - onComplete(data); - }); - }); - }, - }); -} - -util.makeWritableStream = makeWritableStream; - -/** - * Returns true if the API request should be retried, given the error that was - * given the first time the request was attempted. This is used for rate limit - * related errors as well as intermittent server errors. - * - * @param {error} err - The API error to check if it is appropriate to retry. - * @return {boolean} True if the API request should be retried, false otherwise. - */ -function shouldRetryRequest(err) { - if (err) { - if ([429, 500, 502, 503].indexOf(err.code) !== -1) { - return true; - } - - if (err.errors) { - for (const i in err.errors) { - const reason = err.errors[i].reason; - if (reason === 'rateLimitExceeded') { - return true; - } - if (reason === 'userRateLimitExceeded') { - return true; - } - } - } - } - - return false; -} - -util.shouldRetryRequest = shouldRetryRequest; - -/** - * Get a function for making authenticated requests. - * - * @throws {Error} If a projectId is requested, but not able to be detected. - * - * @param {object} config - Configuration object. - * @param {boolean=} config.autoRetry - Automatically retry requests if the - * response is related to rate limits or certain intermittent server errors. - * We will exponentially backoff subsequent requests by default. (default: - * true) - * @param {object=} config.credentials - Credentials object. - * @param {boolean=} config.customEndpoint - If true, just return the provided - * request options. Default: false. - * @param {string=} config.email - Account email address, required for PEM/P12 - * usage. - * @param {number=} config.maxRetries - Maximum number of automatic retries - * attempted before returning the error. (default: 3) - * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile. - * @param {array} config.scopes - Array of scopes required for the API. - */ -function makeAuthenticatedRequestFactory(config) { - config = config || {}; - - const googleAutoAuthConfig = extend({}, config); - - if (googleAutoAuthConfig.projectId === '{{projectId}}') { - delete googleAutoAuthConfig.projectId; - } - - const authClient = googleAuth(googleAutoAuthConfig); - - /** - * The returned function that will make an authenticated request. - * - * @param {type} reqOpts - Request options in the format `request` expects. - * @param {object|function} options - Configuration object or callback - * function. - * @param {function=} options.onAuthenticated - If provided, a request will - * not be made. Instead, this function is passed the error & authenticated - * request options. - */ - function makeAuthenticatedRequest(reqOpts, options) { - let stream; - const reqConfig = extend({}, config); - let activeRequest_; - - if (!options) { - stream = duplexify(); - reqConfig.stream = stream; - } - - function onAuthenticated(err, authenticatedReqOpts) { - const autoAuthFailed = - err && - err.message.indexOf('Could not load the default credentials') > -1; - - if (autoAuthFailed) { - // Even though authentication failed, the API might not actually care. - authenticatedReqOpts = reqOpts; - } - - if (!err || autoAuthFailed) { - let projectId = authClient.projectId; - - if (config.projectId && config.projectId !== '{{projectId}}') { - projectId = config.projectId; - } - - try { - authenticatedReqOpts = util.decorateRequest( - authenticatedReqOpts, - projectId - ); - err = null; - } catch (e) { - // A projectId was required, but we don't have one. - // Re-use the "Could not load the default credentials error" if auto - // auth failed. - err = err || e; - } - } - - if (err) { - if (stream) { - stream.destroy(err); - } else { - (options.onAuthenticated || options)(err); - } - - return; - } - - if (options && options.onAuthenticated) { - options.onAuthenticated(null, authenticatedReqOpts); - } else { - activeRequest_ = util.makeRequest( - authenticatedReqOpts, - reqConfig, - options - ); - } - } - - if (reqConfig.customEndpoint) { - // Using a custom API override. Do not use `google-auto-auth` for - // authentication. (ex: connecting to a local Datastore server) - onAuthenticated(null, reqOpts); - } else { - authClient.authorizeRequest(reqOpts, onAuthenticated); - } - - if (stream) { - return stream; - } - - return { - abort: function() { - if (activeRequest_) { - activeRequest_.abort(); - activeRequest_ = null; - } - }, - }; - } - - makeAuthenticatedRequest.getCredentials = authClient.getCredentials.bind( - authClient - ); - - makeAuthenticatedRequest.authClient = authClient; - - return makeAuthenticatedRequest; -} - -util.makeAuthenticatedRequestFactory = makeAuthenticatedRequestFactory; - -/** - * Make a request through the `retryRequest` module with built-in error handling - * and exponential back off. - * - * @param {object} reqOpts - Request options in the format `request` expects. - * @param {object=} config - Configuration object. - * @param {boolean=} config.autoRetry - Automatically retry requests if the - * response is related to rate limits or certain intermittent server errors. - * We will exponentially backoff subsequent requests by default. (default: - * true) - * @param {number=} config.maxRetries - Maximum number of automatic retries - * attempted before returning the error. (default: 3) - * @param {function} callback - The callback function. - */ -function makeRequest(reqOpts, config, callback) { - if (is.fn(config)) { - callback = config; - config = {}; - } - - config = config || {}; - - const options = { - request: request, - - retries: config.autoRetry !== false ? config.maxRetries || 3 : 0, - - shouldRetryFn: function(httpRespMessage) { - const err = util.parseHttpRespMessage(httpRespMessage).err; - return err && util.shouldRetryRequest(err); - }, - }; - - if (config.stream) { - const dup = config.stream; - let requestStream; - const isGetRequest = (reqOpts.method || 'GET').toUpperCase() === 'GET'; - - if (isGetRequest) { - requestStream = retryRequest(reqOpts, options); - dup.setReadable(requestStream); - } else { - // Streaming writable HTTP requests cannot be retried. - requestStream = request(reqOpts); - dup.setWritable(requestStream); - } - - // Replay the Request events back to the stream. - requestStream - .on('error', dup.destroy.bind(dup)) - .on('response', dup.emit.bind(dup, 'response')) - .on('complete', dup.emit.bind(dup, 'complete')); - - dup.abort = requestStream.abort; - } else { - return retryRequest(reqOpts, options, function(err, response, body) { - util.handleResp(err, response, body, callback); - }); - } -} - -util.makeRequest = makeRequest; - -/** - * Decorate the options about to be made in a request. - * - * @param {object} reqOpts - The options to be passed to `request`. - * @param {string} projectId - The project ID. - * @return {object} reqOpts - The decorated reqOpts. - */ -function decorateRequest(reqOpts, projectId) { - delete reqOpts.autoPaginate; - delete reqOpts.autoPaginateVal; - delete reqOpts.objectMode; - - if (is.object(reqOpts.qs)) { - delete reqOpts.qs.autoPaginate; - delete reqOpts.qs.autoPaginateVal; - reqOpts.qs = util.replaceProjectIdToken(reqOpts.qs, projectId); - } - - if (is.object(reqOpts.json)) { - delete reqOpts.json.autoPaginate; - delete reqOpts.json.autoPaginateVal; - reqOpts.json = util.replaceProjectIdToken(reqOpts.json, projectId); - } - - reqOpts.uri = util.replaceProjectIdToken(reqOpts.uri, projectId); - - return reqOpts; -} - -util.decorateRequest = decorateRequest; - -/** - * Populate the `{{projectId}}` placeholder. - * - * @throws {Error} If a projectId is required, but one is not provided. - * - * @param {*} - Any input value that may contain a placeholder. Arrays and - * objects will be looped. - * @param {string} projectId - A projectId. If not provided - * @return {*} - The original argument with all placeholders populated. - */ -function replaceProjectIdToken(value, projectId) { - if (is.array(value)) { - value = value.map(function(val) { - return replaceProjectIdToken(val, projectId); - }); - } - - if (is.object(value) && is.fn(value.hasOwnProperty)) { - for (const opt in value) { - if (value.hasOwnProperty(opt)) { - value[opt] = replaceProjectIdToken(value[opt], projectId); - } - } - } - - if (is.string(value) && value.indexOf('{{projectId}}') > -1) { - if (!projectId || projectId === '{{projectId}}') { - throw new util.MissingProjectIdError(); - } - value = value.replace(/{{projectId}}/g, projectId); - } - - return value; -} - -util.replaceProjectIdToken = replaceProjectIdToken; - -/** - * Extend a global configuration object with user options provided at the time - * of sub-module instantiation. - * - * Connection details currently come in two ways: `credentials` or - * `keyFilename`. Because of this, we have a special exception when overriding a - * global configuration object. If a user provides either to the global - * configuration, then provides another at submodule instantiation-time, the - * latter is preferred. - * - * @param {object} globalConfig - The global configuration object. - * @param {object=} overrides - The instantiation-time configuration object. - * @return {object} - */ -function extendGlobalConfig(globalConfig, overrides) { - globalConfig = globalConfig || {}; - overrides = overrides || {}; - - const defaultConfig = {}; - - if (process.env.GCLOUD_PROJECT) { - defaultConfig.projectId = process.env.GCLOUD_PROJECT; - } - - const options = extend({}, globalConfig); - - const hasGlobalConnection = options.credentials || options.keyFilename; - const isOverridingConnection = overrides.credentials || overrides.keyFilename; - - if (hasGlobalConnection && isOverridingConnection) { - delete options.credentials; - delete options.keyFilename; - } - - const extendedConfig = extend(true, defaultConfig, options, overrides); - - // Preserve the original (not cloned) interceptors. - extendedConfig.interceptors_ = globalConfig.interceptors_; - - return extendedConfig; -} - -util.extendGlobalConfig = extendGlobalConfig; - -/** - * Merge and validate API configurations. - * - * @param {object} globalContext - gcloud-level context. - * @param {object} globalContext.config_ - gcloud-level configuration. - * @param {object} localConfig - Service-level configurations. - * @return {object} config - Merged and validated configuration. - */ -function normalizeArguments(globalContext, localConfig) { - const globalConfig = globalContext && globalContext.config_; - - return util.extendGlobalConfig(globalConfig, localConfig); -} - -util.normalizeArguments = normalizeArguments; - -/** - * Limit requests according to a `maxApiCalls` limit. - * - * @param {function} makeRequestFn - The function that will be called. - * @param {object=} options - Configuration object. - * @param {number} options.maxApiCalls - The maximum number of API calls to - * make. - * @param {object} options.streamOptions - Options to pass to the Stream - * constructor. - */ -function createLimiter(makeRequestFn, options) { - options = options || {}; - - const stream = streamEvents(through.obj(options.streamOptions)); - - let requestsMade = 0; - let requestsToMake = -1; - - if (is.number(options.maxApiCalls)) { - requestsToMake = options.maxApiCalls; - } - - return { - makeRequest: function() { - requestsMade++; - - if (requestsToMake >= 0 && requestsMade > requestsToMake) { - stream.push(null); - return; - } - - makeRequestFn.apply(null, arguments); - - return stream; - }, - - stream: stream, - }; -} - -util.createLimiter = createLimiter; - -function isCustomType(unknown, module) { - function getConstructorName(obj) { - return obj.constructor && obj.constructor.name.toLowerCase(); - } - - const moduleNameParts = module.split('/'); - - const parentModuleName = - moduleNameParts[0] && moduleNameParts[0].toLowerCase(); - const subModuleName = moduleNameParts[1] && moduleNameParts[1].toLowerCase(); - - if (subModuleName && getConstructorName(unknown) !== subModuleName) { - return false; - } - - let walkingModule = unknown; - do { - if (getConstructorName(walkingModule) === parentModuleName) { - return true; - } - } while ((walkingModule = walkingModule.parent)); - - return false; -} - -util.isCustomType = isCustomType; - -/** - * Create a properly-formatted User-Agent string from a package.json file. - * - * @param {object} packageJson - A module's package.json file. - * @return {string} userAgent - The formatted User-Agent string. - */ -function getUserAgentFromPackageJson(packageJson) { - const hyphenatedPackageName = packageJson.name - .replace('@google-cloud', 'gcloud-node') // For legacy purposes. - .replace('/', '-'); // For UA spec-compliance purposes. - - return hyphenatedPackageName + '/' + packageJson.version; -} - -util.getUserAgentFromPackageJson = getUserAgentFromPackageJson; - -/** - * Wraps a callback style function to conditionally return a promise. - * - * @param {function} originalMethod - The method to promisify. - * @param {object=} options - Promise options. - * @param {boolean} options.singular - Resolve the promise with single arg - * instead of an array. - * @return {function} wrapped - */ -function promisify(originalMethod, options) { - if (originalMethod.promisified_) { - return originalMethod; - } - - options = options || {}; - - const slice = Array.prototype.slice; - - const wrapper = function() { - const context = this; - let last; - - for (last = arguments.length - 1; last >= 0; last--) { - const arg = arguments[last]; - - if (is.undefined(arg)) { - continue; // skip trailing undefined. - } - - if (!is.fn(arg)) { - break; // non-callback last argument found. - } - - return originalMethod.apply(context, arguments); - } - - // peel trailing undefined. - const args = slice.call(arguments, 0, last + 1); - - let PromiseCtor = Promise; - - // Because dedupe will likely create a single install of - // @google-cloud/common to be shared amongst all modules, we need to - // localize it at the Service level. - if (context && context.Promise) { - PromiseCtor = context.Promise; - } - - return new PromiseCtor(function(resolve, reject) { - args.push(function() { - const callbackArgs = slice.call(arguments); - const err = callbackArgs.shift(); - - if (err) { - return reject(err); - } - - if (options.singular && callbackArgs.length === 1) { - resolve(callbackArgs[0]); - } else { - resolve(callbackArgs); - } - }); - - originalMethod.apply(context, args); - }); - }; - - wrapper.promisified_ = true; - return wrapper; -} - -util.promisify = promisify; - -/** - * Promisifies certain Class methods. This will not promisify private or - * streaming methods. - * - * @param {module:common/service} Class - Service class. - * @param {object=} options - Configuration object. - */ -function promisifyAll(Class, options) { - const exclude = (options && options.exclude) || []; - - const methods = Object.keys(Class.prototype).filter(function(methodName) { - return ( - is.fn(Class.prototype[methodName]) && // is it a function? - !/(^_|(Stream|_)|promise$)/.test(methodName) && // is it promisable? - exclude.indexOf(methodName) === -1 - ); // is it blacklisted? - }); - - methods.forEach(function(methodName) { - const originalMethod = Class.prototype[methodName]; - - if (!originalMethod.promisified_) { - Class.prototype[methodName] = util.promisify(originalMethod, options); - } - }); -} - -util.promisifyAll = promisifyAll; - -/** - * This will mask properties of an object from console.log. - * - * @param {object} object - The object to assign the property to. - * @param {string} propName - Property name. - * @param {*} value - Value. - */ -function privatize(object, propName, value) { - Object.defineProperty(object, propName, {value, writable: true}); -} - -util.privatize = privatize; diff --git a/functions/node_modules/@google-cloud/firestore/LICENSE b/functions/node_modules/@google-cloud/firestore/LICENSE deleted file mode 100644 index 7a4a3ea2..00000000 --- a/functions/node_modules/@google-cloud/firestore/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/functions/node_modules/@google-cloud/firestore/README.md b/functions/node_modules/@google-cloud/firestore/README.md deleted file mode 100644 index 94dc0250..00000000 --- a/functions/node_modules/@google-cloud/firestore/README.md +++ /dev/null @@ -1,141 +0,0 @@ -Google Cloud Platform logo - -# [Google Cloud Firestore: Node.js Server SDK](https://github.com/googleapis/nodejs-firestore) - -[![release level](https://img.shields.io/badge/release%20level-beta-yellow.svg?style=flat)](https://cloud.google.com/terms/launch-stages) -[![CircleCI](https://img.shields.io/circleci/project/github/googleapis/nodejs-firestore.svg?style=flat)](https://circleci.com/gh/googleapis/nodejs-firestore) -[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/googleapis/nodejs-firestore?branch=master&svg=true)](https://ci.appveyor.com/project/googleapis/nodejs-firestore) -[![codecov](https://img.shields.io/codecov/c/github/googleapis/nodejs-firestore/master.svg?style=flat)](https://codecov.io/gh/googleapis/nodejs-firestore) - -This is the Node.js Server SDK for -[Google Cloud Firestore](https://firebase.google.com/docs/firestore/). Google -Cloud Firestore is a NoSQL document database built for automatic scaling, high -performance, and ease of application development. - -This Cloud Firestore Server SDK uses Google’s [Cloud Identity and Access -Management](https://cloud.google.com/firestore/docs/security/iam) for -authentication and should only be used **in trusted environments**. Your Cloud -Identity credentials allow you bypass all access restrictions and provide read -and write access to all data in your Cloud Firestore project. - -The Cloud Firestore Server SDKs are designed to manage the full set of data in -your Cloud Firestore project and work best with reliable network connectivity. -Data operations performed via these SDKs directly access the Cloud Firestore -backend and all document reads and writes are optimized for high throughput. - -Applications that use Google's Server SDKs should not be used in end-user -environments, such as on phones or on publicly hosted websites. If you are -developing a Web or Node.js application that accesses Cloud Firestore on behalf -of end users, use the [`firebase`](https://www.npmjs.com/package/firebase) -Client SDK. - -**Table of contents:** - -* [Quickstart](#quickstart) - * [Before you begin](#before-you-begin) - * [Installing the client library](#installing-the-client-library) - * [Using the client library](#using-the-client-library) -* [Versioning](#versioning) -* [Contributing](#contributing) -* [License](#license) - -## Quickstart - -Read more about the client libraries for Cloud APIs, including the older -Google APIs Client Libraries, in [Client Libraries Explained][explained]. - -[explained]: https://cloud.google.com/apis/docs/client-libraries-explained - -* [Cloud Firestore Node.js Client API Reference][client-docs] -* [github.com/googleapis/nodejs-firestore](https://github.com/googleapis/nodejs-firestore) -* [Cloud Firestore Documentation][product-docs] - -### Before you begin - -1. Select or create a Cloud Platform project. - - [Go to the projects page][projects] - -1. Enable the Google Cloud Firestore API. - - [Enable the API][enable_api] - -1. [Set up authentication with a service account][auth] so you can access the - API from your local workstation. - -[projects]: https://console.cloud.google.com/project -[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com -[auth]: https://cloud.google.com/docs/authentication/getting-started - -### Installing the client library - - npm install --save @google-cloud/firestore - -### Using the client library - -```javascript -const Firestore = require('@google-cloud/firestore'); - -const firestore = new Firestore({ - projectId: 'YOUR_PROJECT_ID', - keyFilename: '/path/to/keyfile.json', -}); - -const document = firestore.doc('posts/intro-to-firestore'); - -// Enter new data into the document. -document.set({ - title: 'Welcome to Firestore', - body: 'Hello World', -}).then(() => { - // Document created successfully. -}); - -// Update an existing document. -document.update({ - body: 'My first Firestore app', -}).then(() => { - // Document updated successfully. -}); - -// Read the document. -document.get().then(doc => { - // Document read successfully. -}); - -// Delete the document. -document.delete().then(() => { - // Document deleted successfully. -}); -``` - - -The [Cloud Firestore Node.js Client API Reference][client-docs] documentation -also contains samples. - -## Versioning - -This library follows [Semantic Versioning](http://semver.org/). - -This library is considered to be in **beta**. This means it is expected to be -mostly stable while we work toward a general availability release; however, -complete stability is not guaranteed. We will address issues and requests -against beta libraries with a high priority. - -More Information: [Google Cloud Platform Launch Stages][launch_stages] - -[launch_stages]: https://cloud.google.com/terms/launch-stages - -## Contributing - -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-firestore/blob/master/.github/CONTRIBUTING.md). - -## License - -Apache Version 2.0 - -See [LICENSE](https://github.com/googleapis/nodejs-firestore/blob/master/LICENSE) - -[client-docs]: https://cloud.google.com/nodejs/docs/reference/firestore/latest/ -[product-docs]: https://firebase.google.com/docs/firestore/ -[shell_img]: //gstatic.com/cloudssh/images/open-btn.png diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/README.md b/functions/node_modules/@google-cloud/firestore/build/protos/README.md deleted file mode 100644 index 54468be9..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/protos/README.md +++ /dev/null @@ -1,33 +0,0 @@ -The `firestore_proto_api.d.ts` and `firestore_proto_api.js` are generated from the Firestore -protofbuf definitions. While there are certainly more proper ways of doing this, the following -process was used: - -- Check out `google-proto-files` from NPM. -``` -npm install --save google-proto-files -``` - -- Copy the `google/firestore/v1beta/*.proto` and place them in current folder. -``` -cp node_modules/google-proto-files/google/firestore/v1beta1/*.proto . -``` - -- Remove the `google/firestore/v1beta` path from any import statements in these files. - -``` -sed -i '' 's/import \"google\/firestore\/v1beta1\//import \"/g' *.proto -``` - -- Generate the output files -``` -mkdir -p out && pbjs --proto_path node_modules/google-proto-files -t static-module -w commonjs -o out/firestore_proto_api.js firestore.proto && pbts -o out/firestore_proto_api.d.ts out/firestore_proto_api.js -``` - -- Edit the type used for integers greater than 2^53. The GRPC settings we use represent them as -Strings, but pbjs uses the "Long" type. - -``` -sed -i '' 's/number\|Long/number\|string \"/g' firestore_proto_api.d.ts firestore_proto_api.js -``` - -TODO: Find a way to properly specify the proto paths for the Firestore imports so this can be automated. \ No newline at end of file diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.d.ts b/functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.d.ts deleted file mode 100644 index 46225472..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.d.ts +++ /dev/null @@ -1,10582 +0,0 @@ -import * as $protobuf from "protobufjs"; - -// Note: This file was manually edited to use "string" instead of "Long" for -// types that can potentially hold large integer values (> 2^53). - -/** Namespace google. */ -export namespace google { - - /** Namespace firestore. */ - namespace firestore { - - /** Namespace v1beta1. */ - namespace v1beta1 { - - /** Represents a Firestore */ - class Firestore extends $protobuf.rpc.Service { - - /** - * Constructs a new Firestore service. - * @param rpcImpl RPC implementation - * @param [requestDelimited=false] Whether requests are length-delimited - * @param [responseDelimited=false] Whether responses are length-delimited - */ - constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); - - /** - * Creates new Firestore service using the specified rpc implementation. - * @param rpcImpl RPC implementation - * @param [requestDelimited=false] Whether requests are length-delimited - * @param [responseDelimited=false] Whether responses are length-delimited - * @returns RPC service. Useful where requests and/or responses are streamed. - */ - public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Firestore; - - /** - * Calls GetDocument. - * @param request GetDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest, callback: google.firestore.v1beta1.Firestore.GetDocumentCallback): void; - - /** - * Calls GetDocument. - * @param request GetDocumentRequest message or plain object - * @returns Promise - */ - public getDocument(request: google.firestore.v1beta1.IGetDocumentRequest): Promise; - - /** - * Calls ListDocuments. - * @param request ListDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse - */ - public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest, callback: google.firestore.v1beta1.Firestore.ListDocumentsCallback): void; - - /** - * Calls ListDocuments. - * @param request ListDocumentsRequest message or plain object - * @returns Promise - */ - public listDocuments(request: google.firestore.v1beta1.IListDocumentsRequest): Promise; - - /** - * Calls CreateDocument. - * @param request CreateDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest, callback: google.firestore.v1beta1.Firestore.CreateDocumentCallback): void; - - /** - * Calls CreateDocument. - * @param request CreateDocumentRequest message or plain object - * @returns Promise - */ - public createDocument(request: google.firestore.v1beta1.ICreateDocumentRequest): Promise; - - /** - * Calls UpdateDocument. - * @param request UpdateDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest, callback: google.firestore.v1beta1.Firestore.UpdateDocumentCallback): void; - - /** - * Calls UpdateDocument. - * @param request UpdateDocumentRequest message or plain object - * @returns Promise - */ - public updateDocument(request: google.firestore.v1beta1.IUpdateDocumentRequest): Promise; - - /** - * Calls DeleteDocument. - * @param request DeleteDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest, callback: google.firestore.v1beta1.Firestore.DeleteDocumentCallback): void; - - /** - * Calls DeleteDocument. - * @param request DeleteDocumentRequest message or plain object - * @returns Promise - */ - public deleteDocument(request: google.firestore.v1beta1.IDeleteDocumentRequest): Promise; - - /** - * Calls BatchGetDocuments. - * @param request BatchGetDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse - */ - public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest, callback: google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback): void; - - /** - * Calls BatchGetDocuments. - * @param request BatchGetDocumentsRequest message or plain object - * @returns Promise - */ - public batchGetDocuments(request: google.firestore.v1beta1.IBatchGetDocumentsRequest): Promise; - - /** - * Calls BeginTransaction. - * @param request BeginTransactionRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse - */ - public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest, callback: google.firestore.v1beta1.Firestore.BeginTransactionCallback): void; - - /** - * Calls BeginTransaction. - * @param request BeginTransactionRequest message or plain object - * @returns Promise - */ - public beginTransaction(request: google.firestore.v1beta1.IBeginTransactionRequest): Promise; - - /** - * Calls Commit. - * @param request CommitRequest message or plain object - * @param callback Node-style callback called with the error, if any, and CommitResponse - */ - public commit(request: google.firestore.v1beta1.ICommitRequest, callback: google.firestore.v1beta1.Firestore.CommitCallback): void; - - /** - * Calls Commit. - * @param request CommitRequest message or plain object - * @returns Promise - */ - public commit(request: google.firestore.v1beta1.ICommitRequest): Promise; - - /** - * Calls Rollback. - * @param request RollbackRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public rollback(request: google.firestore.v1beta1.IRollbackRequest, callback: google.firestore.v1beta1.Firestore.RollbackCallback): void; - - /** - * Calls Rollback. - * @param request RollbackRequest message or plain object - * @returns Promise - */ - public rollback(request: google.firestore.v1beta1.IRollbackRequest): Promise; - - /** - * Calls RunQuery. - * @param request RunQueryRequest message or plain object - * @param callback Node-style callback called with the error, if any, and RunQueryResponse - */ - public runQuery(request: google.firestore.v1beta1.IRunQueryRequest, callback: google.firestore.v1beta1.Firestore.RunQueryCallback): void; - - /** - * Calls RunQuery. - * @param request RunQueryRequest message or plain object - * @returns Promise - */ - public runQuery(request: google.firestore.v1beta1.IRunQueryRequest): Promise; - - /** - * Calls Write. - * @param request WriteRequest message or plain object - * @param callback Node-style callback called with the error, if any, and WriteResponse - */ - public write(request: google.firestore.v1beta1.IWriteRequest, callback: google.firestore.v1beta1.Firestore.WriteCallback): void; - - /** - * Calls Write. - * @param request WriteRequest message or plain object - * @returns Promise - */ - public write(request: google.firestore.v1beta1.IWriteRequest): Promise; - - /** - * Calls Listen. - * @param request ListenRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListenResponse - */ - public listen(request: google.firestore.v1beta1.IListenRequest, callback: google.firestore.v1beta1.Firestore.ListenCallback): void; - - /** - * Calls Listen. - * @param request ListenRequest message or plain object - * @returns Promise - */ - public listen(request: google.firestore.v1beta1.IListenRequest): Promise; - - /** - * Calls ListCollectionIds. - * @param request ListCollectionIdsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse - */ - public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest, callback: google.firestore.v1beta1.Firestore.ListCollectionIdsCallback): void; - - /** - * Calls ListCollectionIds. - * @param request ListCollectionIdsRequest message or plain object - * @returns Promise - */ - public listCollectionIds(request: google.firestore.v1beta1.IListCollectionIdsRequest): Promise; - } - - namespace Firestore { - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. - * @param error Error, if any - * @param [response] Document - */ - type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. - * @param error Error, if any - * @param [response] ListDocumentsResponse - */ - type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListDocumentsResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. - * @param error Error, if any - * @param [response] Document - */ - type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. - * @param error Error, if any - * @param [response] Document - */ - type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1beta1.Document) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. - * @param error Error, if any - * @param [response] Empty - */ - type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. - * @param error Error, if any - * @param [response] BatchGetDocumentsResponse - */ - type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1beta1.BatchGetDocumentsResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. - * @param error Error, if any - * @param [response] BeginTransactionResponse - */ - type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1beta1.BeginTransactionResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. - * @param error Error, if any - * @param [response] CommitResponse - */ - type CommitCallback = (error: (Error|null), response?: google.firestore.v1beta1.CommitResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. - * @param error Error, if any - * @param [response] Empty - */ - type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. - * @param error Error, if any - * @param [response] RunQueryResponse - */ - type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1beta1.RunQueryResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. - * @param error Error, if any - * @param [response] WriteResponse - */ - type WriteCallback = (error: (Error|null), response?: google.firestore.v1beta1.WriteResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. - * @param error Error, if any - * @param [response] ListenResponse - */ - type ListenCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListenResponse) => void; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. - * @param error Error, if any - * @param [response] ListCollectionIdsResponse - */ - type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1beta1.ListCollectionIdsResponse) => void; - } - - /** Properties of a GetDocumentRequest. */ - interface IGetDocumentRequest { - - /** GetDocumentRequest name */ - name?: (string|null); - - /** GetDocumentRequest mask */ - mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** GetDocumentRequest transaction */ - transaction?: (Uint8Array|null); - - /** GetDocumentRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a GetDocumentRequest. */ - class GetDocumentRequest implements IGetDocumentRequest { - - /** - * Constructs a new GetDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IGetDocumentRequest); - - /** GetDocumentRequest name. */ - public name: string; - - /** GetDocumentRequest mask. */ - public mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** GetDocumentRequest transaction. */ - public transaction: Uint8Array; - - /** GetDocumentRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** GetDocumentRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"readTime"); - - /** - * Creates a new GetDocumentRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns GetDocumentRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IGetDocumentRequest): google.firestore.v1beta1.GetDocumentRequest; - - /** - * Encodes the specified GetDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.GetDocumentRequest.verify|verify} messages. - * @param message GetDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IGetDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified GetDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.GetDocumentRequest.verify|verify} messages. - * @param message GetDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IGetDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a GetDocumentRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns GetDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.GetDocumentRequest; - - /** - * Decodes a GetDocumentRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns GetDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.GetDocumentRequest; - - /** - * Verifies a GetDocumentRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns GetDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.GetDocumentRequest; - - /** - * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. - * @param message GetDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this GetDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ListDocumentsRequest. */ - interface IListDocumentsRequest { - - /** ListDocumentsRequest parent */ - parent?: (string|null); - - /** ListDocumentsRequest collectionId */ - collectionId?: (string|null); - - /** ListDocumentsRequest pageSize */ - pageSize?: (number|null); - - /** ListDocumentsRequest pageToken */ - pageToken?: (string|null); - - /** ListDocumentsRequest orderBy */ - orderBy?: (string|null); - - /** ListDocumentsRequest mask */ - mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** ListDocumentsRequest transaction */ - transaction?: (Uint8Array|null); - - /** ListDocumentsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - - /** ListDocumentsRequest showMissing */ - showMissing?: (boolean|null); - } - - /** Represents a ListDocumentsRequest. */ - class ListDocumentsRequest implements IListDocumentsRequest { - - /** - * Constructs a new ListDocumentsRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IListDocumentsRequest); - - /** ListDocumentsRequest parent. */ - public parent: string; - - /** ListDocumentsRequest collectionId. */ - public collectionId: string; - - /** ListDocumentsRequest pageSize. */ - public pageSize: number; - - /** ListDocumentsRequest pageToken. */ - public pageToken: string; - - /** ListDocumentsRequest orderBy. */ - public orderBy: string; - - /** ListDocumentsRequest mask. */ - public mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** ListDocumentsRequest transaction. */ - public transaction: Uint8Array; - - /** ListDocumentsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** ListDocumentsRequest showMissing. */ - public showMissing: boolean; - - /** ListDocumentsRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"readTime"); - - /** - * Creates a new ListDocumentsRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns ListDocumentsRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IListDocumentsRequest): google.firestore.v1beta1.ListDocumentsRequest; - - /** - * Encodes the specified ListDocumentsRequest message. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsRequest.verify|verify} messages. - * @param message ListDocumentsRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IListDocumentsRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListDocumentsRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsRequest.verify|verify} messages. - * @param message ListDocumentsRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IListDocumentsRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListDocumentsRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ListDocumentsRequest; - - /** - * Decodes a ListDocumentsRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ListDocumentsRequest; - - /** - * Verifies a ListDocumentsRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListDocumentsRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsRequest; - - /** - * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. - * @param message ListDocumentsRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListDocumentsRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ListDocumentsResponse. */ - interface IListDocumentsResponse { - - /** ListDocumentsResponse documents */ - documents?: (google.firestore.v1beta1.IDocument[]|null); - - /** ListDocumentsResponse nextPageToken */ - nextPageToken?: (string|null); - } - - /** Represents a ListDocumentsResponse. */ - class ListDocumentsResponse implements IListDocumentsResponse { - - /** - * Constructs a new ListDocumentsResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IListDocumentsResponse); - - /** ListDocumentsResponse documents. */ - public documents: google.firestore.v1beta1.IDocument[]; - - /** ListDocumentsResponse nextPageToken. */ - public nextPageToken: string; - - /** - * Creates a new ListDocumentsResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns ListDocumentsResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IListDocumentsResponse): google.firestore.v1beta1.ListDocumentsResponse; - - /** - * Encodes the specified ListDocumentsResponse message. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsResponse.verify|verify} messages. - * @param message ListDocumentsResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IListDocumentsResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListDocumentsResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsResponse.verify|verify} messages. - * @param message ListDocumentsResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IListDocumentsResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListDocumentsResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ListDocumentsResponse; - - /** - * Decodes a ListDocumentsResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ListDocumentsResponse; - - /** - * Verifies a ListDocumentsResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListDocumentsResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListDocumentsResponse; - - /** - * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. - * @param message ListDocumentsResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListDocumentsResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a CreateDocumentRequest. */ - interface ICreateDocumentRequest { - - /** CreateDocumentRequest parent */ - parent?: (string|null); - - /** CreateDocumentRequest collectionId */ - collectionId?: (string|null); - - /** CreateDocumentRequest documentId */ - documentId?: (string|null); - - /** CreateDocumentRequest document */ - document?: (google.firestore.v1beta1.IDocument|null); - - /** CreateDocumentRequest mask */ - mask?: (google.firestore.v1beta1.IDocumentMask|null); - } - - /** Represents a CreateDocumentRequest. */ - class CreateDocumentRequest implements ICreateDocumentRequest { - - /** - * Constructs a new CreateDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ICreateDocumentRequest); - - /** CreateDocumentRequest parent. */ - public parent: string; - - /** CreateDocumentRequest collectionId. */ - public collectionId: string; - - /** CreateDocumentRequest documentId. */ - public documentId: string; - - /** CreateDocumentRequest document. */ - public document?: (google.firestore.v1beta1.IDocument|null); - - /** CreateDocumentRequest mask. */ - public mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** - * Creates a new CreateDocumentRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns CreateDocumentRequest instance - */ - public static create(properties?: google.firestore.v1beta1.ICreateDocumentRequest): google.firestore.v1beta1.CreateDocumentRequest; - - /** - * Encodes the specified CreateDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.CreateDocumentRequest.verify|verify} messages. - * @param message CreateDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ICreateDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified CreateDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.CreateDocumentRequest.verify|verify} messages. - * @param message CreateDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ICreateDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CreateDocumentRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns CreateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.CreateDocumentRequest; - - /** - * Decodes a CreateDocumentRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns CreateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.CreateDocumentRequest; - - /** - * Verifies a CreateDocumentRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CreateDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CreateDocumentRequest; - - /** - * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. - * @param message CreateDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CreateDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an UpdateDocumentRequest. */ - interface IUpdateDocumentRequest { - - /** UpdateDocumentRequest document */ - document?: (google.firestore.v1beta1.IDocument|null); - - /** UpdateDocumentRequest updateMask */ - updateMask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** UpdateDocumentRequest mask */ - mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** UpdateDocumentRequest currentDocument */ - currentDocument?: (google.firestore.v1beta1.IPrecondition|null); - } - - /** Represents an UpdateDocumentRequest. */ - class UpdateDocumentRequest implements IUpdateDocumentRequest { - - /** - * Constructs a new UpdateDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IUpdateDocumentRequest); - - /** UpdateDocumentRequest document. */ - public document?: (google.firestore.v1beta1.IDocument|null); - - /** UpdateDocumentRequest updateMask. */ - public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** UpdateDocumentRequest mask. */ - public mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** UpdateDocumentRequest currentDocument. */ - public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); - - /** - * Creates a new UpdateDocumentRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns UpdateDocumentRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IUpdateDocumentRequest): google.firestore.v1beta1.UpdateDocumentRequest; - - /** - * Encodes the specified UpdateDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.UpdateDocumentRequest.verify|verify} messages. - * @param message UpdateDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IUpdateDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified UpdateDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.UpdateDocumentRequest.verify|verify} messages. - * @param message UpdateDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IUpdateDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an UpdateDocumentRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns UpdateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.UpdateDocumentRequest; - - /** - * Decodes an UpdateDocumentRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns UpdateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.UpdateDocumentRequest; - - /** - * Verifies an UpdateDocumentRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UpdateDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UpdateDocumentRequest; - - /** - * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. - * @param message UpdateDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this UpdateDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DeleteDocumentRequest. */ - interface IDeleteDocumentRequest { - - /** DeleteDocumentRequest name */ - name?: (string|null); - - /** DeleteDocumentRequest currentDocument */ - currentDocument?: (google.firestore.v1beta1.IPrecondition|null); - } - - /** Represents a DeleteDocumentRequest. */ - class DeleteDocumentRequest implements IDeleteDocumentRequest { - - /** - * Constructs a new DeleteDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDeleteDocumentRequest); - - /** DeleteDocumentRequest name. */ - public name: string; - - /** DeleteDocumentRequest currentDocument. */ - public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); - - /** - * Creates a new DeleteDocumentRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns DeleteDocumentRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IDeleteDocumentRequest): google.firestore.v1beta1.DeleteDocumentRequest; - - /** - * Encodes the specified DeleteDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.DeleteDocumentRequest.verify|verify} messages. - * @param message DeleteDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDeleteDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DeleteDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DeleteDocumentRequest.verify|verify} messages. - * @param message DeleteDocumentRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDeleteDocumentRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DeleteDocumentRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DeleteDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DeleteDocumentRequest; - - /** - * Decodes a DeleteDocumentRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DeleteDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DeleteDocumentRequest; - - /** - * Verifies a DeleteDocumentRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DeleteDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DeleteDocumentRequest; - - /** - * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. - * @param message DeleteDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DeleteDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a BatchGetDocumentsRequest. */ - interface IBatchGetDocumentsRequest { - - /** BatchGetDocumentsRequest database */ - database?: (string|null); - - /** BatchGetDocumentsRequest documents */ - documents?: (string[]|null); - - /** BatchGetDocumentsRequest mask */ - mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** BatchGetDocumentsRequest transaction */ - transaction?: (Uint8Array|null); - - /** BatchGetDocumentsRequest newTransaction */ - newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); - - /** BatchGetDocumentsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a BatchGetDocumentsRequest. */ - class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { - - /** - * Constructs a new BatchGetDocumentsRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsRequest); - - /** BatchGetDocumentsRequest database. */ - public database: string; - - /** BatchGetDocumentsRequest documents. */ - public documents: string[]; - - /** BatchGetDocumentsRequest mask. */ - public mask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** BatchGetDocumentsRequest transaction. */ - public transaction: Uint8Array; - - /** BatchGetDocumentsRequest newTransaction. */ - public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); - - /** BatchGetDocumentsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** BatchGetDocumentsRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); - - /** - * Creates a new BatchGetDocumentsRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns BatchGetDocumentsRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IBatchGetDocumentsRequest): google.firestore.v1beta1.BatchGetDocumentsRequest; - - /** - * Encodes the specified BatchGetDocumentsRequest message. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsRequest.verify|verify} messages. - * @param message BatchGetDocumentsRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IBatchGetDocumentsRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified BatchGetDocumentsRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsRequest.verify|verify} messages. - * @param message BatchGetDocumentsRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IBatchGetDocumentsRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a BatchGetDocumentsRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns BatchGetDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.BatchGetDocumentsRequest; - - /** - * Decodes a BatchGetDocumentsRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns BatchGetDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.BatchGetDocumentsRequest; - - /** - * Verifies a BatchGetDocumentsRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchGetDocumentsRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsRequest; - - /** - * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. - * @param message BatchGetDocumentsRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BatchGetDocumentsRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a BatchGetDocumentsResponse. */ - interface IBatchGetDocumentsResponse { - - /** BatchGetDocumentsResponse found */ - found?: (google.firestore.v1beta1.IDocument|null); - - /** BatchGetDocumentsResponse missing */ - missing?: (string|null); - - /** BatchGetDocumentsResponse transaction */ - transaction?: (Uint8Array|null); - - /** BatchGetDocumentsResponse readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a BatchGetDocumentsResponse. */ - class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { - - /** - * Constructs a new BatchGetDocumentsResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IBatchGetDocumentsResponse); - - /** BatchGetDocumentsResponse found. */ - public found?: (google.firestore.v1beta1.IDocument|null); - - /** BatchGetDocumentsResponse missing. */ - public missing: string; - - /** BatchGetDocumentsResponse transaction. */ - public transaction: Uint8Array; - - /** BatchGetDocumentsResponse readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** BatchGetDocumentsResponse result. */ - public result?: ("found"|"missing"); - - /** - * Creates a new BatchGetDocumentsResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns BatchGetDocumentsResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IBatchGetDocumentsResponse): google.firestore.v1beta1.BatchGetDocumentsResponse; - - /** - * Encodes the specified BatchGetDocumentsResponse message. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsResponse.verify|verify} messages. - * @param message BatchGetDocumentsResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IBatchGetDocumentsResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified BatchGetDocumentsResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsResponse.verify|verify} messages. - * @param message BatchGetDocumentsResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IBatchGetDocumentsResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a BatchGetDocumentsResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns BatchGetDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.BatchGetDocumentsResponse; - - /** - * Decodes a BatchGetDocumentsResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns BatchGetDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.BatchGetDocumentsResponse; - - /** - * Verifies a BatchGetDocumentsResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchGetDocumentsResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BatchGetDocumentsResponse; - - /** - * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. - * @param message BatchGetDocumentsResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BatchGetDocumentsResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a BeginTransactionRequest. */ - interface IBeginTransactionRequest { - - /** BeginTransactionRequest database */ - database?: (string|null); - - /** BeginTransactionRequest options */ - options?: (google.firestore.v1beta1.ITransactionOptions|null); - } - - /** Represents a BeginTransactionRequest. */ - class BeginTransactionRequest implements IBeginTransactionRequest { - - /** - * Constructs a new BeginTransactionRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IBeginTransactionRequest); - - /** BeginTransactionRequest database. */ - public database: string; - - /** BeginTransactionRequest options. */ - public options?: (google.firestore.v1beta1.ITransactionOptions|null); - - /** - * Creates a new BeginTransactionRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns BeginTransactionRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IBeginTransactionRequest): google.firestore.v1beta1.BeginTransactionRequest; - - /** - * Encodes the specified BeginTransactionRequest message. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionRequest.verify|verify} messages. - * @param message BeginTransactionRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IBeginTransactionRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified BeginTransactionRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionRequest.verify|verify} messages. - * @param message BeginTransactionRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IBeginTransactionRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a BeginTransactionRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns BeginTransactionRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.BeginTransactionRequest; - - /** - * Decodes a BeginTransactionRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns BeginTransactionRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.BeginTransactionRequest; - - /** - * Verifies a BeginTransactionRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BeginTransactionRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionRequest; - - /** - * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. - * @param message BeginTransactionRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BeginTransactionRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a BeginTransactionResponse. */ - interface IBeginTransactionResponse { - - /** BeginTransactionResponse transaction */ - transaction?: (Uint8Array|null); - } - - /** Represents a BeginTransactionResponse. */ - class BeginTransactionResponse implements IBeginTransactionResponse { - - /** - * Constructs a new BeginTransactionResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IBeginTransactionResponse); - - /** BeginTransactionResponse transaction. */ - public transaction: Uint8Array; - - /** - * Creates a new BeginTransactionResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns BeginTransactionResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IBeginTransactionResponse): google.firestore.v1beta1.BeginTransactionResponse; - - /** - * Encodes the specified BeginTransactionResponse message. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionResponse.verify|verify} messages. - * @param message BeginTransactionResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IBeginTransactionResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified BeginTransactionResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionResponse.verify|verify} messages. - * @param message BeginTransactionResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IBeginTransactionResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a BeginTransactionResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns BeginTransactionResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.BeginTransactionResponse; - - /** - * Decodes a BeginTransactionResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns BeginTransactionResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.BeginTransactionResponse; - - /** - * Verifies a BeginTransactionResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BeginTransactionResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.BeginTransactionResponse; - - /** - * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. - * @param message BeginTransactionResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BeginTransactionResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a CommitRequest. */ - interface ICommitRequest { - - /** CommitRequest database */ - database?: (string|null); - - /** CommitRequest writes */ - writes?: (google.firestore.v1beta1.IWrite[]|null); - - /** CommitRequest transaction */ - transaction?: (Uint8Array|null); - } - - /** Represents a CommitRequest. */ - class CommitRequest implements ICommitRequest { - - /** - * Constructs a new CommitRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ICommitRequest); - - /** CommitRequest database. */ - public database: string; - - /** CommitRequest writes. */ - public writes: google.firestore.v1beta1.IWrite[]; - - /** CommitRequest transaction. */ - public transaction: Uint8Array; - - /** - * Creates a new CommitRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns CommitRequest instance - */ - public static create(properties?: google.firestore.v1beta1.ICommitRequest): google.firestore.v1beta1.CommitRequest; - - /** - * Encodes the specified CommitRequest message. Does not implicitly {@link google.firestore.v1beta1.CommitRequest.verify|verify} messages. - * @param message CommitRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ICommitRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified CommitRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.CommitRequest.verify|verify} messages. - * @param message CommitRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ICommitRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CommitRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns CommitRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.CommitRequest; - - /** - * Decodes a CommitRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns CommitRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.CommitRequest; - - /** - * Verifies a CommitRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CommitRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitRequest; - - /** - * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. - * @param message CommitRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CommitRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a CommitResponse. */ - interface ICommitResponse { - - /** CommitResponse writeResults */ - writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); - - /** CommitResponse commitTime */ - commitTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a CommitResponse. */ - class CommitResponse implements ICommitResponse { - - /** - * Constructs a new CommitResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ICommitResponse); - - /** CommitResponse writeResults. */ - public writeResults: google.firestore.v1beta1.IWriteResult[]; - - /** CommitResponse commitTime. */ - public commitTime?: (google.protobuf.ITimestamp|null); - - /** - * Creates a new CommitResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns CommitResponse instance - */ - public static create(properties?: google.firestore.v1beta1.ICommitResponse): google.firestore.v1beta1.CommitResponse; - - /** - * Encodes the specified CommitResponse message. Does not implicitly {@link google.firestore.v1beta1.CommitResponse.verify|verify} messages. - * @param message CommitResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ICommitResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified CommitResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.CommitResponse.verify|verify} messages. - * @param message CommitResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ICommitResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CommitResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns CommitResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.CommitResponse; - - /** - * Decodes a CommitResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns CommitResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.CommitResponse; - - /** - * Verifies a CommitResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CommitResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.CommitResponse; - - /** - * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. - * @param message CommitResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CommitResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a RollbackRequest. */ - interface IRollbackRequest { - - /** RollbackRequest database */ - database?: (string|null); - - /** RollbackRequest transaction */ - transaction?: (Uint8Array|null); - } - - /** Represents a RollbackRequest. */ - class RollbackRequest implements IRollbackRequest { - - /** - * Constructs a new RollbackRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IRollbackRequest); - - /** RollbackRequest database. */ - public database: string; - - /** RollbackRequest transaction. */ - public transaction: Uint8Array; - - /** - * Creates a new RollbackRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns RollbackRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IRollbackRequest): google.firestore.v1beta1.RollbackRequest; - - /** - * Encodes the specified RollbackRequest message. Does not implicitly {@link google.firestore.v1beta1.RollbackRequest.verify|verify} messages. - * @param message RollbackRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IRollbackRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified RollbackRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.RollbackRequest.verify|verify} messages. - * @param message RollbackRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IRollbackRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a RollbackRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns RollbackRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.RollbackRequest; - - /** - * Decodes a RollbackRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns RollbackRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.RollbackRequest; - - /** - * Verifies a RollbackRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RollbackRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RollbackRequest; - - /** - * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. - * @param message RollbackRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this RollbackRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a RunQueryRequest. */ - interface IRunQueryRequest { - - /** RunQueryRequest parent */ - parent?: (string|null); - - /** RunQueryRequest structuredQuery */ - structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); - - /** RunQueryRequest transaction */ - transaction?: (Uint8Array|null); - - /** RunQueryRequest newTransaction */ - newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); - - /** RunQueryRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a RunQueryRequest. */ - class RunQueryRequest implements IRunQueryRequest { - - /** - * Constructs a new RunQueryRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IRunQueryRequest); - - /** RunQueryRequest parent. */ - public parent: string; - - /** RunQueryRequest structuredQuery. */ - public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); - - /** RunQueryRequest transaction. */ - public transaction: Uint8Array; - - /** RunQueryRequest newTransaction. */ - public newTransaction?: (google.firestore.v1beta1.ITransactionOptions|null); - - /** RunQueryRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** RunQueryRequest queryType. */ - public queryType?: "structuredQuery"; - - /** RunQueryRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); - - /** - * Creates a new RunQueryRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns RunQueryRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IRunQueryRequest): google.firestore.v1beta1.RunQueryRequest; - - /** - * Encodes the specified RunQueryRequest message. Does not implicitly {@link google.firestore.v1beta1.RunQueryRequest.verify|verify} messages. - * @param message RunQueryRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IRunQueryRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified RunQueryRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.RunQueryRequest.verify|verify} messages. - * @param message RunQueryRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IRunQueryRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a RunQueryRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns RunQueryRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.RunQueryRequest; - - /** - * Decodes a RunQueryRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns RunQueryRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.RunQueryRequest; - - /** - * Verifies a RunQueryRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunQueryRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryRequest; - - /** - * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. - * @param message RunQueryRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this RunQueryRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a RunQueryResponse. */ - interface IRunQueryResponse { - - /** RunQueryResponse transaction */ - transaction?: (Uint8Array|null); - - /** RunQueryResponse document */ - document?: (google.firestore.v1beta1.IDocument|null); - - /** RunQueryResponse readTime */ - readTime?: (google.protobuf.ITimestamp|null); - - /** RunQueryResponse skippedResults */ - skippedResults?: (number|null); - } - - /** Represents a RunQueryResponse. */ - class RunQueryResponse implements IRunQueryResponse { - - /** - * Constructs a new RunQueryResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IRunQueryResponse); - - /** RunQueryResponse transaction. */ - public transaction: Uint8Array; - - /** RunQueryResponse document. */ - public document?: (google.firestore.v1beta1.IDocument|null); - - /** RunQueryResponse readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** RunQueryResponse skippedResults. */ - public skippedResults: number; - - /** - * Creates a new RunQueryResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns RunQueryResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IRunQueryResponse): google.firestore.v1beta1.RunQueryResponse; - - /** - * Encodes the specified RunQueryResponse message. Does not implicitly {@link google.firestore.v1beta1.RunQueryResponse.verify|verify} messages. - * @param message RunQueryResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IRunQueryResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified RunQueryResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.RunQueryResponse.verify|verify} messages. - * @param message RunQueryResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IRunQueryResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a RunQueryResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns RunQueryResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.RunQueryResponse; - - /** - * Decodes a RunQueryResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns RunQueryResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.RunQueryResponse; - - /** - * Verifies a RunQueryResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunQueryResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.RunQueryResponse; - - /** - * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. - * @param message RunQueryResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this RunQueryResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a WriteRequest. */ - interface IWriteRequest { - - /** WriteRequest database */ - database?: (string|null); - - /** WriteRequest streamId */ - streamId?: (string|null); - - /** WriteRequest writes */ - writes?: (google.firestore.v1beta1.IWrite[]|null); - - /** WriteRequest streamToken */ - streamToken?: (Uint8Array|null); - - /** WriteRequest labels */ - labels?: ({ [k: string]: string }|null); - } - - /** Represents a WriteRequest. */ - class WriteRequest implements IWriteRequest { - - /** - * Constructs a new WriteRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IWriteRequest); - - /** WriteRequest database. */ - public database: string; - - /** WriteRequest streamId. */ - public streamId: string; - - /** WriteRequest writes. */ - public writes: google.firestore.v1beta1.IWrite[]; - - /** WriteRequest streamToken. */ - public streamToken: Uint8Array; - - /** WriteRequest labels. */ - public labels: { [k: string]: string }; - - /** - * Creates a new WriteRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns WriteRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IWriteRequest): google.firestore.v1beta1.WriteRequest; - - /** - * Encodes the specified WriteRequest message. Does not implicitly {@link google.firestore.v1beta1.WriteRequest.verify|verify} messages. - * @param message WriteRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IWriteRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified WriteRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.WriteRequest.verify|verify} messages. - * @param message WriteRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IWriteRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a WriteRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns WriteRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.WriteRequest; - - /** - * Decodes a WriteRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns WriteRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.WriteRequest; - - /** - * Verifies a WriteRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteRequest; - - /** - * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. - * @param message WriteRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this WriteRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a WriteResponse. */ - interface IWriteResponse { - - /** WriteResponse streamId */ - streamId?: (string|null); - - /** WriteResponse streamToken */ - streamToken?: (Uint8Array|null); - - /** WriteResponse writeResults */ - writeResults?: (google.firestore.v1beta1.IWriteResult[]|null); - - /** WriteResponse commitTime */ - commitTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a WriteResponse. */ - class WriteResponse implements IWriteResponse { - - /** - * Constructs a new WriteResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IWriteResponse); - - /** WriteResponse streamId. */ - public streamId: string; - - /** WriteResponse streamToken. */ - public streamToken: Uint8Array; - - /** WriteResponse writeResults. */ - public writeResults: google.firestore.v1beta1.IWriteResult[]; - - /** WriteResponse commitTime. */ - public commitTime?: (google.protobuf.ITimestamp|null); - - /** - * Creates a new WriteResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns WriteResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IWriteResponse): google.firestore.v1beta1.WriteResponse; - - /** - * Encodes the specified WriteResponse message. Does not implicitly {@link google.firestore.v1beta1.WriteResponse.verify|verify} messages. - * @param message WriteResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IWriteResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified WriteResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.WriteResponse.verify|verify} messages. - * @param message WriteResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IWriteResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a WriteResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns WriteResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.WriteResponse; - - /** - * Decodes a WriteResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns WriteResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.WriteResponse; - - /** - * Verifies a WriteResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResponse; - - /** - * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. - * @param message WriteResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this WriteResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ListenRequest. */ - interface IListenRequest { - - /** ListenRequest database */ - database?: (string|null); - - /** ListenRequest addTarget */ - addTarget?: (google.firestore.v1beta1.ITarget|null); - - /** ListenRequest removeTarget */ - removeTarget?: (number|null); - - /** ListenRequest labels */ - labels?: ({ [k: string]: string }|null); - } - - /** Represents a ListenRequest. */ - class ListenRequest implements IListenRequest { - - /** - * Constructs a new ListenRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IListenRequest); - - /** ListenRequest database. */ - public database: string; - - /** ListenRequest addTarget. */ - public addTarget?: (google.firestore.v1beta1.ITarget|null); - - /** ListenRequest removeTarget. */ - public removeTarget: number; - - /** ListenRequest labels. */ - public labels: { [k: string]: string }; - - /** ListenRequest targetChange. */ - public targetChange?: ("addTarget"|"removeTarget"); - - /** - * Creates a new ListenRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns ListenRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IListenRequest): google.firestore.v1beta1.ListenRequest; - - /** - * Encodes the specified ListenRequest message. Does not implicitly {@link google.firestore.v1beta1.ListenRequest.verify|verify} messages. - * @param message ListenRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IListenRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListenRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListenRequest.verify|verify} messages. - * @param message ListenRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IListenRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListenRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListenRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ListenRequest; - - /** - * Decodes a ListenRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListenRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ListenRequest; - - /** - * Verifies a ListenRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListenRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenRequest; - - /** - * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. - * @param message ListenRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListenRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ListenResponse. */ - interface IListenResponse { - - /** ListenResponse targetChange */ - targetChange?: (google.firestore.v1beta1.ITargetChange|null); - - /** ListenResponse documentChange */ - documentChange?: (google.firestore.v1beta1.IDocumentChange|null); - - /** ListenResponse documentDelete */ - documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); - - /** ListenResponse documentRemove */ - documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); - - /** ListenResponse filter */ - filter?: (google.firestore.v1beta1.IExistenceFilter|null); - } - - /** Represents a ListenResponse. */ - class ListenResponse implements IListenResponse { - - /** - * Constructs a new ListenResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IListenResponse); - - /** ListenResponse targetChange. */ - public targetChange?: (google.firestore.v1beta1.ITargetChange|null); - - /** ListenResponse documentChange. */ - public documentChange?: (google.firestore.v1beta1.IDocumentChange|null); - - /** ListenResponse documentDelete. */ - public documentDelete?: (google.firestore.v1beta1.IDocumentDelete|null); - - /** ListenResponse documentRemove. */ - public documentRemove?: (google.firestore.v1beta1.IDocumentRemove|null); - - /** ListenResponse filter. */ - public filter?: (google.firestore.v1beta1.IExistenceFilter|null); - - /** ListenResponse responseType. */ - public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); - - /** - * Creates a new ListenResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns ListenResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IListenResponse): google.firestore.v1beta1.ListenResponse; - - /** - * Encodes the specified ListenResponse message. Does not implicitly {@link google.firestore.v1beta1.ListenResponse.verify|verify} messages. - * @param message ListenResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IListenResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListenResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListenResponse.verify|verify} messages. - * @param message ListenResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IListenResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListenResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListenResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ListenResponse; - - /** - * Decodes a ListenResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListenResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ListenResponse; - - /** - * Verifies a ListenResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListenResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListenResponse; - - /** - * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. - * @param message ListenResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListenResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Target. */ - interface ITarget { - - /** Target query */ - query?: (google.firestore.v1beta1.Target.IQueryTarget|null); - - /** Target documents */ - documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); - - /** Target resumeToken */ - resumeToken?: (Uint8Array|null); - - /** Target readTime */ - readTime?: (google.protobuf.ITimestamp|null); - - /** Target targetId */ - targetId?: (number|null); - - /** Target once */ - once?: (boolean|null); - } - - /** Represents a Target. */ - class Target implements ITarget { - - /** - * Constructs a new Target. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ITarget); - - /** Target query. */ - public query?: (google.firestore.v1beta1.Target.IQueryTarget|null); - - /** Target documents. */ - public documents?: (google.firestore.v1beta1.Target.IDocumentsTarget|null); - - /** Target resumeToken. */ - public resumeToken: Uint8Array; - - /** Target readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** Target targetId. */ - public targetId: number; - - /** Target once. */ - public once: boolean; - - /** Target targetType. */ - public targetType?: ("query"|"documents"); - - /** Target resumeType. */ - public resumeType?: ("resumeToken"|"readTime"); - - /** - * Creates a new Target instance using the specified properties. - * @param [properties] Properties to set - * @returns Target instance - */ - public static create(properties?: google.firestore.v1beta1.ITarget): google.firestore.v1beta1.Target; - - /** - * Encodes the specified Target message. Does not implicitly {@link google.firestore.v1beta1.Target.verify|verify} messages. - * @param message Target message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ITarget, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Target message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Target.verify|verify} messages. - * @param message Target message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ITarget, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Target message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Target - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Target; - - /** - * Decodes a Target message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Target - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Target; - - /** - * Verifies a Target message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Target message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Target - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target; - - /** - * Creates a plain object from a Target message. Also converts values to other types if specified. - * @param message Target - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Target to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace Target { - - /** Properties of a DocumentsTarget. */ - interface IDocumentsTarget { - - /** DocumentsTarget documents */ - documents?: (string[]|null); - } - - /** Represents a DocumentsTarget. */ - class DocumentsTarget implements IDocumentsTarget { - - /** - * Constructs a new DocumentsTarget. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.Target.IDocumentsTarget); - - /** DocumentsTarget documents. */ - public documents: string[]; - - /** - * Creates a new DocumentsTarget instance using the specified properties. - * @param [properties] Properties to set - * @returns DocumentsTarget instance - */ - public static create(properties?: google.firestore.v1beta1.Target.IDocumentsTarget): google.firestore.v1beta1.Target.DocumentsTarget; - - /** - * Encodes the specified DocumentsTarget message. Does not implicitly {@link google.firestore.v1beta1.Target.DocumentsTarget.verify|verify} messages. - * @param message DocumentsTarget message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.Target.IDocumentsTarget, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DocumentsTarget message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Target.DocumentsTarget.verify|verify} messages. - * @param message DocumentsTarget message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.Target.IDocumentsTarget, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DocumentsTarget message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DocumentsTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Target.DocumentsTarget; - - /** - * Decodes a DocumentsTarget message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DocumentsTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Target.DocumentsTarget; - - /** - * Verifies a DocumentsTarget message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentsTarget - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.DocumentsTarget; - - /** - * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. - * @param message DocumentsTarget - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DocumentsTarget to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a QueryTarget. */ - interface IQueryTarget { - - /** QueryTarget parent */ - parent?: (string|null); - - /** QueryTarget structuredQuery */ - structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); - } - - /** Represents a QueryTarget. */ - class QueryTarget implements IQueryTarget { - - /** - * Constructs a new QueryTarget. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.Target.IQueryTarget); - - /** QueryTarget parent. */ - public parent: string; - - /** QueryTarget structuredQuery. */ - public structuredQuery?: (google.firestore.v1beta1.IStructuredQuery|null); - - /** QueryTarget queryType. */ - public queryType?: "structuredQuery"; - - /** - * Creates a new QueryTarget instance using the specified properties. - * @param [properties] Properties to set - * @returns QueryTarget instance - */ - public static create(properties?: google.firestore.v1beta1.Target.IQueryTarget): google.firestore.v1beta1.Target.QueryTarget; - - /** - * Encodes the specified QueryTarget message. Does not implicitly {@link google.firestore.v1beta1.Target.QueryTarget.verify|verify} messages. - * @param message QueryTarget message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.Target.IQueryTarget, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified QueryTarget message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Target.QueryTarget.verify|verify} messages. - * @param message QueryTarget message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.Target.IQueryTarget, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a QueryTarget message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns QueryTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Target.QueryTarget; - - /** - * Decodes a QueryTarget message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns QueryTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Target.QueryTarget; - - /** - * Verifies a QueryTarget message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns QueryTarget - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Target.QueryTarget; - - /** - * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. - * @param message QueryTarget - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this QueryTarget to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a TargetChange. */ - interface ITargetChange { - - /** TargetChange targetChangeType */ - targetChangeType?: (google.firestore.v1beta1.TargetChange.TargetChangeType|null); - - /** TargetChange targetIds */ - targetIds?: (number[]|null); - - /** TargetChange cause */ - cause?: (google.rpc.IStatus|null); - - /** TargetChange resumeToken */ - resumeToken?: (Uint8Array|null); - - /** TargetChange readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a TargetChange. */ - class TargetChange implements ITargetChange { - - /** - * Constructs a new TargetChange. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ITargetChange); - - /** TargetChange targetChangeType. */ - public targetChangeType: google.firestore.v1beta1.TargetChange.TargetChangeType; - - /** TargetChange targetIds. */ - public targetIds: number[]; - - /** TargetChange cause. */ - public cause?: (google.rpc.IStatus|null); - - /** TargetChange resumeToken. */ - public resumeToken: Uint8Array; - - /** TargetChange readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** - * Creates a new TargetChange instance using the specified properties. - * @param [properties] Properties to set - * @returns TargetChange instance - */ - public static create(properties?: google.firestore.v1beta1.ITargetChange): google.firestore.v1beta1.TargetChange; - - /** - * Encodes the specified TargetChange message. Does not implicitly {@link google.firestore.v1beta1.TargetChange.verify|verify} messages. - * @param message TargetChange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ITargetChange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified TargetChange message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TargetChange.verify|verify} messages. - * @param message TargetChange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ITargetChange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a TargetChange message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns TargetChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.TargetChange; - - /** - * Decodes a TargetChange message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns TargetChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.TargetChange; - - /** - * Verifies a TargetChange message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns TargetChange - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TargetChange; - - /** - * Creates a plain object from a TargetChange message. Also converts values to other types if specified. - * @param message TargetChange - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this TargetChange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace TargetChange { - - /** TargetChangeType enum. */ - enum TargetChangeType { - NO_CHANGE = 0, - ADD = 1, - REMOVE = 2, - CURRENT = 3, - RESET = 4 - } - } - - /** Properties of a ListCollectionIdsRequest. */ - interface IListCollectionIdsRequest { - - /** ListCollectionIdsRequest parent */ - parent?: (string|null); - - /** ListCollectionIdsRequest pageSize */ - pageSize?: (number|null); - - /** ListCollectionIdsRequest pageToken */ - pageToken?: (string|null); - } - - /** Represents a ListCollectionIdsRequest. */ - class ListCollectionIdsRequest implements IListCollectionIdsRequest { - - /** - * Constructs a new ListCollectionIdsRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IListCollectionIdsRequest); - - /** ListCollectionIdsRequest parent. */ - public parent: string; - - /** ListCollectionIdsRequest pageSize. */ - public pageSize: number; - - /** ListCollectionIdsRequest pageToken. */ - public pageToken: string; - - /** - * Creates a new ListCollectionIdsRequest instance using the specified properties. - * @param [properties] Properties to set - * @returns ListCollectionIdsRequest instance - */ - public static create(properties?: google.firestore.v1beta1.IListCollectionIdsRequest): google.firestore.v1beta1.ListCollectionIdsRequest; - - /** - * Encodes the specified ListCollectionIdsRequest message. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsRequest.verify|verify} messages. - * @param message ListCollectionIdsRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IListCollectionIdsRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListCollectionIdsRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsRequest.verify|verify} messages. - * @param message ListCollectionIdsRequest message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IListCollectionIdsRequest, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListCollectionIdsRequest message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListCollectionIdsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ListCollectionIdsRequest; - - /** - * Decodes a ListCollectionIdsRequest message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListCollectionIdsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ListCollectionIdsRequest; - - /** - * Verifies a ListCollectionIdsRequest message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListCollectionIdsRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsRequest; - - /** - * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. - * @param message ListCollectionIdsRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListCollectionIdsRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ListCollectionIdsResponse. */ - interface IListCollectionIdsResponse { - - /** ListCollectionIdsResponse collectionIds */ - collectionIds?: (string[]|null); - - /** ListCollectionIdsResponse nextPageToken */ - nextPageToken?: (string|null); - } - - /** Represents a ListCollectionIdsResponse. */ - class ListCollectionIdsResponse implements IListCollectionIdsResponse { - - /** - * Constructs a new ListCollectionIdsResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IListCollectionIdsResponse); - - /** ListCollectionIdsResponse collectionIds. */ - public collectionIds: string[]; - - /** ListCollectionIdsResponse nextPageToken. */ - public nextPageToken: string; - - /** - * Creates a new ListCollectionIdsResponse instance using the specified properties. - * @param [properties] Properties to set - * @returns ListCollectionIdsResponse instance - */ - public static create(properties?: google.firestore.v1beta1.IListCollectionIdsResponse): google.firestore.v1beta1.ListCollectionIdsResponse; - - /** - * Encodes the specified ListCollectionIdsResponse message. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsResponse.verify|verify} messages. - * @param message ListCollectionIdsResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IListCollectionIdsResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListCollectionIdsResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsResponse.verify|verify} messages. - * @param message ListCollectionIdsResponse message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IListCollectionIdsResponse, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListCollectionIdsResponse message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListCollectionIdsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ListCollectionIdsResponse; - - /** - * Decodes a ListCollectionIdsResponse message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListCollectionIdsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ListCollectionIdsResponse; - - /** - * Verifies a ListCollectionIdsResponse message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListCollectionIdsResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ListCollectionIdsResponse; - - /** - * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. - * @param message ListCollectionIdsResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListCollectionIdsResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DocumentMask. */ - interface IDocumentMask { - - /** DocumentMask fieldPaths */ - fieldPaths?: (string[]|null); - } - - /** Represents a DocumentMask. */ - class DocumentMask implements IDocumentMask { - - /** - * Constructs a new DocumentMask. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDocumentMask); - - /** DocumentMask fieldPaths. */ - public fieldPaths: string[]; - - /** - * Creates a new DocumentMask instance using the specified properties. - * @param [properties] Properties to set - * @returns DocumentMask instance - */ - public static create(properties?: google.firestore.v1beta1.IDocumentMask): google.firestore.v1beta1.DocumentMask; - - /** - * Encodes the specified DocumentMask message. Does not implicitly {@link google.firestore.v1beta1.DocumentMask.verify|verify} messages. - * @param message DocumentMask message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDocumentMask, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DocumentMask message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentMask.verify|verify} messages. - * @param message DocumentMask message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDocumentMask, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DocumentMask message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DocumentMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DocumentMask; - - /** - * Decodes a DocumentMask message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DocumentMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DocumentMask; - - /** - * Verifies a DocumentMask message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentMask - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentMask; - - /** - * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. - * @param message DocumentMask - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DocumentMask to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Precondition. */ - interface IPrecondition { - - /** Precondition exists */ - exists?: (boolean|null); - - /** Precondition updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a Precondition. */ - class Precondition implements IPrecondition { - - /** - * Constructs a new Precondition. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IPrecondition); - - /** Precondition exists. */ - public exists: boolean; - - /** Precondition updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); - - /** Precondition conditionType. */ - public conditionType?: ("exists"|"updateTime"); - - /** - * Creates a new Precondition instance using the specified properties. - * @param [properties] Properties to set - * @returns Precondition instance - */ - public static create(properties?: google.firestore.v1beta1.IPrecondition): google.firestore.v1beta1.Precondition; - - /** - * Encodes the specified Precondition message. Does not implicitly {@link google.firestore.v1beta1.Precondition.verify|verify} messages. - * @param message Precondition message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IPrecondition, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Precondition message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Precondition.verify|verify} messages. - * @param message Precondition message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IPrecondition, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Precondition message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Precondition - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Precondition; - - /** - * Decodes a Precondition message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Precondition - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Precondition; - - /** - * Verifies a Precondition message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Precondition message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Precondition - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Precondition; - - /** - * Creates a plain object from a Precondition message. Also converts values to other types if specified. - * @param message Precondition - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Precondition to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a TransactionOptions. */ - interface ITransactionOptions { - - /** TransactionOptions readOnly */ - readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); - - /** TransactionOptions readWrite */ - readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); - } - - /** Represents a TransactionOptions. */ - class TransactionOptions implements ITransactionOptions { - - /** - * Constructs a new TransactionOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ITransactionOptions); - - /** TransactionOptions readOnly. */ - public readOnly?: (google.firestore.v1beta1.TransactionOptions.IReadOnly|null); - - /** TransactionOptions readWrite. */ - public readWrite?: (google.firestore.v1beta1.TransactionOptions.IReadWrite|null); - - /** TransactionOptions mode. */ - public mode?: ("readOnly"|"readWrite"); - - /** - * Creates a new TransactionOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns TransactionOptions instance - */ - public static create(properties?: google.firestore.v1beta1.ITransactionOptions): google.firestore.v1beta1.TransactionOptions; - - /** - * Encodes the specified TransactionOptions message. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.verify|verify} messages. - * @param message TransactionOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ITransactionOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified TransactionOptions message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.verify|verify} messages. - * @param message TransactionOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ITransactionOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a TransactionOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns TransactionOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.TransactionOptions; - - /** - * Decodes a TransactionOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns TransactionOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.TransactionOptions; - - /** - * Verifies a TransactionOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns TransactionOptions - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions; - - /** - * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. - * @param message TransactionOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this TransactionOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace TransactionOptions { - - /** Properties of a ReadWrite. */ - interface IReadWrite { - - /** ReadWrite retryTransaction */ - retryTransaction?: (Uint8Array|null); - } - - /** Represents a ReadWrite. */ - class ReadWrite implements IReadWrite { - - /** - * Constructs a new ReadWrite. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadWrite); - - /** ReadWrite retryTransaction. */ - public retryTransaction: Uint8Array; - - /** - * Creates a new ReadWrite instance using the specified properties. - * @param [properties] Properties to set - * @returns ReadWrite instance - */ - public static create(properties?: google.firestore.v1beta1.TransactionOptions.IReadWrite): google.firestore.v1beta1.TransactionOptions.ReadWrite; - - /** - * Encodes the specified ReadWrite message. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadWrite.verify|verify} messages. - * @param message ReadWrite message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.TransactionOptions.IReadWrite, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ReadWrite message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadWrite.verify|verify} messages. - * @param message ReadWrite message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.TransactionOptions.IReadWrite, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ReadWrite message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ReadWrite - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.TransactionOptions.ReadWrite; - - /** - * Decodes a ReadWrite message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ReadWrite - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.TransactionOptions.ReadWrite; - - /** - * Verifies a ReadWrite message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ReadWrite - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadWrite; - - /** - * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. - * @param message ReadWrite - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ReadWrite to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ReadOnly. */ - interface IReadOnly { - - /** ReadOnly readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a ReadOnly. */ - class ReadOnly implements IReadOnly { - - /** - * Constructs a new ReadOnly. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.TransactionOptions.IReadOnly); - - /** ReadOnly readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** ReadOnly consistencySelector. */ - public consistencySelector?: "readTime"; - - /** - * Creates a new ReadOnly instance using the specified properties. - * @param [properties] Properties to set - * @returns ReadOnly instance - */ - public static create(properties?: google.firestore.v1beta1.TransactionOptions.IReadOnly): google.firestore.v1beta1.TransactionOptions.ReadOnly; - - /** - * Encodes the specified ReadOnly message. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadOnly.verify|verify} messages. - * @param message ReadOnly message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.TransactionOptions.IReadOnly, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ReadOnly message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadOnly.verify|verify} messages. - * @param message ReadOnly message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.TransactionOptions.IReadOnly, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ReadOnly message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ReadOnly - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.TransactionOptions.ReadOnly; - - /** - * Decodes a ReadOnly message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ReadOnly - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.TransactionOptions.ReadOnly; - - /** - * Verifies a ReadOnly message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ReadOnly - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.TransactionOptions.ReadOnly; - - /** - * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. - * @param message ReadOnly - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ReadOnly to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a Document. */ - interface IDocument { - - /** Document name */ - name?: (string|null); - - /** Document fields */ - fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); - - /** Document createTime */ - createTime?: (google.protobuf.ITimestamp|null); - - /** Document updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a Document. */ - class Document implements IDocument { - - /** - * Constructs a new Document. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDocument); - - /** Document name. */ - public name: string; - - /** Document fields. */ - public fields: { [k: string]: google.firestore.v1beta1.IValue }; - - /** Document createTime. */ - public createTime?: (google.protobuf.ITimestamp|null); - - /** Document updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); - - /** - * Creates a new Document instance using the specified properties. - * @param [properties] Properties to set - * @returns Document instance - */ - public static create(properties?: google.firestore.v1beta1.IDocument): google.firestore.v1beta1.Document; - - /** - * Encodes the specified Document message. Does not implicitly {@link google.firestore.v1beta1.Document.verify|verify} messages. - * @param message Document message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDocument, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Document message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Document.verify|verify} messages. - * @param message Document message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDocument, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Document message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Document - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Document; - - /** - * Decodes a Document message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Document - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Document; - - /** - * Verifies a Document message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Document message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Document - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Document; - - /** - * Creates a plain object from a Document message. Also converts values to other types if specified. - * @param message Document - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Document to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Value. */ - interface IValue { - - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); - - /** Value booleanValue */ - booleanValue?: (boolean|null); - - /** Value integerValue */ - integerValue?: (number|string|null); - - /** Value doubleValue */ - doubleValue?: (number|null); - - /** Value timestampValue */ - timestampValue?: (google.protobuf.ITimestamp|null); - - /** Value stringValue */ - stringValue?: (string|null); - - /** Value bytesValue */ - bytesValue?: (Uint8Array|null); - - /** Value referenceValue */ - referenceValue?: (string|null); - - /** Value geoPointValue */ - geoPointValue?: (google.type.ILatLng|null); - - /** Value arrayValue */ - arrayValue?: (google.firestore.v1beta1.IArrayValue|null); - - /** Value mapValue */ - mapValue?: (google.firestore.v1beta1.IMapValue|null); - } - - /** Represents a Value. */ - class Value implements IValue { - - /** - * Constructs a new Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IValue); - - /** Value nullValue. */ - public nullValue: google.protobuf.NullValue; - - /** Value booleanValue. */ - public booleanValue: boolean; - - /** Value integerValue. */ - public integerValue: (number|string); - - /** Value doubleValue. */ - public doubleValue: number; - - /** Value timestampValue. */ - public timestampValue?: (google.protobuf.ITimestamp|null); - - /** Value stringValue. */ - public stringValue: string; - - /** Value bytesValue. */ - public bytesValue: Uint8Array; - - /** Value referenceValue. */ - public referenceValue: string; - - /** Value geoPointValue. */ - public geoPointValue?: (google.type.ILatLng|null); - - /** Value arrayValue. */ - public arrayValue?: (google.firestore.v1beta1.IArrayValue|null); - - /** Value mapValue. */ - public mapValue?: (google.firestore.v1beta1.IMapValue|null); - - /** Value valueType. */ - public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); - - /** - * Creates a new Value instance using the specified properties. - * @param [properties] Properties to set - * @returns Value instance - */ - public static create(properties?: google.firestore.v1beta1.IValue): google.firestore.v1beta1.Value; - - /** - * Encodes the specified Value message. Does not implicitly {@link google.firestore.v1beta1.Value.verify|verify} messages. - * @param message Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Value message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Value.verify|verify} messages. - * @param message Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Value message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Value; - - /** - * Decodes a Value message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Value; - - /** - * Verifies a Value message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Value - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Value; - - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an ArrayValue. */ - interface IArrayValue { - - /** ArrayValue values */ - values?: (google.firestore.v1beta1.IValue[]|null); - } - - /** Represents an ArrayValue. */ - class ArrayValue implements IArrayValue { - - /** - * Constructs a new ArrayValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IArrayValue); - - /** ArrayValue values. */ - public values: google.firestore.v1beta1.IValue[]; - - /** - * Creates a new ArrayValue instance using the specified properties. - * @param [properties] Properties to set - * @returns ArrayValue instance - */ - public static create(properties?: google.firestore.v1beta1.IArrayValue): google.firestore.v1beta1.ArrayValue; - - /** - * Encodes the specified ArrayValue message. Does not implicitly {@link google.firestore.v1beta1.ArrayValue.verify|verify} messages. - * @param message ArrayValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IArrayValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ArrayValue message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ArrayValue.verify|verify} messages. - * @param message ArrayValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IArrayValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an ArrayValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ArrayValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ArrayValue; - - /** - * Decodes an ArrayValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ArrayValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ArrayValue; - - /** - * Verifies an ArrayValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ArrayValue - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ArrayValue; - - /** - * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. - * @param message ArrayValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ArrayValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a MapValue. */ - interface IMapValue { - - /** MapValue fields */ - fields?: ({ [k: string]: google.firestore.v1beta1.IValue }|null); - } - - /** Represents a MapValue. */ - class MapValue implements IMapValue { - - /** - * Constructs a new MapValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IMapValue); - - /** MapValue fields. */ - public fields: { [k: string]: google.firestore.v1beta1.IValue }; - - /** - * Creates a new MapValue instance using the specified properties. - * @param [properties] Properties to set - * @returns MapValue instance - */ - public static create(properties?: google.firestore.v1beta1.IMapValue): google.firestore.v1beta1.MapValue; - - /** - * Encodes the specified MapValue message. Does not implicitly {@link google.firestore.v1beta1.MapValue.verify|verify} messages. - * @param message MapValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IMapValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified MapValue message, length delimited. Does not implicitly {@link google.firestore.v1beta1.MapValue.verify|verify} messages. - * @param message MapValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IMapValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a MapValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns MapValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.MapValue; - - /** - * Decodes a MapValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns MapValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.MapValue; - - /** - * Verifies a MapValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a MapValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MapValue - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.MapValue; - - /** - * Creates a plain object from a MapValue message. Also converts values to other types if specified. - * @param message MapValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this MapValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a StructuredQuery. */ - interface IStructuredQuery { - - /** StructuredQuery select */ - select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); - - /** StructuredQuery from */ - from?: (google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]|null); - - /** StructuredQuery where */ - where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); - - /** StructuredQuery orderBy */ - orderBy?: (google.firestore.v1beta1.StructuredQuery.IOrder[]|null); - - /** StructuredQuery startAt */ - startAt?: (google.firestore.v1beta1.ICursor|null); - - /** StructuredQuery endAt */ - endAt?: (google.firestore.v1beta1.ICursor|null); - - /** StructuredQuery offset */ - offset?: (number|null); - - /** StructuredQuery limit */ - limit?: (google.protobuf.IInt32Value|null); - } - - /** Represents a StructuredQuery. */ - class StructuredQuery implements IStructuredQuery { - - /** - * Constructs a new StructuredQuery. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IStructuredQuery); - - /** StructuredQuery select. */ - public select?: (google.firestore.v1beta1.StructuredQuery.IProjection|null); - - /** StructuredQuery from. */ - public from: google.firestore.v1beta1.StructuredQuery.ICollectionSelector[]; - - /** StructuredQuery where. */ - public where?: (google.firestore.v1beta1.StructuredQuery.IFilter|null); - - /** StructuredQuery orderBy. */ - public orderBy: google.firestore.v1beta1.StructuredQuery.IOrder[]; - - /** StructuredQuery startAt. */ - public startAt?: (google.firestore.v1beta1.ICursor|null); - - /** StructuredQuery endAt. */ - public endAt?: (google.firestore.v1beta1.ICursor|null); - - /** StructuredQuery offset. */ - public offset: number; - - /** StructuredQuery limit. */ - public limit?: (google.protobuf.IInt32Value|null); - - /** - * Creates a new StructuredQuery instance using the specified properties. - * @param [properties] Properties to set - * @returns StructuredQuery instance - */ - public static create(properties?: google.firestore.v1beta1.IStructuredQuery): google.firestore.v1beta1.StructuredQuery; - - /** - * Encodes the specified StructuredQuery message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.verify|verify} messages. - * @param message StructuredQuery message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IStructuredQuery, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified StructuredQuery message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.verify|verify} messages. - * @param message StructuredQuery message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IStructuredQuery, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a StructuredQuery message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns StructuredQuery - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery; - - /** - * Decodes a StructuredQuery message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns StructuredQuery - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery; - - /** - * Verifies a StructuredQuery message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StructuredQuery - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery; - - /** - * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. - * @param message StructuredQuery - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this StructuredQuery to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace StructuredQuery { - - /** Properties of a CollectionSelector. */ - interface ICollectionSelector { - - /** CollectionSelector collectionId */ - collectionId?: (string|null); - - /** CollectionSelector allDescendants */ - allDescendants?: (boolean|null); - } - - /** Represents a CollectionSelector. */ - class CollectionSelector implements ICollectionSelector { - - /** - * Constructs a new CollectionSelector. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICollectionSelector); - - /** CollectionSelector collectionId. */ - public collectionId: string; - - /** CollectionSelector allDescendants. */ - public allDescendants: boolean; - - /** - * Creates a new CollectionSelector instance using the specified properties. - * @param [properties] Properties to set - * @returns CollectionSelector instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.ICollectionSelector): google.firestore.v1beta1.StructuredQuery.CollectionSelector; - - /** - * Encodes the specified CollectionSelector message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CollectionSelector.verify|verify} messages. - * @param message CollectionSelector message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.ICollectionSelector, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified CollectionSelector message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CollectionSelector.verify|verify} messages. - * @param message CollectionSelector message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.ICollectionSelector, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CollectionSelector message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns CollectionSelector - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.CollectionSelector; - - /** - * Decodes a CollectionSelector message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns CollectionSelector - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.CollectionSelector; - - /** - * Verifies a CollectionSelector message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CollectionSelector - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CollectionSelector; - - /** - * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. - * @param message CollectionSelector - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CollectionSelector to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Filter. */ - interface IFilter { - - /** Filter compositeFilter */ - compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); - - /** Filter fieldFilter */ - fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); - - /** Filter unaryFilter */ - unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); - } - - /** Represents a Filter. */ - class Filter implements IFilter { - - /** - * Constructs a new Filter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFilter); - - /** Filter compositeFilter. */ - public compositeFilter?: (google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null); - - /** Filter fieldFilter. */ - public fieldFilter?: (google.firestore.v1beta1.StructuredQuery.IFieldFilter|null); - - /** Filter unaryFilter. */ - public unaryFilter?: (google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null); - - /** Filter filterType. */ - public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); - - /** - * Creates a new Filter instance using the specified properties. - * @param [properties] Properties to set - * @returns Filter instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.IFilter): google.firestore.v1beta1.StructuredQuery.Filter; - - /** - * Encodes the specified Filter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Filter.verify|verify} messages. - * @param message Filter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.IFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Filter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Filter.verify|verify} messages. - * @param message Filter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.IFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Filter message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Filter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.Filter; - - /** - * Decodes a Filter message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Filter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.Filter; - - /** - * Verifies a Filter message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Filter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Filter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Filter; - - /** - * Creates a plain object from a Filter message. Also converts values to other types if specified. - * @param message Filter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Filter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a CompositeFilter. */ - interface ICompositeFilter { - - /** CompositeFilter op */ - op?: (google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null); - - /** CompositeFilter filters */ - filters?: (google.firestore.v1beta1.StructuredQuery.IFilter[]|null); - } - - /** Represents a CompositeFilter. */ - class CompositeFilter implements ICompositeFilter { - - /** - * Constructs a new CompositeFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.ICompositeFilter); - - /** CompositeFilter op. */ - public op: google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator; - - /** CompositeFilter filters. */ - public filters: google.firestore.v1beta1.StructuredQuery.IFilter[]; - - /** - * Creates a new CompositeFilter instance using the specified properties. - * @param [properties] Properties to set - * @returns CompositeFilter instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.ICompositeFilter): google.firestore.v1beta1.StructuredQuery.CompositeFilter; - - /** - * Encodes the specified CompositeFilter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CompositeFilter.verify|verify} messages. - * @param message CompositeFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.ICompositeFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified CompositeFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CompositeFilter.verify|verify} messages. - * @param message CompositeFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.ICompositeFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CompositeFilter message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns CompositeFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.CompositeFilter; - - /** - * Decodes a CompositeFilter message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns CompositeFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.CompositeFilter; - - /** - * Verifies a CompositeFilter message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CompositeFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.CompositeFilter; - - /** - * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. - * @param message CompositeFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CompositeFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace CompositeFilter { - - /** Operator enum. */ - enum Operator { - OPERATOR_UNSPECIFIED = 0, - AND = 1 - } - } - - /** Properties of a FieldFilter. */ - interface IFieldFilter { - - /** FieldFilter field */ - field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); - - /** FieldFilter op */ - op?: (google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null); - - /** FieldFilter value */ - value?: (google.firestore.v1beta1.IValue|null); - } - - /** Represents a FieldFilter. */ - class FieldFilter implements IFieldFilter { - - /** - * Constructs a new FieldFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldFilter); - - /** FieldFilter field. */ - public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); - - /** FieldFilter op. */ - public op: google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator; - - /** FieldFilter value. */ - public value?: (google.firestore.v1beta1.IValue|null); - - /** - * Creates a new FieldFilter instance using the specified properties. - * @param [properties] Properties to set - * @returns FieldFilter instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.IFieldFilter): google.firestore.v1beta1.StructuredQuery.FieldFilter; - - /** - * Encodes the specified FieldFilter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldFilter.verify|verify} messages. - * @param message FieldFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.IFieldFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FieldFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldFilter.verify|verify} messages. - * @param message FieldFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.IFieldFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FieldFilter message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FieldFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.FieldFilter; - - /** - * Decodes a FieldFilter message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FieldFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.FieldFilter; - - /** - * Verifies a FieldFilter message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldFilter; - - /** - * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. - * @param message FieldFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace FieldFilter { - - /** Operator enum. */ - enum Operator { - OPERATOR_UNSPECIFIED = 0, - LESS_THAN = 1, - LESS_THAN_OR_EQUAL = 2, - GREATER_THAN = 3, - GREATER_THAN_OR_EQUAL = 4, - EQUAL = 5, - ARRAY_CONTAINS = 7 - } - } - - /** Properties of an UnaryFilter. */ - interface IUnaryFilter { - - /** UnaryFilter op */ - op?: (google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null); - - /** UnaryFilter field */ - field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); - } - - /** Represents an UnaryFilter. */ - class UnaryFilter implements IUnaryFilter { - - /** - * Constructs a new UnaryFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.IUnaryFilter); - - /** UnaryFilter op. */ - public op: google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator; - - /** UnaryFilter field. */ - public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); - - /** UnaryFilter operandType. */ - public operandType?: "field"; - - /** - * Creates a new UnaryFilter instance using the specified properties. - * @param [properties] Properties to set - * @returns UnaryFilter instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.IUnaryFilter): google.firestore.v1beta1.StructuredQuery.UnaryFilter; - - /** - * Encodes the specified UnaryFilter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.UnaryFilter.verify|verify} messages. - * @param message UnaryFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.IUnaryFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified UnaryFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.UnaryFilter.verify|verify} messages. - * @param message UnaryFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.IUnaryFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an UnaryFilter message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns UnaryFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.UnaryFilter; - - /** - * Decodes an UnaryFilter message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns UnaryFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.UnaryFilter; - - /** - * Verifies an UnaryFilter message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UnaryFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.UnaryFilter; - - /** - * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. - * @param message UnaryFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this UnaryFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace UnaryFilter { - - /** Operator enum. */ - enum Operator { - OPERATOR_UNSPECIFIED = 0, - IS_NAN = 2, - IS_NULL = 3 - } - } - - /** Properties of an Order. */ - interface IOrder { - - /** Order field */ - field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); - - /** Order direction */ - direction?: (google.firestore.v1beta1.StructuredQuery.Direction|null); - } - - /** Represents an Order. */ - class Order implements IOrder { - - /** - * Constructs a new Order. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.IOrder); - - /** Order field. */ - public field?: (google.firestore.v1beta1.StructuredQuery.IFieldReference|null); - - /** Order direction. */ - public direction: google.firestore.v1beta1.StructuredQuery.Direction; - - /** - * Creates a new Order instance using the specified properties. - * @param [properties] Properties to set - * @returns Order instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.IOrder): google.firestore.v1beta1.StructuredQuery.Order; - - /** - * Encodes the specified Order message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Order.verify|verify} messages. - * @param message Order message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.IOrder, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Order message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Order.verify|verify} messages. - * @param message Order message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.IOrder, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Order message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Order - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.Order; - - /** - * Decodes an Order message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Order - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.Order; - - /** - * Verifies an Order message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an Order message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Order - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Order; - - /** - * Creates a plain object from an Order message. Also converts values to other types if specified. - * @param message Order - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Order to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a FieldReference. */ - interface IFieldReference { - - /** FieldReference fieldPath */ - fieldPath?: (string|null); - } - - /** Represents a FieldReference. */ - class FieldReference implements IFieldReference { - - /** - * Constructs a new FieldReference. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.IFieldReference); - - /** FieldReference fieldPath. */ - public fieldPath: string; - - /** - * Creates a new FieldReference instance using the specified properties. - * @param [properties] Properties to set - * @returns FieldReference instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.IFieldReference): google.firestore.v1beta1.StructuredQuery.FieldReference; - - /** - * Encodes the specified FieldReference message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldReference.verify|verify} messages. - * @param message FieldReference message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.IFieldReference, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FieldReference message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldReference.verify|verify} messages. - * @param message FieldReference message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.IFieldReference, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FieldReference message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FieldReference - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.FieldReference; - - /** - * Decodes a FieldReference message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FieldReference - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.FieldReference; - - /** - * Verifies a FieldReference message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldReference - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.FieldReference; - - /** - * Creates a plain object from a FieldReference message. Also converts values to other types if specified. - * @param message FieldReference - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldReference to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Projection. */ - interface IProjection { - - /** Projection fields */ - fields?: (google.firestore.v1beta1.StructuredQuery.IFieldReference[]|null); - } - - /** Represents a Projection. */ - class Projection implements IProjection { - - /** - * Constructs a new Projection. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.StructuredQuery.IProjection); - - /** Projection fields. */ - public fields: google.firestore.v1beta1.StructuredQuery.IFieldReference[]; - - /** - * Creates a new Projection instance using the specified properties. - * @param [properties] Properties to set - * @returns Projection instance - */ - public static create(properties?: google.firestore.v1beta1.StructuredQuery.IProjection): google.firestore.v1beta1.StructuredQuery.Projection; - - /** - * Encodes the specified Projection message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Projection.verify|verify} messages. - * @param message Projection message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.StructuredQuery.IProjection, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Projection message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Projection.verify|verify} messages. - * @param message Projection message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.StructuredQuery.IProjection, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Projection message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Projection - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.StructuredQuery.Projection; - - /** - * Decodes a Projection message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Projection - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.StructuredQuery.Projection; - - /** - * Verifies a Projection message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Projection message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Projection - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.StructuredQuery.Projection; - - /** - * Creates a plain object from a Projection message. Also converts values to other types if specified. - * @param message Projection - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Projection to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Direction enum. */ - enum Direction { - DIRECTION_UNSPECIFIED = 0, - ASCENDING = 1, - DESCENDING = 2 - } - } - - /** Properties of a Cursor. */ - interface ICursor { - - /** Cursor values */ - values?: (google.firestore.v1beta1.IValue[]|null); - - /** Cursor before */ - before?: (boolean|null); - } - - /** Represents a Cursor. */ - class Cursor implements ICursor { - - /** - * Constructs a new Cursor. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.ICursor); - - /** Cursor values. */ - public values: google.firestore.v1beta1.IValue[]; - - /** Cursor before. */ - public before: boolean; - - /** - * Creates a new Cursor instance using the specified properties. - * @param [properties] Properties to set - * @returns Cursor instance - */ - public static create(properties?: google.firestore.v1beta1.ICursor): google.firestore.v1beta1.Cursor; - - /** - * Encodes the specified Cursor message. Does not implicitly {@link google.firestore.v1beta1.Cursor.verify|verify} messages. - * @param message Cursor message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.ICursor, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Cursor message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Cursor.verify|verify} messages. - * @param message Cursor message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.ICursor, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Cursor message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Cursor - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Cursor; - - /** - * Decodes a Cursor message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Cursor - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Cursor; - - /** - * Verifies a Cursor message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Cursor message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Cursor - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Cursor; - - /** - * Creates a plain object from a Cursor message. Also converts values to other types if specified. - * @param message Cursor - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Cursor to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Write. */ - interface IWrite { - - /** Write update */ - update?: (google.firestore.v1beta1.IDocument|null); - - /** Write delete */ - "delete"?: (string|null); - - /** Write transform */ - transform?: (google.firestore.v1beta1.IDocumentTransform|null); - - /** Write updateMask */ - updateMask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** Write currentDocument */ - currentDocument?: (google.firestore.v1beta1.IPrecondition|null); - } - - /** Represents a Write. */ - class Write implements IWrite { - - /** - * Constructs a new Write. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IWrite); - - /** Write update. */ - public update?: (google.firestore.v1beta1.IDocument|null); - - /** Write delete. */ - public delete: string; - - /** Write transform. */ - public transform?: (google.firestore.v1beta1.IDocumentTransform|null); - - /** Write updateMask. */ - public updateMask?: (google.firestore.v1beta1.IDocumentMask|null); - - /** Write currentDocument. */ - public currentDocument?: (google.firestore.v1beta1.IPrecondition|null); - - /** Write operation. */ - public operation?: ("update"|"delete"|"transform"); - - /** - * Creates a new Write instance using the specified properties. - * @param [properties] Properties to set - * @returns Write instance - */ - public static create(properties?: google.firestore.v1beta1.IWrite): google.firestore.v1beta1.Write; - - /** - * Encodes the specified Write message. Does not implicitly {@link google.firestore.v1beta1.Write.verify|verify} messages. - * @param message Write message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IWrite, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Write message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Write.verify|verify} messages. - * @param message Write message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IWrite, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Write message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Write - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.Write; - - /** - * Decodes a Write message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Write - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.Write; - - /** - * Verifies a Write message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Write message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Write - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.Write; - - /** - * Creates a plain object from a Write message. Also converts values to other types if specified. - * @param message Write - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Write to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DocumentTransform. */ - interface IDocumentTransform { - - /** DocumentTransform document */ - document?: (string|null); - - /** DocumentTransform fieldTransforms */ - fieldTransforms?: (google.firestore.v1beta1.DocumentTransform.IFieldTransform[]|null); - } - - /** Represents a DocumentTransform. */ - class DocumentTransform implements IDocumentTransform { - - /** - * Constructs a new DocumentTransform. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDocumentTransform); - - /** DocumentTransform document. */ - public document: string; - - /** DocumentTransform fieldTransforms. */ - public fieldTransforms: google.firestore.v1beta1.DocumentTransform.IFieldTransform[]; - - /** - * Creates a new DocumentTransform instance using the specified properties. - * @param [properties] Properties to set - * @returns DocumentTransform instance - */ - public static create(properties?: google.firestore.v1beta1.IDocumentTransform): google.firestore.v1beta1.DocumentTransform; - - /** - * Encodes the specified DocumentTransform message. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.verify|verify} messages. - * @param message DocumentTransform message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDocumentTransform, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DocumentTransform message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.verify|verify} messages. - * @param message DocumentTransform message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDocumentTransform, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DocumentTransform message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DocumentTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DocumentTransform; - - /** - * Decodes a DocumentTransform message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DocumentTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DocumentTransform; - - /** - * Verifies a DocumentTransform message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentTransform - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform; - - /** - * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. - * @param message DocumentTransform - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DocumentTransform to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace DocumentTransform { - - /** Properties of a FieldTransform. */ - interface IFieldTransform { - - /** FieldTransform fieldPath */ - fieldPath?: (string|null); - - /** FieldTransform setToServerValue */ - setToServerValue?: (google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null); - - /** FieldTransform appendMissingElements */ - appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); - - /** FieldTransform removeAllFromArray */ - removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); - } - - /** Represents a FieldTransform. */ - class FieldTransform implements IFieldTransform { - - /** - * Constructs a new FieldTransform. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.DocumentTransform.IFieldTransform); - - /** FieldTransform fieldPath. */ - public fieldPath: string; - - /** FieldTransform setToServerValue. */ - public setToServerValue: google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue; - - /** FieldTransform appendMissingElements. */ - public appendMissingElements?: (google.firestore.v1beta1.IArrayValue|null); - - /** FieldTransform removeAllFromArray. */ - public removeAllFromArray?: (google.firestore.v1beta1.IArrayValue|null); - - /** FieldTransform transformType. */ - public transformType?: ("setToServerValue"|"appendMissingElements"|"removeAllFromArray"); - - /** - * Creates a new FieldTransform instance using the specified properties. - * @param [properties] Properties to set - * @returns FieldTransform instance - */ - public static create(properties?: google.firestore.v1beta1.DocumentTransform.IFieldTransform): google.firestore.v1beta1.DocumentTransform.FieldTransform; - - /** - * Encodes the specified FieldTransform message. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.FieldTransform.verify|verify} messages. - * @param message FieldTransform message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.DocumentTransform.IFieldTransform, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FieldTransform message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.FieldTransform.verify|verify} messages. - * @param message FieldTransform message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.DocumentTransform.IFieldTransform, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FieldTransform message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FieldTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DocumentTransform.FieldTransform; - - /** - * Decodes a FieldTransform message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FieldTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DocumentTransform.FieldTransform; - - /** - * Verifies a FieldTransform message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldTransform - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentTransform.FieldTransform; - - /** - * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. - * @param message FieldTransform - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldTransform to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace FieldTransform { - - /** ServerValue enum. */ - enum ServerValue { - SERVER_VALUE_UNSPECIFIED = 0, - REQUEST_TIME = 1 - } - } - } - - /** Properties of a WriteResult. */ - interface IWriteResult { - - /** WriteResult updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - - /** WriteResult transformResults */ - transformResults?: (google.firestore.v1beta1.IValue[]|null); - } - - /** Represents a WriteResult. */ - class WriteResult implements IWriteResult { - - /** - * Constructs a new WriteResult. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IWriteResult); - - /** WriteResult updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); - - /** WriteResult transformResults. */ - public transformResults: google.firestore.v1beta1.IValue[]; - - /** - * Creates a new WriteResult instance using the specified properties. - * @param [properties] Properties to set - * @returns WriteResult instance - */ - public static create(properties?: google.firestore.v1beta1.IWriteResult): google.firestore.v1beta1.WriteResult; - - /** - * Encodes the specified WriteResult message. Does not implicitly {@link google.firestore.v1beta1.WriteResult.verify|verify} messages. - * @param message WriteResult message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IWriteResult, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified WriteResult message, length delimited. Does not implicitly {@link google.firestore.v1beta1.WriteResult.verify|verify} messages. - * @param message WriteResult message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IWriteResult, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a WriteResult message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns WriteResult - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.WriteResult; - - /** - * Decodes a WriteResult message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns WriteResult - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.WriteResult; - - /** - * Verifies a WriteResult message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteResult - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.WriteResult; - - /** - * Creates a plain object from a WriteResult message. Also converts values to other types if specified. - * @param message WriteResult - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this WriteResult to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DocumentChange. */ - interface IDocumentChange { - - /** DocumentChange document */ - document?: (google.firestore.v1beta1.IDocument|null); - - /** DocumentChange targetIds */ - targetIds?: (number[]|null); - - /** DocumentChange removedTargetIds */ - removedTargetIds?: (number[]|null); - } - - /** Represents a DocumentChange. */ - class DocumentChange implements IDocumentChange { - - /** - * Constructs a new DocumentChange. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDocumentChange); - - /** DocumentChange document. */ - public document?: (google.firestore.v1beta1.IDocument|null); - - /** DocumentChange targetIds. */ - public targetIds: number[]; - - /** DocumentChange removedTargetIds. */ - public removedTargetIds: number[]; - - /** - * Creates a new DocumentChange instance using the specified properties. - * @param [properties] Properties to set - * @returns DocumentChange instance - */ - public static create(properties?: google.firestore.v1beta1.IDocumentChange): google.firestore.v1beta1.DocumentChange; - - /** - * Encodes the specified DocumentChange message. Does not implicitly {@link google.firestore.v1beta1.DocumentChange.verify|verify} messages. - * @param message DocumentChange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDocumentChange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DocumentChange message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentChange.verify|verify} messages. - * @param message DocumentChange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDocumentChange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DocumentChange message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DocumentChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DocumentChange; - - /** - * Decodes a DocumentChange message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DocumentChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DocumentChange; - - /** - * Verifies a DocumentChange message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentChange - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentChange; - - /** - * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. - * @param message DocumentChange - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DocumentChange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DocumentDelete. */ - interface IDocumentDelete { - - /** DocumentDelete document */ - document?: (string|null); - - /** DocumentDelete removedTargetIds */ - removedTargetIds?: (number[]|null); - - /** DocumentDelete readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a DocumentDelete. */ - class DocumentDelete implements IDocumentDelete { - - /** - * Constructs a new DocumentDelete. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDocumentDelete); - - /** DocumentDelete document. */ - public document: string; - - /** DocumentDelete removedTargetIds. */ - public removedTargetIds: number[]; - - /** DocumentDelete readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** - * Creates a new DocumentDelete instance using the specified properties. - * @param [properties] Properties to set - * @returns DocumentDelete instance - */ - public static create(properties?: google.firestore.v1beta1.IDocumentDelete): google.firestore.v1beta1.DocumentDelete; - - /** - * Encodes the specified DocumentDelete message. Does not implicitly {@link google.firestore.v1beta1.DocumentDelete.verify|verify} messages. - * @param message DocumentDelete message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDocumentDelete, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DocumentDelete message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentDelete.verify|verify} messages. - * @param message DocumentDelete message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDocumentDelete, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DocumentDelete message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DocumentDelete - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DocumentDelete; - - /** - * Decodes a DocumentDelete message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DocumentDelete - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DocumentDelete; - - /** - * Verifies a DocumentDelete message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentDelete - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentDelete; - - /** - * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. - * @param message DocumentDelete - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DocumentDelete to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DocumentRemove. */ - interface IDocumentRemove { - - /** DocumentRemove document */ - document?: (string|null); - - /** DocumentRemove removedTargetIds */ - removedTargetIds?: (number[]|null); - - /** DocumentRemove readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } - - /** Represents a DocumentRemove. */ - class DocumentRemove implements IDocumentRemove { - - /** - * Constructs a new DocumentRemove. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IDocumentRemove); - - /** DocumentRemove document. */ - public document: string; - - /** DocumentRemove removedTargetIds. */ - public removedTargetIds: number[]; - - /** DocumentRemove readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); - - /** - * Creates a new DocumentRemove instance using the specified properties. - * @param [properties] Properties to set - * @returns DocumentRemove instance - */ - public static create(properties?: google.firestore.v1beta1.IDocumentRemove): google.firestore.v1beta1.DocumentRemove; - - /** - * Encodes the specified DocumentRemove message. Does not implicitly {@link google.firestore.v1beta1.DocumentRemove.verify|verify} messages. - * @param message DocumentRemove message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IDocumentRemove, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DocumentRemove message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentRemove.verify|verify} messages. - * @param message DocumentRemove message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IDocumentRemove, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DocumentRemove message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DocumentRemove - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.DocumentRemove; - - /** - * Decodes a DocumentRemove message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DocumentRemove - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.DocumentRemove; - - /** - * Verifies a DocumentRemove message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentRemove - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.DocumentRemove; - - /** - * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. - * @param message DocumentRemove - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DocumentRemove to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an ExistenceFilter. */ - interface IExistenceFilter { - - /** ExistenceFilter targetId */ - targetId?: (number|null); - - /** ExistenceFilter count */ - count?: (number|null); - } - - /** Represents an ExistenceFilter. */ - class ExistenceFilter implements IExistenceFilter { - - /** - * Constructs a new ExistenceFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1beta1.IExistenceFilter); - - /** ExistenceFilter targetId. */ - public targetId: number; - - /** ExistenceFilter count. */ - public count: number; - - /** - * Creates a new ExistenceFilter instance using the specified properties. - * @param [properties] Properties to set - * @returns ExistenceFilter instance - */ - public static create(properties?: google.firestore.v1beta1.IExistenceFilter): google.firestore.v1beta1.ExistenceFilter; - - /** - * Encodes the specified ExistenceFilter message. Does not implicitly {@link google.firestore.v1beta1.ExistenceFilter.verify|verify} messages. - * @param message ExistenceFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.firestore.v1beta1.IExistenceFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ExistenceFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ExistenceFilter.verify|verify} messages. - * @param message ExistenceFilter message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.firestore.v1beta1.IExistenceFilter, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an ExistenceFilter message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ExistenceFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.firestore.v1beta1.ExistenceFilter; - - /** - * Decodes an ExistenceFilter message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ExistenceFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.firestore.v1beta1.ExistenceFilter; - - /** - * Verifies an ExistenceFilter message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExistenceFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.ExistenceFilter; - - /** - * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. - * @param message ExistenceFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1beta1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ExistenceFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - } - - /** Namespace api. */ - namespace api { - - /** Properties of a Http. */ - interface IHttp { - - /** Http rules */ - rules?: (google.api.IHttpRule[]|null); - } - - /** Represents a Http. */ - class Http implements IHttp { - - /** - * Constructs a new Http. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.IHttp); - - /** Http rules. */ - public rules: google.api.IHttpRule[]; - - /** - * Creates a new Http instance using the specified properties. - * @param [properties] Properties to set - * @returns Http instance - */ - public static create(properties?: google.api.IHttp): google.api.Http; - - /** - * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. - * @param message Http message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. - * @param message Http message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Http message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Http - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; - - /** - * Decodes a Http message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Http - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; - - /** - * Verifies a Http message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Http - */ - public static fromObject(object: { [k: string]: any }): google.api.Http; - - /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @param message Http - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Http to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a HttpRule. */ - interface IHttpRule { - - /** HttpRule get */ - get?: (string|null); - - /** HttpRule put */ - put?: (string|null); - - /** HttpRule post */ - post?: (string|null); - - /** HttpRule delete */ - "delete"?: (string|null); - - /** HttpRule patch */ - patch?: (string|null); - - /** HttpRule custom */ - custom?: (google.api.ICustomHttpPattern|null); - - /** HttpRule selector */ - selector?: (string|null); - - /** HttpRule body */ - body?: (string|null); - - /** HttpRule additionalBindings */ - additionalBindings?: (google.api.IHttpRule[]|null); - } - - /** Represents a HttpRule. */ - class HttpRule implements IHttpRule { - - /** - * Constructs a new HttpRule. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.IHttpRule); - - /** HttpRule get. */ - public get: string; - - /** HttpRule put. */ - public put: string; - - /** HttpRule post. */ - public post: string; - - /** HttpRule delete. */ - public delete: string; - - /** HttpRule patch. */ - public patch: string; - - /** HttpRule custom. */ - public custom?: (google.api.ICustomHttpPattern|null); - - /** HttpRule selector. */ - public selector: string; - - /** HttpRule body. */ - public body: string; - - /** HttpRule additionalBindings. */ - public additionalBindings: google.api.IHttpRule[]; - - /** HttpRule pattern. */ - public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); - - /** - * Creates a new HttpRule instance using the specified properties. - * @param [properties] Properties to set - * @returns HttpRule instance - */ - public static create(properties?: google.api.IHttpRule): google.api.HttpRule; - - /** - * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. - * @param message HttpRule message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. - * @param message HttpRule message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a HttpRule message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns HttpRule - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; - - /** - * Decodes a HttpRule message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns HttpRule - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; - - /** - * Verifies a HttpRule message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns HttpRule - */ - public static fromObject(object: { [k: string]: any }): google.api.HttpRule; - - /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. - * @param message HttpRule - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this HttpRule to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a CustomHttpPattern. */ - interface ICustomHttpPattern { - - /** CustomHttpPattern kind */ - kind?: (string|null); - - /** CustomHttpPattern path */ - path?: (string|null); - } - - /** Represents a CustomHttpPattern. */ - class CustomHttpPattern implements ICustomHttpPattern { - - /** - * Constructs a new CustomHttpPattern. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.ICustomHttpPattern); - - /** CustomHttpPattern kind. */ - public kind: string; - - /** CustomHttpPattern path. */ - public path: string; - - /** - * Creates a new CustomHttpPattern instance using the specified properties. - * @param [properties] Properties to set - * @returns CustomHttpPattern instance - */ - public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; - - /** - * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. - * @param message CustomHttpPattern message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. - * @param message CustomHttpPattern message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a CustomHttpPattern message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns CustomHttpPattern - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; - - /** - * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns CustomHttpPattern - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; - - /** - * Verifies a CustomHttpPattern message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CustomHttpPattern - */ - public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; - - /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. - * @param message CustomHttpPattern - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this CustomHttpPattern to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Namespace protobuf. */ - namespace protobuf { - - /** Properties of a FileDescriptorSet. */ - interface IFileDescriptorSet { - - /** FileDescriptorSet file */ - file?: (google.protobuf.IFileDescriptorProto[]|null); - } - - /** Represents a FileDescriptorSet. */ - class FileDescriptorSet implements IFileDescriptorSet { - - /** - * Constructs a new FileDescriptorSet. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileDescriptorSet); - - /** FileDescriptorSet file. */ - public file: google.protobuf.IFileDescriptorProto[]; - - /** - * Creates a new FileDescriptorSet instance using the specified properties. - * @param [properties] Properties to set - * @returns FileDescriptorSet instance - */ - public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; - - /** - * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. - * @param message FileDescriptorSet message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. - * @param message FileDescriptorSet message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FileDescriptorSet message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FileDescriptorSet - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; - - /** - * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FileDescriptorSet - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; - - /** - * Verifies a FileDescriptorSet message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileDescriptorSet - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; - - /** - * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. - * @param message FileDescriptorSet - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FileDescriptorSet to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a FileDescriptorProto. */ - interface IFileDescriptorProto { - - /** FileDescriptorProto name */ - name?: (string|null); - - /** FileDescriptorProto package */ - "package"?: (string|null); - - /** FileDescriptorProto dependency */ - dependency?: (string[]|null); - - /** FileDescriptorProto publicDependency */ - publicDependency?: (number[]|null); - - /** FileDescriptorProto weakDependency */ - weakDependency?: (number[]|null); - - /** FileDescriptorProto messageType */ - messageType?: (google.protobuf.IDescriptorProto[]|null); - - /** FileDescriptorProto enumType */ - enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - - /** FileDescriptorProto service */ - service?: (google.protobuf.IServiceDescriptorProto[]|null); - - /** FileDescriptorProto extension */ - extension?: (google.protobuf.IFieldDescriptorProto[]|null); - - /** FileDescriptorProto options */ - options?: (google.protobuf.IFileOptions|null); - - /** FileDescriptorProto sourceCodeInfo */ - sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - - /** FileDescriptorProto syntax */ - syntax?: (string|null); - } - - /** Represents a FileDescriptorProto. */ - class FileDescriptorProto implements IFileDescriptorProto { - - /** - * Constructs a new FileDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileDescriptorProto); - - /** FileDescriptorProto name. */ - public name: string; - - /** FileDescriptorProto package. */ - public package: string; - - /** FileDescriptorProto dependency. */ - public dependency: string[]; - - /** FileDescriptorProto publicDependency. */ - public publicDependency: number[]; - - /** FileDescriptorProto weakDependency. */ - public weakDependency: number[]; - - /** FileDescriptorProto messageType. */ - public messageType: google.protobuf.IDescriptorProto[]; - - /** FileDescriptorProto enumType. */ - public enumType: google.protobuf.IEnumDescriptorProto[]; - - /** FileDescriptorProto service. */ - public service: google.protobuf.IServiceDescriptorProto[]; - - /** FileDescriptorProto extension. */ - public extension: google.protobuf.IFieldDescriptorProto[]; - - /** FileDescriptorProto options. */ - public options?: (google.protobuf.IFileOptions|null); - - /** FileDescriptorProto sourceCodeInfo. */ - public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - - /** FileDescriptorProto syntax. */ - public syntax: string; - - /** - * Creates a new FileDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns FileDescriptorProto instance - */ - public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; - - /** - * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. - * @param message FileDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. - * @param message FileDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FileDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FileDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; - - /** - * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FileDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; - - /** - * Verifies a FileDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; - - /** - * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. - * @param message FileDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FileDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DescriptorProto. */ - interface IDescriptorProto { - - /** DescriptorProto name */ - name?: (string|null); - - /** DescriptorProto field */ - field?: (google.protobuf.IFieldDescriptorProto[]|null); - - /** DescriptorProto extension */ - extension?: (google.protobuf.IFieldDescriptorProto[]|null); - - /** DescriptorProto nestedType */ - nestedType?: (google.protobuf.IDescriptorProto[]|null); - - /** DescriptorProto enumType */ - enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - - /** DescriptorProto extensionRange */ - extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); - - /** DescriptorProto oneofDecl */ - oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); - - /** DescriptorProto options */ - options?: (google.protobuf.IMessageOptions|null); - - /** DescriptorProto reservedRange */ - reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); - - /** DescriptorProto reservedName */ - reservedName?: (string[]|null); - } - - /** Represents a DescriptorProto. */ - class DescriptorProto implements IDescriptorProto { - - /** - * Constructs a new DescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDescriptorProto); - - /** DescriptorProto name. */ - public name: string; - - /** DescriptorProto field. */ - public field: google.protobuf.IFieldDescriptorProto[]; - - /** DescriptorProto extension. */ - public extension: google.protobuf.IFieldDescriptorProto[]; - - /** DescriptorProto nestedType. */ - public nestedType: google.protobuf.IDescriptorProto[]; - - /** DescriptorProto enumType. */ - public enumType: google.protobuf.IEnumDescriptorProto[]; - - /** DescriptorProto extensionRange. */ - public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; - - /** DescriptorProto oneofDecl. */ - public oneofDecl: google.protobuf.IOneofDescriptorProto[]; - - /** DescriptorProto options. */ - public options?: (google.protobuf.IMessageOptions|null); - - /** DescriptorProto reservedRange. */ - public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; - - /** DescriptorProto reservedName. */ - public reservedName: string[]; - - /** - * Creates a new DescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns DescriptorProto instance - */ - public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; - - /** - * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. - * @param message DescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. - * @param message DescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; - - /** - * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; - - /** - * Verifies a DescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; - - /** - * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. - * @param message DescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace DescriptorProto { - - /** Properties of an ExtensionRange. */ - interface IExtensionRange { - - /** ExtensionRange start */ - start?: (number|null); - - /** ExtensionRange end */ - end?: (number|null); - } - - /** Represents an ExtensionRange. */ - class ExtensionRange implements IExtensionRange { - - /** - * Constructs a new ExtensionRange. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); - - /** ExtensionRange start. */ - public start: number; - - /** ExtensionRange end. */ - public end: number; - - /** - * Creates a new ExtensionRange instance using the specified properties. - * @param [properties] Properties to set - * @returns ExtensionRange instance - */ - public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; - - /** - * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. - * @param message ExtensionRange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. - * @param message ExtensionRange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an ExtensionRange message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ExtensionRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; - - /** - * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ExtensionRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; - - /** - * Verifies an ExtensionRange message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExtensionRange - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; - - /** - * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. - * @param message ExtensionRange - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ExtensionRange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ReservedRange. */ - interface IReservedRange { - - /** ReservedRange start */ - start?: (number|null); - - /** ReservedRange end */ - end?: (number|null); - } - - /** Represents a ReservedRange. */ - class ReservedRange implements IReservedRange { - - /** - * Constructs a new ReservedRange. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); - - /** ReservedRange start. */ - public start: number; - - /** ReservedRange end. */ - public end: number; - - /** - * Creates a new ReservedRange instance using the specified properties. - * @param [properties] Properties to set - * @returns ReservedRange instance - */ - public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; - - /** - * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. - * @param message ReservedRange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. - * @param message ReservedRange message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ReservedRange message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ReservedRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; - - /** - * Decodes a ReservedRange message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ReservedRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; - - /** - * Verifies a ReservedRange message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ReservedRange - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; - - /** - * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. - * @param message ReservedRange - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ReservedRange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a FieldDescriptorProto. */ - interface IFieldDescriptorProto { - - /** FieldDescriptorProto name */ - name?: (string|null); - - /** FieldDescriptorProto number */ - number?: (number|null); - - /** FieldDescriptorProto label */ - label?: (google.protobuf.FieldDescriptorProto.Label|null); - - /** FieldDescriptorProto type */ - type?: (google.protobuf.FieldDescriptorProto.Type|null); - - /** FieldDescriptorProto typeName */ - typeName?: (string|null); - - /** FieldDescriptorProto extendee */ - extendee?: (string|null); - - /** FieldDescriptorProto defaultValue */ - defaultValue?: (string|null); - - /** FieldDescriptorProto oneofIndex */ - oneofIndex?: (number|null); - - /** FieldDescriptorProto jsonName */ - jsonName?: (string|null); - - /** FieldDescriptorProto options */ - options?: (google.protobuf.IFieldOptions|null); - } - - /** Represents a FieldDescriptorProto. */ - class FieldDescriptorProto implements IFieldDescriptorProto { - - /** - * Constructs a new FieldDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldDescriptorProto); - - /** FieldDescriptorProto name. */ - public name: string; - - /** FieldDescriptorProto number. */ - public number: number; - - /** FieldDescriptorProto label. */ - public label: google.protobuf.FieldDescriptorProto.Label; - - /** FieldDescriptorProto type. */ - public type: google.protobuf.FieldDescriptorProto.Type; - - /** FieldDescriptorProto typeName. */ - public typeName: string; - - /** FieldDescriptorProto extendee. */ - public extendee: string; - - /** FieldDescriptorProto defaultValue. */ - public defaultValue: string; - - /** FieldDescriptorProto oneofIndex. */ - public oneofIndex: number; - - /** FieldDescriptorProto jsonName. */ - public jsonName: string; - - /** FieldDescriptorProto options. */ - public options?: (google.protobuf.IFieldOptions|null); - - /** - * Creates a new FieldDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns FieldDescriptorProto instance - */ - public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; - - /** - * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. - * @param message FieldDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. - * @param message FieldDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FieldDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FieldDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; - - /** - * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FieldDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; - - /** - * Verifies a FieldDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; - - /** - * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. - * @param message FieldDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace FieldDescriptorProto { - - /** Type enum. */ - enum Type { - TYPE_DOUBLE = 1, - TYPE_FLOAT = 2, - TYPE_INT64 = 3, - TYPE_UINT64 = 4, - TYPE_INT32 = 5, - TYPE_FIXED64 = 6, - TYPE_FIXED32 = 7, - TYPE_BOOL = 8, - TYPE_STRING = 9, - TYPE_GROUP = 10, - TYPE_MESSAGE = 11, - TYPE_BYTES = 12, - TYPE_UINT32 = 13, - TYPE_ENUM = 14, - TYPE_SFIXED32 = 15, - TYPE_SFIXED64 = 16, - TYPE_SINT32 = 17, - TYPE_SINT64 = 18 - } - - /** Label enum. */ - enum Label { - LABEL_OPTIONAL = 1, - LABEL_REQUIRED = 2, - LABEL_REPEATED = 3 - } - } - - /** Properties of an OneofDescriptorProto. */ - interface IOneofDescriptorProto { - - /** OneofDescriptorProto name */ - name?: (string|null); - - /** OneofDescriptorProto options */ - options?: (google.protobuf.IOneofOptions|null); - } - - /** Represents an OneofDescriptorProto. */ - class OneofDescriptorProto implements IOneofDescriptorProto { - - /** - * Constructs a new OneofDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IOneofDescriptorProto); - - /** OneofDescriptorProto name. */ - public name: string; - - /** OneofDescriptorProto options. */ - public options?: (google.protobuf.IOneofOptions|null); - - /** - * Creates a new OneofDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns OneofDescriptorProto instance - */ - public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; - - /** - * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. - * @param message OneofDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. - * @param message OneofDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an OneofDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns OneofDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; - - /** - * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns OneofDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; - - /** - * Verifies an OneofDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns OneofDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; - - /** - * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. - * @param message OneofDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this OneofDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an EnumDescriptorProto. */ - interface IEnumDescriptorProto { - - /** EnumDescriptorProto name */ - name?: (string|null); - - /** EnumDescriptorProto value */ - value?: (google.protobuf.IEnumValueDescriptorProto[]|null); - - /** EnumDescriptorProto options */ - options?: (google.protobuf.IEnumOptions|null); - } - - /** Represents an EnumDescriptorProto. */ - class EnumDescriptorProto implements IEnumDescriptorProto { - - /** - * Constructs a new EnumDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumDescriptorProto); - - /** EnumDescriptorProto name. */ - public name: string; - - /** EnumDescriptorProto value. */ - public value: google.protobuf.IEnumValueDescriptorProto[]; - - /** EnumDescriptorProto options. */ - public options?: (google.protobuf.IEnumOptions|null); - - /** - * Creates a new EnumDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns EnumDescriptorProto instance - */ - public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; - - /** - * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. - * @param message EnumDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. - * @param message EnumDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an EnumDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns EnumDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; - - /** - * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns EnumDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; - - /** - * Verifies an EnumDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; - - /** - * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. - * @param message EnumDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this EnumDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an EnumValueDescriptorProto. */ - interface IEnumValueDescriptorProto { - - /** EnumValueDescriptorProto name */ - name?: (string|null); - - /** EnumValueDescriptorProto number */ - number?: (number|null); - - /** EnumValueDescriptorProto options */ - options?: (google.protobuf.IEnumValueOptions|null); - } - - /** Represents an EnumValueDescriptorProto. */ - class EnumValueDescriptorProto implements IEnumValueDescriptorProto { - - /** - * Constructs a new EnumValueDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumValueDescriptorProto); - - /** EnumValueDescriptorProto name. */ - public name: string; - - /** EnumValueDescriptorProto number. */ - public number: number; - - /** EnumValueDescriptorProto options. */ - public options?: (google.protobuf.IEnumValueOptions|null); - - /** - * Creates a new EnumValueDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns EnumValueDescriptorProto instance - */ - public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; - - /** - * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. - * @param message EnumValueDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. - * @param message EnumValueDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns EnumValueDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; - - /** - * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns EnumValueDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; - - /** - * Verifies an EnumValueDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumValueDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; - - /** - * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. - * @param message EnumValueDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this EnumValueDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ServiceDescriptorProto. */ - interface IServiceDescriptorProto { - - /** ServiceDescriptorProto name */ - name?: (string|null); - - /** ServiceDescriptorProto method */ - method?: (google.protobuf.IMethodDescriptorProto[]|null); - - /** ServiceDescriptorProto options */ - options?: (google.protobuf.IServiceOptions|null); - } - - /** Represents a ServiceDescriptorProto. */ - class ServiceDescriptorProto implements IServiceDescriptorProto { - - /** - * Constructs a new ServiceDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IServiceDescriptorProto); - - /** ServiceDescriptorProto name. */ - public name: string; - - /** ServiceDescriptorProto method. */ - public method: google.protobuf.IMethodDescriptorProto[]; - - /** ServiceDescriptorProto options. */ - public options?: (google.protobuf.IServiceOptions|null); - - /** - * Creates a new ServiceDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns ServiceDescriptorProto instance - */ - public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; - - /** - * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. - * @param message ServiceDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. - * @param message ServiceDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ServiceDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ServiceDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; - - /** - * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ServiceDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; - - /** - * Verifies a ServiceDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ServiceDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; - - /** - * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. - * @param message ServiceDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ServiceDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a MethodDescriptorProto. */ - interface IMethodDescriptorProto { - - /** MethodDescriptorProto name */ - name?: (string|null); - - /** MethodDescriptorProto inputType */ - inputType?: (string|null); - - /** MethodDescriptorProto outputType */ - outputType?: (string|null); - - /** MethodDescriptorProto options */ - options?: (google.protobuf.IMethodOptions|null); - - /** MethodDescriptorProto clientStreaming */ - clientStreaming?: (boolean|null); - - /** MethodDescriptorProto serverStreaming */ - serverStreaming?: (boolean|null); - } - - /** Represents a MethodDescriptorProto. */ - class MethodDescriptorProto implements IMethodDescriptorProto { - - /** - * Constructs a new MethodDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMethodDescriptorProto); - - /** MethodDescriptorProto name. */ - public name: string; - - /** MethodDescriptorProto inputType. */ - public inputType: string; - - /** MethodDescriptorProto outputType. */ - public outputType: string; - - /** MethodDescriptorProto options. */ - public options?: (google.protobuf.IMethodOptions|null); - - /** MethodDescriptorProto clientStreaming. */ - public clientStreaming: boolean; - - /** MethodDescriptorProto serverStreaming. */ - public serverStreaming: boolean; - - /** - * Creates a new MethodDescriptorProto instance using the specified properties. - * @param [properties] Properties to set - * @returns MethodDescriptorProto instance - */ - public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; - - /** - * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. - * @param message MethodDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. - * @param message MethodDescriptorProto message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a MethodDescriptorProto message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns MethodDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; - - /** - * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns MethodDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; - - /** - * Verifies a MethodDescriptorProto message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MethodDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; - - /** - * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. - * @param message MethodDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this MethodDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a FileOptions. */ - interface IFileOptions { - - /** FileOptions javaPackage */ - javaPackage?: (string|null); - - /** FileOptions javaOuterClassname */ - javaOuterClassname?: (string|null); - - /** FileOptions javaMultipleFiles */ - javaMultipleFiles?: (boolean|null); - - /** FileOptions javaGenerateEqualsAndHash */ - javaGenerateEqualsAndHash?: (boolean|null); - - /** FileOptions javaStringCheckUtf8 */ - javaStringCheckUtf8?: (boolean|null); - - /** FileOptions optimizeFor */ - optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); - - /** FileOptions goPackage */ - goPackage?: (string|null); - - /** FileOptions ccGenericServices */ - ccGenericServices?: (boolean|null); - - /** FileOptions javaGenericServices */ - javaGenericServices?: (boolean|null); - - /** FileOptions pyGenericServices */ - pyGenericServices?: (boolean|null); - - /** FileOptions deprecated */ - deprecated?: (boolean|null); - - /** FileOptions ccEnableArenas */ - ccEnableArenas?: (boolean|null); - - /** FileOptions objcClassPrefix */ - objcClassPrefix?: (string|null); - - /** FileOptions csharpNamespace */ - csharpNamespace?: (string|null); - - /** FileOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents a FileOptions. */ - class FileOptions implements IFileOptions { - - /** - * Constructs a new FileOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileOptions); - - /** FileOptions javaPackage. */ - public javaPackage: string; - - /** FileOptions javaOuterClassname. */ - public javaOuterClassname: string; - - /** FileOptions javaMultipleFiles. */ - public javaMultipleFiles: boolean; - - /** FileOptions javaGenerateEqualsAndHash. */ - public javaGenerateEqualsAndHash: boolean; - - /** FileOptions javaStringCheckUtf8. */ - public javaStringCheckUtf8: boolean; - - /** FileOptions optimizeFor. */ - public optimizeFor: google.protobuf.FileOptions.OptimizeMode; - - /** FileOptions goPackage. */ - public goPackage: string; - - /** FileOptions ccGenericServices. */ - public ccGenericServices: boolean; - - /** FileOptions javaGenericServices. */ - public javaGenericServices: boolean; - - /** FileOptions pyGenericServices. */ - public pyGenericServices: boolean; - - /** FileOptions deprecated. */ - public deprecated: boolean; - - /** FileOptions ccEnableArenas. */ - public ccEnableArenas: boolean; - - /** FileOptions objcClassPrefix. */ - public objcClassPrefix: string; - - /** FileOptions csharpNamespace. */ - public csharpNamespace: string; - - /** FileOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new FileOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns FileOptions instance - */ - public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; - - /** - * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. - * @param message FileOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. - * @param message FileOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FileOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FileOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; - - /** - * Decodes a FileOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FileOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; - - /** - * Verifies a FileOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; - - /** - * Creates a plain object from a FileOptions message. Also converts values to other types if specified. - * @param message FileOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FileOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace FileOptions { - - /** OptimizeMode enum. */ - enum OptimizeMode { - SPEED = 1, - CODE_SIZE = 2, - LITE_RUNTIME = 3 - } - } - - /** Properties of a MessageOptions. */ - interface IMessageOptions { - - /** MessageOptions messageSetWireFormat */ - messageSetWireFormat?: (boolean|null); - - /** MessageOptions noStandardDescriptorAccessor */ - noStandardDescriptorAccessor?: (boolean|null); - - /** MessageOptions deprecated */ - deprecated?: (boolean|null); - - /** MessageOptions mapEntry */ - mapEntry?: (boolean|null); - - /** MessageOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents a MessageOptions. */ - class MessageOptions implements IMessageOptions { - - /** - * Constructs a new MessageOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMessageOptions); - - /** MessageOptions messageSetWireFormat. */ - public messageSetWireFormat: boolean; - - /** MessageOptions noStandardDescriptorAccessor. */ - public noStandardDescriptorAccessor: boolean; - - /** MessageOptions deprecated. */ - public deprecated: boolean; - - /** MessageOptions mapEntry. */ - public mapEntry: boolean; - - /** MessageOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new MessageOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns MessageOptions instance - */ - public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; - - /** - * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. - * @param message MessageOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. - * @param message MessageOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a MessageOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns MessageOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; - - /** - * Decodes a MessageOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns MessageOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; - - /** - * Verifies a MessageOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MessageOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; - - /** - * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. - * @param message MessageOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this MessageOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a FieldOptions. */ - interface IFieldOptions { - - /** FieldOptions ctype */ - ctype?: (google.protobuf.FieldOptions.CType|null); - - /** FieldOptions packed */ - packed?: (boolean|null); - - /** FieldOptions jstype */ - jstype?: (google.protobuf.FieldOptions.JSType|null); - - /** FieldOptions lazy */ - lazy?: (boolean|null); - - /** FieldOptions deprecated */ - deprecated?: (boolean|null); - - /** FieldOptions weak */ - weak?: (boolean|null); - - /** FieldOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents a FieldOptions. */ - class FieldOptions implements IFieldOptions { - - /** - * Constructs a new FieldOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldOptions); - - /** FieldOptions ctype. */ - public ctype: google.protobuf.FieldOptions.CType; - - /** FieldOptions packed. */ - public packed: boolean; - - /** FieldOptions jstype. */ - public jstype: google.protobuf.FieldOptions.JSType; - - /** FieldOptions lazy. */ - public lazy: boolean; - - /** FieldOptions deprecated. */ - public deprecated: boolean; - - /** FieldOptions weak. */ - public weak: boolean; - - /** FieldOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new FieldOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns FieldOptions instance - */ - public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; - - /** - * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. - * @param message FieldOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. - * @param message FieldOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FieldOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FieldOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; - - /** - * Decodes a FieldOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FieldOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; - - /** - * Verifies a FieldOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; - - /** - * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. - * @param message FieldOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace FieldOptions { - - /** CType enum. */ - enum CType { - STRING = 0, - CORD = 1, - STRING_PIECE = 2 - } - - /** JSType enum. */ - enum JSType { - JS_NORMAL = 0, - JS_STRING = 1, - JS_NUMBER = 2 - } - } - - /** Properties of an OneofOptions. */ - interface IOneofOptions { - - /** OneofOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents an OneofOptions. */ - class OneofOptions implements IOneofOptions { - - /** - * Constructs a new OneofOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IOneofOptions); - - /** OneofOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new OneofOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns OneofOptions instance - */ - public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; - - /** - * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. - * @param message OneofOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. - * @param message OneofOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an OneofOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns OneofOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; - - /** - * Decodes an OneofOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns OneofOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; - - /** - * Verifies an OneofOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns OneofOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; - - /** - * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. - * @param message OneofOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this OneofOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an EnumOptions. */ - interface IEnumOptions { - - /** EnumOptions allowAlias */ - allowAlias?: (boolean|null); - - /** EnumOptions deprecated */ - deprecated?: (boolean|null); - - /** EnumOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents an EnumOptions. */ - class EnumOptions implements IEnumOptions { - - /** - * Constructs a new EnumOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumOptions); - - /** EnumOptions allowAlias. */ - public allowAlias: boolean; - - /** EnumOptions deprecated. */ - public deprecated: boolean; - - /** EnumOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new EnumOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns EnumOptions instance - */ - public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; - - /** - * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. - * @param message EnumOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. - * @param message EnumOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an EnumOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns EnumOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; - - /** - * Decodes an EnumOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns EnumOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; - - /** - * Verifies an EnumOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; - - /** - * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. - * @param message EnumOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this EnumOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an EnumValueOptions. */ - interface IEnumValueOptions { - - /** EnumValueOptions deprecated */ - deprecated?: (boolean|null); - - /** EnumValueOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents an EnumValueOptions. */ - class EnumValueOptions implements IEnumValueOptions { - - /** - * Constructs a new EnumValueOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumValueOptions); - - /** EnumValueOptions deprecated. */ - public deprecated: boolean; - - /** EnumValueOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new EnumValueOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns EnumValueOptions instance - */ - public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; - - /** - * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. - * @param message EnumValueOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. - * @param message EnumValueOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an EnumValueOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns EnumValueOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; - - /** - * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns EnumValueOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; - - /** - * Verifies an EnumValueOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumValueOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; - - /** - * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. - * @param message EnumValueOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this EnumValueOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a ServiceOptions. */ - interface IServiceOptions { - - /** ServiceOptions deprecated */ - deprecated?: (boolean|null); - - /** ServiceOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } - - /** Represents a ServiceOptions. */ - class ServiceOptions implements IServiceOptions { - - /** - * Constructs a new ServiceOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IServiceOptions); - - /** ServiceOptions deprecated. */ - public deprecated: boolean; - - /** ServiceOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new ServiceOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns ServiceOptions instance - */ - public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; - - /** - * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. - * @param message ServiceOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. - * @param message ServiceOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ServiceOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ServiceOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; - - /** - * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ServiceOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; - - /** - * Verifies a ServiceOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ServiceOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; - - /** - * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. - * @param message ServiceOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ServiceOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a MethodOptions. */ - interface IMethodOptions { - - /** MethodOptions deprecated */ - deprecated?: (boolean|null); - - /** MethodOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - - /** MethodOptions .google.api.http */ - ".google.api.http"?: (google.api.IHttpRule|null); - } - - /** Represents a MethodOptions. */ - class MethodOptions implements IMethodOptions { - - /** - * Constructs a new MethodOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMethodOptions); - - /** MethodOptions deprecated. */ - public deprecated: boolean; - - /** MethodOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a new MethodOptions instance using the specified properties. - * @param [properties] Properties to set - * @returns MethodOptions instance - */ - public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; - - /** - * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. - * @param message MethodOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. - * @param message MethodOptions message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a MethodOptions message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns MethodOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; - - /** - * Decodes a MethodOptions message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns MethodOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; - - /** - * Verifies a MethodOptions message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MethodOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; - - /** - * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. - * @param message MethodOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this MethodOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an UninterpretedOption. */ - interface IUninterpretedOption { - - /** UninterpretedOption name */ - name?: (google.protobuf.UninterpretedOption.INamePart[]|null); - - /** UninterpretedOption identifierValue */ - identifierValue?: (string|null); - - /** UninterpretedOption positiveIntValue */ - positiveIntValue?: (number|string|null); - - /** UninterpretedOption negativeIntValue */ - negativeIntValue?: (number|string|null); - - /** UninterpretedOption doubleValue */ - doubleValue?: (number|null); - - /** UninterpretedOption stringValue */ - stringValue?: (Uint8Array|null); - - /** UninterpretedOption aggregateValue */ - aggregateValue?: (string|null); - } - - /** Represents an UninterpretedOption. */ - class UninterpretedOption implements IUninterpretedOption { - - /** - * Constructs a new UninterpretedOption. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUninterpretedOption); - - /** UninterpretedOption name. */ - public name: google.protobuf.UninterpretedOption.INamePart[]; - - /** UninterpretedOption identifierValue. */ - public identifierValue: string; - - /** UninterpretedOption positiveIntValue. */ - public positiveIntValue: (number|string); - - /** UninterpretedOption negativeIntValue. */ - public negativeIntValue: (number|string); - - /** UninterpretedOption doubleValue. */ - public doubleValue: number; - - /** UninterpretedOption stringValue. */ - public stringValue: Uint8Array; - - /** UninterpretedOption aggregateValue. */ - public aggregateValue: string; - - /** - * Creates a new UninterpretedOption instance using the specified properties. - * @param [properties] Properties to set - * @returns UninterpretedOption instance - */ - public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; - - /** - * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. - * @param message UninterpretedOption message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. - * @param message UninterpretedOption message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an UninterpretedOption message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns UninterpretedOption - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; - - /** - * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns UninterpretedOption - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; - - /** - * Verifies an UninterpretedOption message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UninterpretedOption - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; - - /** - * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. - * @param message UninterpretedOption - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this UninterpretedOption to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace UninterpretedOption { - - /** Properties of a NamePart. */ - interface INamePart { - - /** NamePart namePart */ - namePart: string; - - /** NamePart isExtension */ - isExtension: boolean; - } - - /** Represents a NamePart. */ - class NamePart implements INamePart { - - /** - * Constructs a new NamePart. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.UninterpretedOption.INamePart); - - /** NamePart namePart. */ - public namePart: string; - - /** NamePart isExtension. */ - public isExtension: boolean; - - /** - * Creates a new NamePart instance using the specified properties. - * @param [properties] Properties to set - * @returns NamePart instance - */ - public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; - - /** - * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. - * @param message NamePart message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. - * @param message NamePart message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a NamePart message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns NamePart - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; - - /** - * Decodes a NamePart message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns NamePart - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; - - /** - * Verifies a NamePart message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a NamePart message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns NamePart - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; - - /** - * Creates a plain object from a NamePart message. Also converts values to other types if specified. - * @param message NamePart - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this NamePart to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a SourceCodeInfo. */ - interface ISourceCodeInfo { - - /** SourceCodeInfo location */ - location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); - } - - /** Represents a SourceCodeInfo. */ - class SourceCodeInfo implements ISourceCodeInfo { - - /** - * Constructs a new SourceCodeInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.ISourceCodeInfo); - - /** SourceCodeInfo location. */ - public location: google.protobuf.SourceCodeInfo.ILocation[]; - - /** - * Creates a new SourceCodeInfo instance using the specified properties. - * @param [properties] Properties to set - * @returns SourceCodeInfo instance - */ - public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; - - /** - * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. - * @param message SourceCodeInfo message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. - * @param message SourceCodeInfo message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a SourceCodeInfo message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns SourceCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; - - /** - * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns SourceCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; - - /** - * Verifies a SourceCodeInfo message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns SourceCodeInfo - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; - - /** - * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. - * @param message SourceCodeInfo - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this SourceCodeInfo to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace SourceCodeInfo { - - /** Properties of a Location. */ - interface ILocation { - - /** Location path */ - path?: (number[]|null); - - /** Location span */ - span?: (number[]|null); - - /** Location leadingComments */ - leadingComments?: (string|null); - - /** Location trailingComments */ - trailingComments?: (string|null); - - /** Location leadingDetachedComments */ - leadingDetachedComments?: (string[]|null); - } - - /** Represents a Location. */ - class Location implements ILocation { - - /** - * Constructs a new Location. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); - - /** Location path. */ - public path: number[]; - - /** Location span. */ - public span: number[]; - - /** Location leadingComments. */ - public leadingComments: string; - - /** Location trailingComments. */ - public trailingComments: string; - - /** Location leadingDetachedComments. */ - public leadingDetachedComments: string[]; - - /** - * Creates a new Location instance using the specified properties. - * @param [properties] Properties to set - * @returns Location instance - */ - public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; - - /** - * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. - * @param message Location message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. - * @param message Location message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Location message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Location - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; - - /** - * Decodes a Location message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Location - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; - - /** - * Verifies a Location message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Location message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Location - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; - - /** - * Creates a plain object from a Location message. Also converts values to other types if specified. - * @param message Location - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Location to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a GeneratedCodeInfo. */ - interface IGeneratedCodeInfo { - - /** GeneratedCodeInfo annotation */ - annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); - } - - /** Represents a GeneratedCodeInfo. */ - class GeneratedCodeInfo implements IGeneratedCodeInfo { - - /** - * Constructs a new GeneratedCodeInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IGeneratedCodeInfo); - - /** GeneratedCodeInfo annotation. */ - public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; - - /** - * Creates a new GeneratedCodeInfo instance using the specified properties. - * @param [properties] Properties to set - * @returns GeneratedCodeInfo instance - */ - public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; - - /** - * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. - * @param message GeneratedCodeInfo message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. - * @param message GeneratedCodeInfo message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a GeneratedCodeInfo message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns GeneratedCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; - - /** - * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns GeneratedCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; - - /** - * Verifies a GeneratedCodeInfo message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns GeneratedCodeInfo - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; - - /** - * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. - * @param message GeneratedCodeInfo - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this GeneratedCodeInfo to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace GeneratedCodeInfo { - - /** Properties of an Annotation. */ - interface IAnnotation { - - /** Annotation path */ - path?: (number[]|null); - - /** Annotation sourceFile */ - sourceFile?: (string|null); - - /** Annotation begin */ - begin?: (number|null); - - /** Annotation end */ - end?: (number|null); - } - - /** Represents an Annotation. */ - class Annotation implements IAnnotation { - - /** - * Constructs a new Annotation. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); - - /** Annotation path. */ - public path: number[]; - - /** Annotation sourceFile. */ - public sourceFile: string; - - /** Annotation begin. */ - public begin: number; - - /** Annotation end. */ - public end: number; - - /** - * Creates a new Annotation instance using the specified properties. - * @param [properties] Properties to set - * @returns Annotation instance - */ - public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; - - /** - * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. - * @param message Annotation message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. - * @param message Annotation message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Annotation message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Annotation - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; - - /** - * Decodes an Annotation message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Annotation - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; - - /** - * Verifies an Annotation message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an Annotation message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Annotation - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; - - /** - * Creates a plain object from an Annotation message. Also converts values to other types if specified. - * @param message Annotation - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Annotation to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a Timestamp. */ - interface ITimestamp { - - /** Timestamp seconds */ - seconds?: (number|string|null); - - /** Timestamp nanos */ - nanos?: (number|null); - } - - /** Represents a Timestamp. */ - class Timestamp implements ITimestamp { - - /** - * Constructs a new Timestamp. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.ITimestamp); - - /** Timestamp seconds. */ - public seconds: (number|string); - - /** Timestamp nanos. */ - public nanos: number; - - /** - * Creates a new Timestamp instance using the specified properties. - * @param [properties] Properties to set - * @returns Timestamp instance - */ - public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp; - - /** - * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. - * @param message Timestamp message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. - * @param message Timestamp message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Timestamp message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Timestamp - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Timestamp; - - /** - * Decodes a Timestamp message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Timestamp - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Timestamp; - - /** - * Verifies a Timestamp message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Timestamp - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; - - /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. - * @param message Timestamp - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Timestamp to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Struct. */ - interface IStruct { - - /** Struct fields */ - fields?: ({ [k: string]: google.protobuf.IValue }|null); - } - - /** Represents a Struct. */ - class Struct implements IStruct { - - /** - * Constructs a new Struct. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IStruct); - - /** Struct fields. */ - public fields: { [k: string]: google.protobuf.IValue }; - - /** - * Creates a new Struct instance using the specified properties. - * @param [properties] Properties to set - * @returns Struct instance - */ - public static create(properties?: google.protobuf.IStruct): google.protobuf.Struct; - - /** - * Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. - * @param message Struct message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. - * @param message Struct message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Struct message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Struct - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Struct; - - /** - * Decodes a Struct message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Struct - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Struct; - - /** - * Verifies a Struct message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Struct message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Struct - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; - - /** - * Creates a plain object from a Struct message. Also converts values to other types if specified. - * @param message Struct - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Struct to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a Value. */ - interface IValue { - - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); - - /** Value numberValue */ - numberValue?: (number|null); - - /** Value stringValue */ - stringValue?: (string|null); - - /** Value boolValue */ - boolValue?: (boolean|null); - - /** Value structValue */ - structValue?: (google.protobuf.IStruct|null); - - /** Value listValue */ - listValue?: (google.protobuf.IListValue|null); - } - - /** Represents a Value. */ - class Value implements IValue { - - /** - * Constructs a new Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IValue); - - /** Value nullValue. */ - public nullValue: google.protobuf.NullValue; - - /** Value numberValue. */ - public numberValue: number; - - /** Value stringValue. */ - public stringValue: string; - - /** Value boolValue. */ - public boolValue: boolean; - - /** Value structValue. */ - public structValue?: (google.protobuf.IStruct|null); - - /** Value listValue. */ - public listValue?: (google.protobuf.IListValue|null); - - /** Value kind. */ - public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); - - /** - * Creates a new Value instance using the specified properties. - * @param [properties] Properties to set - * @returns Value instance - */ - public static create(properties?: google.protobuf.IValue): google.protobuf.Value; - - /** - * Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. - * @param message Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. - * @param message Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Value message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Value; - - /** - * Decodes a Value message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Value; - - /** - * Verifies a Value message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Value; - - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** NullValue enum. */ - enum NullValue { - NULL_VALUE = 0 - } - - /** Properties of a ListValue. */ - interface IListValue { - - /** ListValue values */ - values?: (google.protobuf.IValue[]|null); - } - - /** Represents a ListValue. */ - class ListValue implements IListValue { - - /** - * Constructs a new ListValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IListValue); - - /** ListValue values. */ - public values: google.protobuf.IValue[]; - - /** - * Creates a new ListValue instance using the specified properties. - * @param [properties] Properties to set - * @returns ListValue instance - */ - public static create(properties?: google.protobuf.IListValue): google.protobuf.ListValue; - - /** - * Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. - * @param message ListValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. - * @param message ListValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a ListValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ListValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ListValue; - - /** - * Decodes a ListValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ListValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ListValue; - - /** - * Verifies a ListValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a ListValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; - - /** - * Creates a plain object from a ListValue message. Also converts values to other types if specified. - * @param message ListValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DoubleValue. */ - interface IDoubleValue { - - /** DoubleValue value */ - value?: (number|null); - } - - /** Represents a DoubleValue. */ - class DoubleValue implements IDoubleValue { - - /** - * Constructs a new DoubleValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDoubleValue); - - /** DoubleValue value. */ - public value: number; - - /** - * Creates a new DoubleValue instance using the specified properties. - * @param [properties] Properties to set - * @returns DoubleValue instance - */ - public static create(properties?: google.protobuf.IDoubleValue): google.protobuf.DoubleValue; - - /** - * Encodes the specified DoubleValue message. Does not implicitly {@link google.protobuf.DoubleValue.verify|verify} messages. - * @param message DoubleValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IDoubleValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified DoubleValue message, length delimited. Does not implicitly {@link google.protobuf.DoubleValue.verify|verify} messages. - * @param message DoubleValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IDoubleValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a DoubleValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns DoubleValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DoubleValue; - - /** - * Decodes a DoubleValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns DoubleValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DoubleValue; - - /** - * Verifies a DoubleValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DoubleValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; - - /** - * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. - * @param message DoubleValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DoubleValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a FloatValue. */ - interface IFloatValue { - - /** FloatValue value */ - value?: (number|null); - } - - /** Represents a FloatValue. */ - class FloatValue implements IFloatValue { - - /** - * Constructs a new FloatValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFloatValue); - - /** FloatValue value. */ - public value: number; - - /** - * Creates a new FloatValue instance using the specified properties. - * @param [properties] Properties to set - * @returns FloatValue instance - */ - public static create(properties?: google.protobuf.IFloatValue): google.protobuf.FloatValue; - - /** - * Encodes the specified FloatValue message. Does not implicitly {@link google.protobuf.FloatValue.verify|verify} messages. - * @param message FloatValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IFloatValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified FloatValue message, length delimited. Does not implicitly {@link google.protobuf.FloatValue.verify|verify} messages. - * @param message FloatValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IFloatValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a FloatValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns FloatValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FloatValue; - - /** - * Decodes a FloatValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns FloatValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FloatValue; - - /** - * Verifies a FloatValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FloatValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; - - /** - * Creates a plain object from a FloatValue message. Also converts values to other types if specified. - * @param message FloatValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FloatValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an Int64Value. */ - interface IInt64Value { - - /** Int64Value value */ - value?: (number|string|null); - } - - /** Represents an Int64Value. */ - class Int64Value implements IInt64Value { - - /** - * Constructs a new Int64Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IInt64Value); - - /** Int64Value value. */ - public value: (number|string); - - /** - * Creates a new Int64Value instance using the specified properties. - * @param [properties] Properties to set - * @returns Int64Value instance - */ - public static create(properties?: google.protobuf.IInt64Value): google.protobuf.Int64Value; - - /** - * Encodes the specified Int64Value message. Does not implicitly {@link google.protobuf.Int64Value.verify|verify} messages. - * @param message Int64Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Int64Value message, length delimited. Does not implicitly {@link google.protobuf.Int64Value.verify|verify} messages. - * @param message Int64Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Int64Value message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Int64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Int64Value; - - /** - * Decodes an Int64Value message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Int64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Int64Value; - - /** - * Verifies an Int64Value message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Int64Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; - - /** - * Creates a plain object from an Int64Value message. Also converts values to other types if specified. - * @param message Int64Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Int64Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a UInt64Value. */ - interface IUInt64Value { - - /** UInt64Value value */ - value?: (number|string|null); - } - - /** Represents a UInt64Value. */ - class UInt64Value implements IUInt64Value { - - /** - * Constructs a new UInt64Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUInt64Value); - - /** UInt64Value value. */ - public value: (number|string); - - /** - * Creates a new UInt64Value instance using the specified properties. - * @param [properties] Properties to set - * @returns UInt64Value instance - */ - public static create(properties?: google.protobuf.IUInt64Value): google.protobuf.UInt64Value; - - /** - * Encodes the specified UInt64Value message. Does not implicitly {@link google.protobuf.UInt64Value.verify|verify} messages. - * @param message UInt64Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IUInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified UInt64Value message, length delimited. Does not implicitly {@link google.protobuf.UInt64Value.verify|verify} messages. - * @param message UInt64Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IUInt64Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a UInt64Value message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns UInt64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UInt64Value; - - /** - * Decodes a UInt64Value message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns UInt64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UInt64Value; - - /** - * Verifies a UInt64Value message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UInt64Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; - - /** - * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. - * @param message UInt64Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this UInt64Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an Int32Value. */ - interface IInt32Value { - - /** Int32Value value */ - value?: (number|null); - } - - /** Represents an Int32Value. */ - class Int32Value implements IInt32Value { - - /** - * Constructs a new Int32Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IInt32Value); - - /** Int32Value value. */ - public value: number; - - /** - * Creates a new Int32Value instance using the specified properties. - * @param [properties] Properties to set - * @returns Int32Value instance - */ - public static create(properties?: google.protobuf.IInt32Value): google.protobuf.Int32Value; - - /** - * Encodes the specified Int32Value message. Does not implicitly {@link google.protobuf.Int32Value.verify|verify} messages. - * @param message Int32Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Int32Value message, length delimited. Does not implicitly {@link google.protobuf.Int32Value.verify|verify} messages. - * @param message Int32Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Int32Value message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Int32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Int32Value; - - /** - * Decodes an Int32Value message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Int32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Int32Value; - - /** - * Verifies an Int32Value message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Int32Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; - - /** - * Creates a plain object from an Int32Value message. Also converts values to other types if specified. - * @param message Int32Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Int32Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a UInt32Value. */ - interface IUInt32Value { - - /** UInt32Value value */ - value?: (number|null); - } - - /** Represents a UInt32Value. */ - class UInt32Value implements IUInt32Value { - - /** - * Constructs a new UInt32Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUInt32Value); - - /** UInt32Value value. */ - public value: number; - - /** - * Creates a new UInt32Value instance using the specified properties. - * @param [properties] Properties to set - * @returns UInt32Value instance - */ - public static create(properties?: google.protobuf.IUInt32Value): google.protobuf.UInt32Value; - - /** - * Encodes the specified UInt32Value message. Does not implicitly {@link google.protobuf.UInt32Value.verify|verify} messages. - * @param message UInt32Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IUInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified UInt32Value message, length delimited. Does not implicitly {@link google.protobuf.UInt32Value.verify|verify} messages. - * @param message UInt32Value message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IUInt32Value, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a UInt32Value message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns UInt32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UInt32Value; - - /** - * Decodes a UInt32Value message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns UInt32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UInt32Value; - - /** - * Verifies a UInt32Value message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UInt32Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; - - /** - * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. - * @param message UInt32Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this UInt32Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a BoolValue. */ - interface IBoolValue { - - /** BoolValue value */ - value?: (boolean|null); - } - - /** Represents a BoolValue. */ - class BoolValue implements IBoolValue { - - /** - * Constructs a new BoolValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IBoolValue); - - /** BoolValue value. */ - public value: boolean; - - /** - * Creates a new BoolValue instance using the specified properties. - * @param [properties] Properties to set - * @returns BoolValue instance - */ - public static create(properties?: google.protobuf.IBoolValue): google.protobuf.BoolValue; - - /** - * Encodes the specified BoolValue message. Does not implicitly {@link google.protobuf.BoolValue.verify|verify} messages. - * @param message BoolValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IBoolValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified BoolValue message, length delimited. Does not implicitly {@link google.protobuf.BoolValue.verify|verify} messages. - * @param message BoolValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IBoolValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a BoolValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns BoolValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.BoolValue; - - /** - * Decodes a BoolValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns BoolValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.BoolValue; - - /** - * Verifies a BoolValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BoolValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; - - /** - * Creates a plain object from a BoolValue message. Also converts values to other types if specified. - * @param message BoolValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BoolValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a StringValue. */ - interface IStringValue { - - /** StringValue value */ - value?: (string|null); - } - - /** Represents a StringValue. */ - class StringValue implements IStringValue { - - /** - * Constructs a new StringValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IStringValue); - - /** StringValue value. */ - public value: string; - - /** - * Creates a new StringValue instance using the specified properties. - * @param [properties] Properties to set - * @returns StringValue instance - */ - public static create(properties?: google.protobuf.IStringValue): google.protobuf.StringValue; - - /** - * Encodes the specified StringValue message. Does not implicitly {@link google.protobuf.StringValue.verify|verify} messages. - * @param message StringValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IStringValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified StringValue message, length delimited. Does not implicitly {@link google.protobuf.StringValue.verify|verify} messages. - * @param message StringValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IStringValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a StringValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns StringValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.StringValue; - - /** - * Decodes a StringValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns StringValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.StringValue; - - /** - * Verifies a StringValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a StringValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StringValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; - - /** - * Creates a plain object from a StringValue message. Also converts values to other types if specified. - * @param message StringValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this StringValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a BytesValue. */ - interface IBytesValue { - - /** BytesValue value */ - value?: (Uint8Array|null); - } - - /** Represents a BytesValue. */ - class BytesValue implements IBytesValue { - - /** - * Constructs a new BytesValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IBytesValue); - - /** BytesValue value. */ - public value: Uint8Array; - - /** - * Creates a new BytesValue instance using the specified properties. - * @param [properties] Properties to set - * @returns BytesValue instance - */ - public static create(properties?: google.protobuf.IBytesValue): google.protobuf.BytesValue; - - /** - * Encodes the specified BytesValue message. Does not implicitly {@link google.protobuf.BytesValue.verify|verify} messages. - * @param message BytesValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IBytesValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified BytesValue message, length delimited. Does not implicitly {@link google.protobuf.BytesValue.verify|verify} messages. - * @param message BytesValue message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IBytesValue, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a BytesValue message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns BytesValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.BytesValue; - - /** - * Decodes a BytesValue message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns BytesValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.BytesValue; - - /** - * Verifies a BytesValue message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BytesValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; - - /** - * Creates a plain object from a BytesValue message. Also converts values to other types if specified. - * @param message BytesValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BytesValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an Empty. */ - interface IEmpty { - } - - /** Represents an Empty. */ - class Empty implements IEmpty { - - /** - * Constructs a new Empty. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEmpty); - - /** - * Creates a new Empty instance using the specified properties. - * @param [properties] Properties to set - * @returns Empty instance - */ - public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty; - - /** - * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. - * @param message Empty message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. - * @param message Empty message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Empty message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Empty - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty; - - /** - * Decodes an Empty message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Empty - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty; - - /** - * Verifies an Empty message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Empty - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; - - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @param message Empty - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Empty to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an Any. */ - interface IAny { - - /** Any type_url */ - type_url?: (string|null); - - /** Any value */ - value?: (Uint8Array|null); - } - - /** Represents an Any. */ - class Any implements IAny { - - /** - * Constructs a new Any. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IAny); - - /** Any type_url. */ - public type_url: string; - - /** Any value. */ - public value: Uint8Array; - - /** - * Creates a new Any instance using the specified properties. - * @param [properties] Properties to set - * @returns Any instance - */ - public static create(properties?: google.protobuf.IAny): google.protobuf.Any; - - /** - * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. - * @param message Any message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. - * @param message Any message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes an Any message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Any - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; - - /** - * Decodes an Any message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Any - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; - - /** - * Verifies an Any message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Any - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Any; - - /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @param message Any - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Any to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Namespace type. */ - namespace type { - - /** Properties of a LatLng. */ - interface ILatLng { - - /** LatLng latitude */ - latitude?: (number|null); - - /** LatLng longitude */ - longitude?: (number|null); - } - - /** Represents a LatLng. */ - class LatLng implements ILatLng { - - /** - * Constructs a new LatLng. - * @param [properties] Properties to set - */ - constructor(properties?: google.type.ILatLng); - - /** LatLng latitude. */ - public latitude: number; - - /** LatLng longitude. */ - public longitude: number; - - /** - * Creates a new LatLng instance using the specified properties. - * @param [properties] Properties to set - * @returns LatLng instance - */ - public static create(properties?: google.type.ILatLng): google.type.LatLng; - - /** - * Encodes the specified LatLng message. Does not implicitly {@link google.type.LatLng.verify|verify} messages. - * @param message LatLng message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.type.ILatLng, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified LatLng message, length delimited. Does not implicitly {@link google.type.LatLng.verify|verify} messages. - * @param message LatLng message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.type.ILatLng, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a LatLng message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns LatLng - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.type.LatLng; - - /** - * Decodes a LatLng message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns LatLng - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.type.LatLng; - - /** - * Verifies a LatLng message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a LatLng message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns LatLng - */ - public static fromObject(object: { [k: string]: any }): google.type.LatLng; - - /** - * Creates a plain object from a LatLng message. Also converts values to other types if specified. - * @param message LatLng - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this LatLng to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } - - /** Namespace rpc. */ - namespace rpc { - - /** Properties of a Status. */ - interface IStatus { - - /** Status code */ - code?: (number|null); - - /** Status message */ - message?: (string|null); - - /** Status details */ - details?: (google.protobuf.IAny[]|null); - } - - /** Represents a Status. */ - class Status implements IStatus { - - /** - * Constructs a new Status. - * @param [properties] Properties to set - */ - constructor(properties?: google.rpc.IStatus); - - /** Status code. */ - public code: number; - - /** Status message. */ - public message: string; - - /** Status details. */ - public details: google.protobuf.IAny[]; - - /** - * Creates a new Status instance using the specified properties. - * @param [properties] Properties to set - * @returns Status instance - */ - public static create(properties?: google.rpc.IStatus): google.rpc.Status; - - /** - * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. - * @param message Status message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. - * @param message Status message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; - - /** - * Decodes a Status message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns Status - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status; - - /** - * Decodes a Status message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns Status - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status; - - /** - * Verifies a Status message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); - - /** - * Creates a Status message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Status - */ - public static fromObject(object: { [k: string]: any }): google.rpc.Status; - - /** - * Creates a plain object from a Status message. Also converts values to other types if specified. - * @param message Status - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Status to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } -} diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.js b/functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.js deleted file mode 100644 index b3d1db77..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/protos/firestore_proto_api.js +++ /dev/null @@ -1,26706 +0,0 @@ -/*eslint-disable block-scoped-var, no-redeclare, no-control-regex, no-prototype-builtins*/ -"use strict"; - -// Note: This file was manually edited to use "string" instead of "Long" for -// types that can potentially hold large integer values (> 2^53). - -var $protobuf = require("protobufjs/minimal"); - -// Common aliases -var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); - -$root.google = (function() { - - /** - * Namespace google. - * @exports google - * @namespace - */ - var google = {}; - - google.firestore = (function() { - - /** - * Namespace firestore. - * @memberof google - * @namespace - */ - var firestore = {}; - - firestore.v1beta1 = (function() { - - /** - * Namespace v1beta1. - * @memberof google.firestore - * @namespace - */ - var v1beta1 = {}; - - v1beta1.Firestore = (function() { - - /** - * Constructs a new Firestore service. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Firestore - * @extends $protobuf.rpc.Service - * @constructor - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ - function Firestore(rpcImpl, requestDelimited, responseDelimited) { - $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); - } - - (Firestore.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Firestore; - - /** - * Creates new Firestore service using the specified rpc implementation. - * @function create - * @memberof google.firestore.v1beta1.Firestore - * @static - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - * @returns {Firestore} RPC service. Useful where requests and/or responses are streamed. - */ - Firestore.create = function create(rpcImpl, requestDelimited, responseDelimited) { - return new this(rpcImpl, requestDelimited, responseDelimited); - }; - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#getDocument}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef GetDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.Document} [response] Document - */ - - /** - * Calls GetDocument. - * @function getDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IGetDocumentRequest} request GetDocumentRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.GetDocumentCallback} callback Node-style callback called with the error, if any, and Document - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.getDocument = function getDocument(request, callback) { - return this.rpcCall(getDocument, $root.google.firestore.v1beta1.GetDocumentRequest, $root.google.firestore.v1beta1.Document, request, callback); - }; - - /** - * Calls GetDocument. - * @function getDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IGetDocumentRequest} request GetDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#listDocuments}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef ListDocumentsCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.ListDocumentsResponse} [response] ListDocumentsResponse - */ - - /** - * Calls ListDocuments. - * @function listDocuments - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IListDocumentsRequest} request ListDocumentsRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.ListDocumentsCallback} callback Node-style callback called with the error, if any, and ListDocumentsResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.listDocuments = function listDocuments(request, callback) { - return this.rpcCall(listDocuments, $root.google.firestore.v1beta1.ListDocumentsRequest, $root.google.firestore.v1beta1.ListDocumentsResponse, request, callback); - }; - - /** - * Calls ListDocuments. - * @function listDocuments - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IListDocumentsRequest} request ListDocumentsRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#createDocument}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef CreateDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.Document} [response] Document - */ - - /** - * Calls CreateDocument. - * @function createDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.CreateDocumentCallback} callback Node-style callback called with the error, if any, and Document - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.createDocument = function createDocument(request, callback) { - return this.rpcCall(createDocument, $root.google.firestore.v1beta1.CreateDocumentRequest, $root.google.firestore.v1beta1.Document, request, callback); - }; - - /** - * Calls CreateDocument. - * @function createDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#updateDocument}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef UpdateDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.Document} [response] Document - */ - - /** - * Calls UpdateDocument. - * @function updateDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.UpdateDocumentCallback} callback Node-style callback called with the error, if any, and Document - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.updateDocument = function updateDocument(request, callback) { - return this.rpcCall(updateDocument, $root.google.firestore.v1beta1.UpdateDocumentRequest, $root.google.firestore.v1beta1.Document, request, callback); - }; - - /** - * Calls UpdateDocument. - * @function updateDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#deleteDocument}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef DeleteDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.protobuf.Empty} [response] Empty - */ - - /** - * Calls DeleteDocument. - * @function deleteDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.DeleteDocumentCallback} callback Node-style callback called with the error, if any, and Empty - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.deleteDocument = function deleteDocument(request, callback) { - return this.rpcCall(deleteDocument, $root.google.firestore.v1beta1.DeleteDocumentRequest, $root.google.protobuf.Empty, request, callback); - }; - - /** - * Calls DeleteDocument. - * @function deleteDocument - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#batchGetDocuments}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef BatchGetDocumentsCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.BatchGetDocumentsResponse} [response] BatchGetDocumentsResponse - */ - - /** - * Calls BatchGetDocuments. - * @function batchGetDocuments - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.BatchGetDocumentsCallback} callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.batchGetDocuments = function batchGetDocuments(request, callback) { - return this.rpcCall(batchGetDocuments, $root.google.firestore.v1beta1.BatchGetDocumentsRequest, $root.google.firestore.v1beta1.BatchGetDocumentsResponse, request, callback); - }; - - /** - * Calls BatchGetDocuments. - * @function batchGetDocuments - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#beginTransaction}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef BeginTransactionCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.BeginTransactionResponse} [response] BeginTransactionResponse - */ - - /** - * Calls BeginTransaction. - * @function beginTransaction - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.BeginTransactionCallback} callback Node-style callback called with the error, if any, and BeginTransactionResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.beginTransaction = function beginTransaction(request, callback) { - return this.rpcCall(beginTransaction, $root.google.firestore.v1beta1.BeginTransactionRequest, $root.google.firestore.v1beta1.BeginTransactionResponse, request, callback); - }; - - /** - * Calls BeginTransaction. - * @function beginTransaction - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#commit}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef CommitCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.CommitResponse} [response] CommitResponse - */ - - /** - * Calls Commit. - * @function commit - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.ICommitRequest} request CommitRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.CommitCallback} callback Node-style callback called with the error, if any, and CommitResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.commit = function commit(request, callback) { - return this.rpcCall(commit, $root.google.firestore.v1beta1.CommitRequest, $root.google.firestore.v1beta1.CommitResponse, request, callback); - }; - - /** - * Calls Commit. - * @function commit - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.ICommitRequest} request CommitRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#rollback}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef RollbackCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.protobuf.Empty} [response] Empty - */ - - /** - * Calls Rollback. - * @function rollback - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IRollbackRequest} request RollbackRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.RollbackCallback} callback Node-style callback called with the error, if any, and Empty - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.rollback = function rollback(request, callback) { - return this.rpcCall(rollback, $root.google.firestore.v1beta1.RollbackRequest, $root.google.protobuf.Empty, request, callback); - }; - - /** - * Calls Rollback. - * @function rollback - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IRollbackRequest} request RollbackRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#runQuery}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef RunQueryCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.RunQueryResponse} [response] RunQueryResponse - */ - - /** - * Calls RunQuery. - * @function runQuery - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IRunQueryRequest} request RunQueryRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.RunQueryCallback} callback Node-style callback called with the error, if any, and RunQueryResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.runQuery = function runQuery(request, callback) { - return this.rpcCall(runQuery, $root.google.firestore.v1beta1.RunQueryRequest, $root.google.firestore.v1beta1.RunQueryResponse, request, callback); - }; - - /** - * Calls RunQuery. - * @function runQuery - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IRunQueryRequest} request RunQueryRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#write}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef WriteCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.WriteResponse} [response] WriteResponse - */ - - /** - * Calls Write. - * @function write - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IWriteRequest} request WriteRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.WriteCallback} callback Node-style callback called with the error, if any, and WriteResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.write = function write(request, callback) { - return this.rpcCall(write, $root.google.firestore.v1beta1.WriteRequest, $root.google.firestore.v1beta1.WriteResponse, request, callback); - }; - - /** - * Calls Write. - * @function write - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IWriteRequest} request WriteRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#listen}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef ListenCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.ListenResponse} [response] ListenResponse - */ - - /** - * Calls Listen. - * @function listen - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IListenRequest} request ListenRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.ListenCallback} callback Node-style callback called with the error, if any, and ListenResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.listen = function listen(request, callback) { - return this.rpcCall(listen, $root.google.firestore.v1beta1.ListenRequest, $root.google.firestore.v1beta1.ListenResponse, request, callback); - }; - - /** - * Calls Listen. - * @function listen - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IListenRequest} request ListenRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1beta1.Firestore#listCollectionIds}. - * @memberof google.firestore.v1beta1.Firestore - * @typedef ListCollectionIdsCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1beta1.ListCollectionIdsResponse} [response] ListCollectionIdsResponse - */ - - /** - * Calls ListCollectionIds. - * @function listCollectionIds - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object - * @param {google.firestore.v1beta1.Firestore.ListCollectionIdsCallback} callback Node-style callback called with the error, if any, and ListCollectionIdsResponse - * @returns {undefined} - * @variation 1 - */ - Firestore.prototype.listCollectionIds = function listCollectionIds(request, callback) { - return this.rpcCall(listCollectionIds, $root.google.firestore.v1beta1.ListCollectionIdsRequest, $root.google.firestore.v1beta1.ListCollectionIdsResponse, request, callback); - }; - - /** - * Calls ListCollectionIds. - * @function listCollectionIds - * @memberof google.firestore.v1beta1.Firestore - * @instance - * @param {google.firestore.v1beta1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - return Firestore; - })(); - - v1beta1.GetDocumentRequest = (function() { - - /** - * Properties of a GetDocumentRequest. - * @memberof google.firestore.v1beta1 - * @interface IGetDocumentRequest - * @property {string|null} [name] GetDocumentRequest name - * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] GetDocumentRequest mask - * @property {Uint8Array|null} [transaction] GetDocumentRequest transaction - * @property {google.protobuf.ITimestamp|null} [readTime] GetDocumentRequest readTime - */ - - /** - * Constructs a new GetDocumentRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a GetDocumentRequest. - * @implements IGetDocumentRequest - * @constructor - * @param {google.firestore.v1beta1.IGetDocumentRequest=} [properties] Properties to set - */ - function GetDocumentRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * GetDocumentRequest name. - * @member {string} name - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.name = ""; - - /** - * GetDocumentRequest mask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.mask = null; - - /** - * GetDocumentRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.transaction = $util.newBuffer([]); - - /** - * GetDocumentRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * GetDocumentRequest consistencySelector. - * @member {"transaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @instance - */ - Object.defineProperty(GetDocumentRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new GetDocumentRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {google.firestore.v1beta1.IGetDocumentRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.GetDocumentRequest} GetDocumentRequest instance - */ - GetDocumentRequest.create = function create(properties) { - return new GetDocumentRequest(properties); - }; - - /** - * Encodes the specified GetDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.GetDocumentRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {google.firestore.v1beta1.IGetDocumentRequest} message GetDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - GetDocumentRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.mask != null && message.hasOwnProperty("mask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.mask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.transaction); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified GetDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.GetDocumentRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {google.firestore.v1beta1.IGetDocumentRequest} message GetDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - GetDocumentRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a GetDocumentRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.GetDocumentRequest} GetDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - GetDocumentRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.GetDocumentRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - message.mask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - case 3: - message.transaction = reader.bytes(); - break; - case 5: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a GetDocumentRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.GetDocumentRequest} GetDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - GetDocumentRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a GetDocumentRequest message. - * @function verify - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - GetDocumentRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.mask != null && message.hasOwnProperty("mask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.mask); - if (error) - return "mask." + error; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - properties.consistencySelector = 1; - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - if (properties.consistencySelector === 1) - return "consistencySelector: multiple values"; - properties.consistencySelector = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - } - return null; - }; - - /** - * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.GetDocumentRequest} GetDocumentRequest - */ - GetDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.GetDocumentRequest) - return object; - var message = new $root.google.firestore.v1beta1.GetDocumentRequest(); - if (object.name != null) - message.name = String(object.name); - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1beta1.GetDocumentRequest.mask: object expected"); - message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.GetDocumentRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @static - * @param {google.firestore.v1beta1.GetDocumentRequest} message GetDocumentRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - GetDocumentRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.mask = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; - - /** - * Converts this GetDocumentRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.GetDocumentRequest - * @instance - * @returns {Object.} JSON object - */ - GetDocumentRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return GetDocumentRequest; - })(); - - v1beta1.ListDocumentsRequest = (function() { - - /** - * Properties of a ListDocumentsRequest. - * @memberof google.firestore.v1beta1 - * @interface IListDocumentsRequest - * @property {string|null} [parent] ListDocumentsRequest parent - * @property {string|null} [collectionId] ListDocumentsRequest collectionId - * @property {number|null} [pageSize] ListDocumentsRequest pageSize - * @property {string|null} [pageToken] ListDocumentsRequest pageToken - * @property {string|null} [orderBy] ListDocumentsRequest orderBy - * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] ListDocumentsRequest mask - * @property {Uint8Array|null} [transaction] ListDocumentsRequest transaction - * @property {google.protobuf.ITimestamp|null} [readTime] ListDocumentsRequest readTime - * @property {boolean|null} [showMissing] ListDocumentsRequest showMissing - */ - - /** - * Constructs a new ListDocumentsRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a ListDocumentsRequest. - * @implements IListDocumentsRequest - * @constructor - * @param {google.firestore.v1beta1.IListDocumentsRequest=} [properties] Properties to set - */ - function ListDocumentsRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListDocumentsRequest parent. - * @member {string} parent - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.parent = ""; - - /** - * ListDocumentsRequest collectionId. - * @member {string} collectionId - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.collectionId = ""; - - /** - * ListDocumentsRequest pageSize. - * @member {number} pageSize - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.pageSize = 0; - - /** - * ListDocumentsRequest pageToken. - * @member {string} pageToken - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.pageToken = ""; - - /** - * ListDocumentsRequest orderBy. - * @member {string} orderBy - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.orderBy = ""; - - /** - * ListDocumentsRequest mask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.mask = null; - - /** - * ListDocumentsRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.transaction = $util.newBuffer([]); - - /** - * ListDocumentsRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.readTime = null; - - /** - * ListDocumentsRequest showMissing. - * @member {boolean} showMissing - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.showMissing = false; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * ListDocumentsRequest consistencySelector. - * @member {"transaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - */ - Object.defineProperty(ListDocumentsRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new ListDocumentsRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {google.firestore.v1beta1.IListDocumentsRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ListDocumentsRequest} ListDocumentsRequest instance - */ - ListDocumentsRequest.create = function create(properties) { - return new ListDocumentsRequest(properties); - }; - - /** - * Encodes the specified ListDocumentsRequest message. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {google.firestore.v1beta1.IListDocumentsRequest} message ListDocumentsRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListDocumentsRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.parent != null && message.hasOwnProperty("parent")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.collectionId); - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); - if (message.orderBy != null && message.hasOwnProperty("orderBy")) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.orderBy); - if (message.mask != null && message.hasOwnProperty("mask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.mask, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 8, wireType 2 =*/66).bytes(message.transaction); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); - if (message.showMissing != null && message.hasOwnProperty("showMissing")) - writer.uint32(/* id 12, wireType 0 =*/96).bool(message.showMissing); - return writer; - }; - - /** - * Encodes the specified ListDocumentsRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {google.firestore.v1beta1.IListDocumentsRequest} message ListDocumentsRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListDocumentsRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListDocumentsRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ListDocumentsRequest} ListDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListDocumentsRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ListDocumentsRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.parent = reader.string(); - break; - case 2: - message.collectionId = reader.string(); - break; - case 3: - message.pageSize = reader.int32(); - break; - case 4: - message.pageToken = reader.string(); - break; - case 6: - message.orderBy = reader.string(); - break; - case 7: - message.mask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - case 8: - message.transaction = reader.bytes(); - break; - case 10: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - case 12: - message.showMissing = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListDocumentsRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ListDocumentsRequest} ListDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListDocumentsRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListDocumentsRequest message. - * @function verify - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListDocumentsRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.parent != null && message.hasOwnProperty("parent")) - if (!$util.isString(message.parent)) - return "parent: string expected"; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - if (!$util.isString(message.collectionId)) - return "collectionId: string expected"; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - if (!$util.isInteger(message.pageSize)) - return "pageSize: integer expected"; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - if (!$util.isString(message.pageToken)) - return "pageToken: string expected"; - if (message.orderBy != null && message.hasOwnProperty("orderBy")) - if (!$util.isString(message.orderBy)) - return "orderBy: string expected"; - if (message.mask != null && message.hasOwnProperty("mask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.mask); - if (error) - return "mask." + error; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - properties.consistencySelector = 1; - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - if (properties.consistencySelector === 1) - return "consistencySelector: multiple values"; - properties.consistencySelector = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - } - if (message.showMissing != null && message.hasOwnProperty("showMissing")) - if (typeof message.showMissing !== "boolean") - return "showMissing: boolean expected"; - return null; - }; - - /** - * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ListDocumentsRequest} ListDocumentsRequest - */ - ListDocumentsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ListDocumentsRequest) - return object; - var message = new $root.google.firestore.v1beta1.ListDocumentsRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.collectionId != null) - message.collectionId = String(object.collectionId); - if (object.pageSize != null) - message.pageSize = object.pageSize | 0; - if (object.pageToken != null) - message.pageToken = String(object.pageToken); - if (object.orderBy != null) - message.orderBy = String(object.orderBy); - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1beta1.ListDocumentsRequest.mask: object expected"); - message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.ListDocumentsRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.showMissing != null) - message.showMissing = Boolean(object.showMissing); - return message; - }; - - /** - * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @static - * @param {google.firestore.v1beta1.ListDocumentsRequest} message ListDocumentsRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListDocumentsRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - object.collectionId = ""; - object.pageSize = 0; - object.pageToken = ""; - object.orderBy = ""; - object.mask = null; - object.showMissing = false; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - object.collectionId = message.collectionId; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - object.pageSize = message.pageSize; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - object.pageToken = message.pageToken; - if (message.orderBy != null && message.hasOwnProperty("orderBy")) - object.orderBy = message.orderBy; - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - if (message.showMissing != null && message.hasOwnProperty("showMissing")) - object.showMissing = message.showMissing; - return object; - }; - - /** - * Converts this ListDocumentsRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ListDocumentsRequest - * @instance - * @returns {Object.} JSON object - */ - ListDocumentsRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListDocumentsRequest; - })(); - - v1beta1.ListDocumentsResponse = (function() { - - /** - * Properties of a ListDocumentsResponse. - * @memberof google.firestore.v1beta1 - * @interface IListDocumentsResponse - * @property {Array.|null} [documents] ListDocumentsResponse documents - * @property {string|null} [nextPageToken] ListDocumentsResponse nextPageToken - */ - - /** - * Constructs a new ListDocumentsResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a ListDocumentsResponse. - * @implements IListDocumentsResponse - * @constructor - * @param {google.firestore.v1beta1.IListDocumentsResponse=} [properties] Properties to set - */ - function ListDocumentsResponse(properties) { - this.documents = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListDocumentsResponse documents. - * @member {Array.} documents - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @instance - */ - ListDocumentsResponse.prototype.documents = $util.emptyArray; - - /** - * ListDocumentsResponse nextPageToken. - * @member {string} nextPageToken - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @instance - */ - ListDocumentsResponse.prototype.nextPageToken = ""; - - /** - * Creates a new ListDocumentsResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {google.firestore.v1beta1.IListDocumentsResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ListDocumentsResponse} ListDocumentsResponse instance - */ - ListDocumentsResponse.create = function create(properties) { - return new ListDocumentsResponse(properties); - }; - - /** - * Encodes the specified ListDocumentsResponse message. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {google.firestore.v1beta1.IListDocumentsResponse} message ListDocumentsResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListDocumentsResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.documents != null && message.documents.length) - for (var i = 0; i < message.documents.length; ++i) - $root.google.firestore.v1beta1.Document.encode(message.documents[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); - return writer; - }; - - /** - * Encodes the specified ListDocumentsResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListDocumentsResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {google.firestore.v1beta1.IListDocumentsResponse} message ListDocumentsResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListDocumentsResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListDocumentsResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ListDocumentsResponse} ListDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListDocumentsResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ListDocumentsResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.documents && message.documents.length)) - message.documents = []; - message.documents.push($root.google.firestore.v1beta1.Document.decode(reader, reader.uint32())); - break; - case 2: - message.nextPageToken = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListDocumentsResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ListDocumentsResponse} ListDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListDocumentsResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListDocumentsResponse message. - * @function verify - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListDocumentsResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.documents != null && message.hasOwnProperty("documents")) { - if (!Array.isArray(message.documents)) - return "documents: array expected"; - for (var i = 0; i < message.documents.length; ++i) { - var error = $root.google.firestore.v1beta1.Document.verify(message.documents[i]); - if (error) - return "documents." + error; - } - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - if (!$util.isString(message.nextPageToken)) - return "nextPageToken: string expected"; - return null; - }; - - /** - * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ListDocumentsResponse} ListDocumentsResponse - */ - ListDocumentsResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ListDocumentsResponse) - return object; - var message = new $root.google.firestore.v1beta1.ListDocumentsResponse(); - if (object.documents) { - if (!Array.isArray(object.documents)) - throw TypeError(".google.firestore.v1beta1.ListDocumentsResponse.documents: array expected"); - message.documents = []; - for (var i = 0; i < object.documents.length; ++i) { - if (typeof object.documents[i] !== "object") - throw TypeError(".google.firestore.v1beta1.ListDocumentsResponse.documents: object expected"); - message.documents[i] = $root.google.firestore.v1beta1.Document.fromObject(object.documents[i]); - } - } - if (object.nextPageToken != null) - message.nextPageToken = String(object.nextPageToken); - return message; - }; - - /** - * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @static - * @param {google.firestore.v1beta1.ListDocumentsResponse} message ListDocumentsResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListDocumentsResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.documents = []; - if (options.defaults) - object.nextPageToken = ""; - if (message.documents && message.documents.length) { - object.documents = []; - for (var j = 0; j < message.documents.length; ++j) - object.documents[j] = $root.google.firestore.v1beta1.Document.toObject(message.documents[j], options); - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - object.nextPageToken = message.nextPageToken; - return object; - }; - - /** - * Converts this ListDocumentsResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ListDocumentsResponse - * @instance - * @returns {Object.} JSON object - */ - ListDocumentsResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListDocumentsResponse; - })(); - - v1beta1.CreateDocumentRequest = (function() { - - /** - * Properties of a CreateDocumentRequest. - * @memberof google.firestore.v1beta1 - * @interface ICreateDocumentRequest - * @property {string|null} [parent] CreateDocumentRequest parent - * @property {string|null} [collectionId] CreateDocumentRequest collectionId - * @property {string|null} [documentId] CreateDocumentRequest documentId - * @property {google.firestore.v1beta1.IDocument|null} [document] CreateDocumentRequest document - * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] CreateDocumentRequest mask - */ - - /** - * Constructs a new CreateDocumentRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a CreateDocumentRequest. - * @implements ICreateDocumentRequest - * @constructor - * @param {google.firestore.v1beta1.ICreateDocumentRequest=} [properties] Properties to set - */ - function CreateDocumentRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CreateDocumentRequest parent. - * @member {string} parent - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.parent = ""; - - /** - * CreateDocumentRequest collectionId. - * @member {string} collectionId - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.collectionId = ""; - - /** - * CreateDocumentRequest documentId. - * @member {string} documentId - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.documentId = ""; - - /** - * CreateDocumentRequest document. - * @member {google.firestore.v1beta1.IDocument|null|undefined} document - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.document = null; - - /** - * CreateDocumentRequest mask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.mask = null; - - /** - * Creates a new CreateDocumentRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {google.firestore.v1beta1.ICreateDocumentRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.CreateDocumentRequest} CreateDocumentRequest instance - */ - CreateDocumentRequest.create = function create(properties) { - return new CreateDocumentRequest(properties); - }; - - /** - * Encodes the specified CreateDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.CreateDocumentRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {google.firestore.v1beta1.ICreateDocumentRequest} message CreateDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CreateDocumentRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.parent != null && message.hasOwnProperty("parent")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.collectionId); - if (message.documentId != null && message.hasOwnProperty("documentId")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.documentId); - if (message.document != null && message.hasOwnProperty("document")) - $root.google.firestore.v1beta1.Document.encode(message.document, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.mask != null && message.hasOwnProperty("mask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.mask, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified CreateDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.CreateDocumentRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {google.firestore.v1beta1.ICreateDocumentRequest} message CreateDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CreateDocumentRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a CreateDocumentRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.CreateDocumentRequest} CreateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CreateDocumentRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.CreateDocumentRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.parent = reader.string(); - break; - case 2: - message.collectionId = reader.string(); - break; - case 3: - message.documentId = reader.string(); - break; - case 4: - message.document = $root.google.firestore.v1beta1.Document.decode(reader, reader.uint32()); - break; - case 5: - message.mask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a CreateDocumentRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.CreateDocumentRequest} CreateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CreateDocumentRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a CreateDocumentRequest message. - * @function verify - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - CreateDocumentRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.parent != null && message.hasOwnProperty("parent")) - if (!$util.isString(message.parent)) - return "parent: string expected"; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - if (!$util.isString(message.collectionId)) - return "collectionId: string expected"; - if (message.documentId != null && message.hasOwnProperty("documentId")) - if (!$util.isString(message.documentId)) - return "documentId: string expected"; - if (message.document != null && message.hasOwnProperty("document")) { - var error = $root.google.firestore.v1beta1.Document.verify(message.document); - if (error) - return "document." + error; - } - if (message.mask != null && message.hasOwnProperty("mask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.mask); - if (error) - return "mask." + error; - } - return null; - }; - - /** - * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.CreateDocumentRequest} CreateDocumentRequest - */ - CreateDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.CreateDocumentRequest) - return object; - var message = new $root.google.firestore.v1beta1.CreateDocumentRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.collectionId != null) - message.collectionId = String(object.collectionId); - if (object.documentId != null) - message.documentId = String(object.documentId); - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1beta1.CreateDocumentRequest.document: object expected"); - message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); - } - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1beta1.CreateDocumentRequest.mask: object expected"); - message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); - } - return message; - }; - - /** - * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @static - * @param {google.firestore.v1beta1.CreateDocumentRequest} message CreateDocumentRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CreateDocumentRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - object.collectionId = ""; - object.documentId = ""; - object.document = null; - object.mask = null; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - object.collectionId = message.collectionId; - if (message.documentId != null && message.hasOwnProperty("documentId")) - object.documentId = message.documentId; - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); - return object; - }; - - /** - * Converts this CreateDocumentRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.CreateDocumentRequest - * @instance - * @returns {Object.} JSON object - */ - CreateDocumentRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return CreateDocumentRequest; - })(); - - v1beta1.UpdateDocumentRequest = (function() { - - /** - * Properties of an UpdateDocumentRequest. - * @memberof google.firestore.v1beta1 - * @interface IUpdateDocumentRequest - * @property {google.firestore.v1beta1.IDocument|null} [document] UpdateDocumentRequest document - * @property {google.firestore.v1beta1.IDocumentMask|null} [updateMask] UpdateDocumentRequest updateMask - * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] UpdateDocumentRequest mask - * @property {google.firestore.v1beta1.IPrecondition|null} [currentDocument] UpdateDocumentRequest currentDocument - */ - - /** - * Constructs a new UpdateDocumentRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents an UpdateDocumentRequest. - * @implements IUpdateDocumentRequest - * @constructor - * @param {google.firestore.v1beta1.IUpdateDocumentRequest=} [properties] Properties to set - */ - function UpdateDocumentRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * UpdateDocumentRequest document. - * @member {google.firestore.v1beta1.IDocument|null|undefined} document - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.document = null; - - /** - * UpdateDocumentRequest updateMask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} updateMask - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.updateMask = null; - - /** - * UpdateDocumentRequest mask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.mask = null; - - /** - * UpdateDocumentRequest currentDocument. - * @member {google.firestore.v1beta1.IPrecondition|null|undefined} currentDocument - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.currentDocument = null; - - /** - * Creates a new UpdateDocumentRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {google.firestore.v1beta1.IUpdateDocumentRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.UpdateDocumentRequest} UpdateDocumentRequest instance - */ - UpdateDocumentRequest.create = function create(properties) { - return new UpdateDocumentRequest(properties); - }; - - /** - * Encodes the specified UpdateDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.UpdateDocumentRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {google.firestore.v1beta1.IUpdateDocumentRequest} message UpdateDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UpdateDocumentRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.document != null && message.hasOwnProperty("document")) - $root.google.firestore.v1beta1.Document.encode(message.document, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.updateMask != null && message.hasOwnProperty("updateMask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.mask != null && message.hasOwnProperty("mask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.mask, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - $root.google.firestore.v1beta1.Precondition.encode(message.currentDocument, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified UpdateDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.UpdateDocumentRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {google.firestore.v1beta1.IUpdateDocumentRequest} message UpdateDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UpdateDocumentRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an UpdateDocumentRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.UpdateDocumentRequest} UpdateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UpdateDocumentRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.UpdateDocumentRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.document = $root.google.firestore.v1beta1.Document.decode(reader, reader.uint32()); - break; - case 2: - message.updateMask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - case 3: - message.mask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - case 4: - message.currentDocument = $root.google.firestore.v1beta1.Precondition.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an UpdateDocumentRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.UpdateDocumentRequest} UpdateDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UpdateDocumentRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an UpdateDocumentRequest message. - * @function verify - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - UpdateDocumentRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.document != null && message.hasOwnProperty("document")) { - var error = $root.google.firestore.v1beta1.Document.verify(message.document); - if (error) - return "document." + error; - } - if (message.updateMask != null && message.hasOwnProperty("updateMask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.updateMask); - if (error) - return "updateMask." + error; - } - if (message.mask != null && message.hasOwnProperty("mask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.mask); - if (error) - return "mask." + error; - } - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) { - var error = $root.google.firestore.v1beta1.Precondition.verify(message.currentDocument); - if (error) - return "currentDocument." + error; - } - return null; - }; - - /** - * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.UpdateDocumentRequest} UpdateDocumentRequest - */ - UpdateDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.UpdateDocumentRequest) - return object; - var message = new $root.google.firestore.v1beta1.UpdateDocumentRequest(); - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.document: object expected"); - message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); - } - if (object.updateMask != null) { - if (typeof object.updateMask !== "object") - throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.updateMask: object expected"); - message.updateMask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.updateMask); - } - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.mask: object expected"); - message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); - } - if (object.currentDocument != null) { - if (typeof object.currentDocument !== "object") - throw TypeError(".google.firestore.v1beta1.UpdateDocumentRequest.currentDocument: object expected"); - message.currentDocument = $root.google.firestore.v1beta1.Precondition.fromObject(object.currentDocument); - } - return message; - }; - - /** - * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @static - * @param {google.firestore.v1beta1.UpdateDocumentRequest} message UpdateDocumentRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UpdateDocumentRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.document = null; - object.updateMask = null; - object.mask = null; - object.currentDocument = null; - } - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); - if (message.updateMask != null && message.hasOwnProperty("updateMask")) - object.updateMask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.updateMask, options); - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - object.currentDocument = $root.google.firestore.v1beta1.Precondition.toObject(message.currentDocument, options); - return object; - }; - - /** - * Converts this UpdateDocumentRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.UpdateDocumentRequest - * @instance - * @returns {Object.} JSON object - */ - UpdateDocumentRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return UpdateDocumentRequest; - })(); - - v1beta1.DeleteDocumentRequest = (function() { - - /** - * Properties of a DeleteDocumentRequest. - * @memberof google.firestore.v1beta1 - * @interface IDeleteDocumentRequest - * @property {string|null} [name] DeleteDocumentRequest name - * @property {google.firestore.v1beta1.IPrecondition|null} [currentDocument] DeleteDocumentRequest currentDocument - */ - - /** - * Constructs a new DeleteDocumentRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a DeleteDocumentRequest. - * @implements IDeleteDocumentRequest - * @constructor - * @param {google.firestore.v1beta1.IDeleteDocumentRequest=} [properties] Properties to set - */ - function DeleteDocumentRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DeleteDocumentRequest name. - * @member {string} name - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @instance - */ - DeleteDocumentRequest.prototype.name = ""; - - /** - * DeleteDocumentRequest currentDocument. - * @member {google.firestore.v1beta1.IPrecondition|null|undefined} currentDocument - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @instance - */ - DeleteDocumentRequest.prototype.currentDocument = null; - - /** - * Creates a new DeleteDocumentRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {google.firestore.v1beta1.IDeleteDocumentRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DeleteDocumentRequest} DeleteDocumentRequest instance - */ - DeleteDocumentRequest.create = function create(properties) { - return new DeleteDocumentRequest(properties); - }; - - /** - * Encodes the specified DeleteDocumentRequest message. Does not implicitly {@link google.firestore.v1beta1.DeleteDocumentRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {google.firestore.v1beta1.IDeleteDocumentRequest} message DeleteDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DeleteDocumentRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - $root.google.firestore.v1beta1.Precondition.encode(message.currentDocument, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified DeleteDocumentRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DeleteDocumentRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {google.firestore.v1beta1.IDeleteDocumentRequest} message DeleteDocumentRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DeleteDocumentRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DeleteDocumentRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DeleteDocumentRequest} DeleteDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DeleteDocumentRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DeleteDocumentRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - message.currentDocument = $root.google.firestore.v1beta1.Precondition.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DeleteDocumentRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DeleteDocumentRequest} DeleteDocumentRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DeleteDocumentRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DeleteDocumentRequest message. - * @function verify - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DeleteDocumentRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) { - var error = $root.google.firestore.v1beta1.Precondition.verify(message.currentDocument); - if (error) - return "currentDocument." + error; - } - return null; - }; - - /** - * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DeleteDocumentRequest} DeleteDocumentRequest - */ - DeleteDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DeleteDocumentRequest) - return object; - var message = new $root.google.firestore.v1beta1.DeleteDocumentRequest(); - if (object.name != null) - message.name = String(object.name); - if (object.currentDocument != null) { - if (typeof object.currentDocument !== "object") - throw TypeError(".google.firestore.v1beta1.DeleteDocumentRequest.currentDocument: object expected"); - message.currentDocument = $root.google.firestore.v1beta1.Precondition.fromObject(object.currentDocument); - } - return message; - }; - - /** - * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @static - * @param {google.firestore.v1beta1.DeleteDocumentRequest} message DeleteDocumentRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DeleteDocumentRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.currentDocument = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - object.currentDocument = $root.google.firestore.v1beta1.Precondition.toObject(message.currentDocument, options); - return object; - }; - - /** - * Converts this DeleteDocumentRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DeleteDocumentRequest - * @instance - * @returns {Object.} JSON object - */ - DeleteDocumentRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DeleteDocumentRequest; - })(); - - v1beta1.BatchGetDocumentsRequest = (function() { - - /** - * Properties of a BatchGetDocumentsRequest. - * @memberof google.firestore.v1beta1 - * @interface IBatchGetDocumentsRequest - * @property {string|null} [database] BatchGetDocumentsRequest database - * @property {Array.|null} [documents] BatchGetDocumentsRequest documents - * @property {google.firestore.v1beta1.IDocumentMask|null} [mask] BatchGetDocumentsRequest mask - * @property {Uint8Array|null} [transaction] BatchGetDocumentsRequest transaction - * @property {google.firestore.v1beta1.ITransactionOptions|null} [newTransaction] BatchGetDocumentsRequest newTransaction - * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsRequest readTime - */ - - /** - * Constructs a new BatchGetDocumentsRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a BatchGetDocumentsRequest. - * @implements IBatchGetDocumentsRequest - * @constructor - * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest=} [properties] Properties to set - */ - function BatchGetDocumentsRequest(properties) { - this.documents = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BatchGetDocumentsRequest database. - * @member {string} database - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - BatchGetDocumentsRequest.prototype.database = ""; - - /** - * BatchGetDocumentsRequest documents. - * @member {Array.} documents - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - BatchGetDocumentsRequest.prototype.documents = $util.emptyArray; - - /** - * BatchGetDocumentsRequest mask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - BatchGetDocumentsRequest.prototype.mask = null; - - /** - * BatchGetDocumentsRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - BatchGetDocumentsRequest.prototype.transaction = $util.newBuffer([]); - - /** - * BatchGetDocumentsRequest newTransaction. - * @member {google.firestore.v1beta1.ITransactionOptions|null|undefined} newTransaction - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - BatchGetDocumentsRequest.prototype.newTransaction = null; - - /** - * BatchGetDocumentsRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - BatchGetDocumentsRequest.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * BatchGetDocumentsRequest consistencySelector. - * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - */ - Object.defineProperty(BatchGetDocumentsRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new BatchGetDocumentsRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.BatchGetDocumentsRequest} BatchGetDocumentsRequest instance - */ - BatchGetDocumentsRequest.create = function create(properties) { - return new BatchGetDocumentsRequest(properties); - }; - - /** - * Encodes the specified BatchGetDocumentsRequest message. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest} message BatchGetDocumentsRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BatchGetDocumentsRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.database != null && message.hasOwnProperty("database")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); - if (message.documents != null && message.documents.length) - for (var i = 0; i < message.documents.length; ++i) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.documents[i]); - if (message.mask != null && message.hasOwnProperty("mask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.mask, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.transaction); - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) - $root.google.firestore.v1beta1.TransactionOptions.encode(message.newTransaction, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified BatchGetDocumentsRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {google.firestore.v1beta1.IBatchGetDocumentsRequest} message BatchGetDocumentsRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BatchGetDocumentsRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BatchGetDocumentsRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.BatchGetDocumentsRequest} BatchGetDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BatchGetDocumentsRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.BatchGetDocumentsRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.database = reader.string(); - break; - case 2: - if (!(message.documents && message.documents.length)) - message.documents = []; - message.documents.push(reader.string()); - break; - case 3: - message.mask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - case 4: - message.transaction = reader.bytes(); - break; - case 5: - message.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.decode(reader, reader.uint32()); - break; - case 7: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BatchGetDocumentsRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.BatchGetDocumentsRequest} BatchGetDocumentsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BatchGetDocumentsRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BatchGetDocumentsRequest message. - * @function verify - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BatchGetDocumentsRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.database != null && message.hasOwnProperty("database")) - if (!$util.isString(message.database)) - return "database: string expected"; - if (message.documents != null && message.hasOwnProperty("documents")) { - if (!Array.isArray(message.documents)) - return "documents: array expected"; - for (var i = 0; i < message.documents.length; ++i) - if (!$util.isString(message.documents[i])) - return "documents: string[] expected"; - } - if (message.mask != null && message.hasOwnProperty("mask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.mask); - if (error) - return "mask." + error; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - properties.consistencySelector = 1; - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - if (properties.consistencySelector === 1) - return "consistencySelector: multiple values"; - properties.consistencySelector = 1; - { - var error = $root.google.firestore.v1beta1.TransactionOptions.verify(message.newTransaction); - if (error) - return "newTransaction." + error; - } - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - if (properties.consistencySelector === 1) - return "consistencySelector: multiple values"; - properties.consistencySelector = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - } - return null; - }; - - /** - * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.BatchGetDocumentsRequest} BatchGetDocumentsRequest - */ - BatchGetDocumentsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.BatchGetDocumentsRequest) - return object; - var message = new $root.google.firestore.v1beta1.BatchGetDocumentsRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.documents) { - if (!Array.isArray(object.documents)) - throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.documents: array expected"); - message.documents = []; - for (var i = 0; i < object.documents.length; ++i) - message.documents[i] = String(object.documents[i]); - } - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.mask: object expected"); - message.mask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.mask); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - if (object.newTransaction != null) { - if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.newTransaction: object expected"); - message.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.fromObject(object.newTransaction); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @static - * @param {google.firestore.v1beta1.BatchGetDocumentsRequest} message BatchGetDocumentsRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BatchGetDocumentsRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.documents = []; - if (options.defaults) { - object.database = ""; - object.mask = null; - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.documents && message.documents.length) { - object.documents = []; - for (var j = 0; j < message.documents.length; ++j) - object.documents[j] = message.documents[j]; - } - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.mask, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - object.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.toObject(message.newTransaction, options); - if (options.oneofs) - object.consistencySelector = "newTransaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; - - /** - * Converts this BatchGetDocumentsRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.BatchGetDocumentsRequest - * @instance - * @returns {Object.} JSON object - */ - BatchGetDocumentsRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return BatchGetDocumentsRequest; - })(); - - v1beta1.BatchGetDocumentsResponse = (function() { - - /** - * Properties of a BatchGetDocumentsResponse. - * @memberof google.firestore.v1beta1 - * @interface IBatchGetDocumentsResponse - * @property {google.firestore.v1beta1.IDocument|null} [found] BatchGetDocumentsResponse found - * @property {string|null} [missing] BatchGetDocumentsResponse missing - * @property {Uint8Array|null} [transaction] BatchGetDocumentsResponse transaction - * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsResponse readTime - */ - - /** - * Constructs a new BatchGetDocumentsResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a BatchGetDocumentsResponse. - * @implements IBatchGetDocumentsResponse - * @constructor - * @param {google.firestore.v1beta1.IBatchGetDocumentsResponse=} [properties] Properties to set - */ - function BatchGetDocumentsResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BatchGetDocumentsResponse found. - * @member {google.firestore.v1beta1.IDocument|null|undefined} found - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @instance - */ - BatchGetDocumentsResponse.prototype.found = null; - - /** - * BatchGetDocumentsResponse missing. - * @member {string} missing - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @instance - */ - BatchGetDocumentsResponse.prototype.missing = ""; - - /** - * BatchGetDocumentsResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @instance - */ - BatchGetDocumentsResponse.prototype.transaction = $util.newBuffer([]); - - /** - * BatchGetDocumentsResponse readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @instance - */ - BatchGetDocumentsResponse.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * BatchGetDocumentsResponse result. - * @member {"found"|"missing"|undefined} result - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @instance - */ - Object.defineProperty(BatchGetDocumentsResponse.prototype, "result", { - get: $util.oneOfGetter($oneOfFields = ["found", "missing"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new BatchGetDocumentsResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {google.firestore.v1beta1.IBatchGetDocumentsResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.BatchGetDocumentsResponse} BatchGetDocumentsResponse instance - */ - BatchGetDocumentsResponse.create = function create(properties) { - return new BatchGetDocumentsResponse(properties); - }; - - /** - * Encodes the specified BatchGetDocumentsResponse message. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {google.firestore.v1beta1.IBatchGetDocumentsResponse} message BatchGetDocumentsResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BatchGetDocumentsResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.found != null && message.hasOwnProperty("found")) - $root.google.firestore.v1beta1.Document.encode(message.found, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.missing != null && message.hasOwnProperty("missing")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.missing); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.transaction); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified BatchGetDocumentsResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BatchGetDocumentsResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {google.firestore.v1beta1.IBatchGetDocumentsResponse} message BatchGetDocumentsResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BatchGetDocumentsResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BatchGetDocumentsResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.BatchGetDocumentsResponse} BatchGetDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BatchGetDocumentsResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.BatchGetDocumentsResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.found = $root.google.firestore.v1beta1.Document.decode(reader, reader.uint32()); - break; - case 2: - message.missing = reader.string(); - break; - case 3: - message.transaction = reader.bytes(); - break; - case 4: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BatchGetDocumentsResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.BatchGetDocumentsResponse} BatchGetDocumentsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BatchGetDocumentsResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BatchGetDocumentsResponse message. - * @function verify - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BatchGetDocumentsResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.found != null && message.hasOwnProperty("found")) { - properties.result = 1; - { - var error = $root.google.firestore.v1beta1.Document.verify(message.found); - if (error) - return "found." + error; - } - } - if (message.missing != null && message.hasOwnProperty("missing")) { - if (properties.result === 1) - return "result: multiple values"; - properties.result = 1; - if (!$util.isString(message.missing)) - return "missing: string expected"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - return null; - }; - - /** - * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.BatchGetDocumentsResponse} BatchGetDocumentsResponse - */ - BatchGetDocumentsResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.BatchGetDocumentsResponse) - return object; - var message = new $root.google.firestore.v1beta1.BatchGetDocumentsResponse(); - if (object.found != null) { - if (typeof object.found !== "object") - throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsResponse.found: object expected"); - message.found = $root.google.firestore.v1beta1.Document.fromObject(object.found); - } - if (object.missing != null) - message.missing = String(object.missing); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.BatchGetDocumentsResponse.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @static - * @param {google.firestore.v1beta1.BatchGetDocumentsResponse} message BatchGetDocumentsResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BatchGetDocumentsResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.transaction = options.bytes === String ? "" : []; - object.readTime = null; - } - if (message.found != null && message.hasOwnProperty("found")) { - object.found = $root.google.firestore.v1beta1.Document.toObject(message.found, options); - if (options.oneofs) - object.result = "found"; - } - if (message.missing != null && message.hasOwnProperty("missing")) { - object.missing = message.missing; - if (options.oneofs) - object.result = "missing"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - return object; - }; - - /** - * Converts this BatchGetDocumentsResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.BatchGetDocumentsResponse - * @instance - * @returns {Object.} JSON object - */ - BatchGetDocumentsResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return BatchGetDocumentsResponse; - })(); - - v1beta1.BeginTransactionRequest = (function() { - - /** - * Properties of a BeginTransactionRequest. - * @memberof google.firestore.v1beta1 - * @interface IBeginTransactionRequest - * @property {string|null} [database] BeginTransactionRequest database - * @property {google.firestore.v1beta1.ITransactionOptions|null} [options] BeginTransactionRequest options - */ - - /** - * Constructs a new BeginTransactionRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a BeginTransactionRequest. - * @implements IBeginTransactionRequest - * @constructor - * @param {google.firestore.v1beta1.IBeginTransactionRequest=} [properties] Properties to set - */ - function BeginTransactionRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BeginTransactionRequest database. - * @member {string} database - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @instance - */ - BeginTransactionRequest.prototype.database = ""; - - /** - * BeginTransactionRequest options. - * @member {google.firestore.v1beta1.ITransactionOptions|null|undefined} options - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @instance - */ - BeginTransactionRequest.prototype.options = null; - - /** - * Creates a new BeginTransactionRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {google.firestore.v1beta1.IBeginTransactionRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.BeginTransactionRequest} BeginTransactionRequest instance - */ - BeginTransactionRequest.create = function create(properties) { - return new BeginTransactionRequest(properties); - }; - - /** - * Encodes the specified BeginTransactionRequest message. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {google.firestore.v1beta1.IBeginTransactionRequest} message BeginTransactionRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BeginTransactionRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.database != null && message.hasOwnProperty("database")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.firestore.v1beta1.TransactionOptions.encode(message.options, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified BeginTransactionRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {google.firestore.v1beta1.IBeginTransactionRequest} message BeginTransactionRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BeginTransactionRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BeginTransactionRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.BeginTransactionRequest} BeginTransactionRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BeginTransactionRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.BeginTransactionRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.database = reader.string(); - break; - case 2: - message.options = $root.google.firestore.v1beta1.TransactionOptions.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BeginTransactionRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.BeginTransactionRequest} BeginTransactionRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BeginTransactionRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BeginTransactionRequest message. - * @function verify - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BeginTransactionRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.database != null && message.hasOwnProperty("database")) - if (!$util.isString(message.database)) - return "database: string expected"; - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.firestore.v1beta1.TransactionOptions.verify(message.options); - if (error) - return "options." + error; - } - return null; - }; - - /** - * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.BeginTransactionRequest} BeginTransactionRequest - */ - BeginTransactionRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.BeginTransactionRequest) - return object; - var message = new $root.google.firestore.v1beta1.BeginTransactionRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.firestore.v1beta1.BeginTransactionRequest.options: object expected"); - message.options = $root.google.firestore.v1beta1.TransactionOptions.fromObject(object.options); - } - return message; - }; - - /** - * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @static - * @param {google.firestore.v1beta1.BeginTransactionRequest} message BeginTransactionRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BeginTransactionRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.database = ""; - object.options = null; - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.firestore.v1beta1.TransactionOptions.toObject(message.options, options); - return object; - }; - - /** - * Converts this BeginTransactionRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.BeginTransactionRequest - * @instance - * @returns {Object.} JSON object - */ - BeginTransactionRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return BeginTransactionRequest; - })(); - - v1beta1.BeginTransactionResponse = (function() { - - /** - * Properties of a BeginTransactionResponse. - * @memberof google.firestore.v1beta1 - * @interface IBeginTransactionResponse - * @property {Uint8Array|null} [transaction] BeginTransactionResponse transaction - */ - - /** - * Constructs a new BeginTransactionResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a BeginTransactionResponse. - * @implements IBeginTransactionResponse - * @constructor - * @param {google.firestore.v1beta1.IBeginTransactionResponse=} [properties] Properties to set - */ - function BeginTransactionResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BeginTransactionResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @instance - */ - BeginTransactionResponse.prototype.transaction = $util.newBuffer([]); - - /** - * Creates a new BeginTransactionResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {google.firestore.v1beta1.IBeginTransactionResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.BeginTransactionResponse} BeginTransactionResponse instance - */ - BeginTransactionResponse.create = function create(properties) { - return new BeginTransactionResponse(properties); - }; - - /** - * Encodes the specified BeginTransactionResponse message. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {google.firestore.v1beta1.IBeginTransactionResponse} message BeginTransactionResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BeginTransactionResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.transaction); - return writer; - }; - - /** - * Encodes the specified BeginTransactionResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.BeginTransactionResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {google.firestore.v1beta1.IBeginTransactionResponse} message BeginTransactionResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BeginTransactionResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BeginTransactionResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.BeginTransactionResponse} BeginTransactionResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BeginTransactionResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.BeginTransactionResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.transaction = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BeginTransactionResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.BeginTransactionResponse} BeginTransactionResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BeginTransactionResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BeginTransactionResponse message. - * @function verify - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BeginTransactionResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.transaction != null && message.hasOwnProperty("transaction")) - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - return null; - }; - - /** - * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.BeginTransactionResponse} BeginTransactionResponse - */ - BeginTransactionResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.BeginTransactionResponse) - return object; - var message = new $root.google.firestore.v1beta1.BeginTransactionResponse(); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - return message; - }; - - /** - * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @static - * @param {google.firestore.v1beta1.BeginTransactionResponse} message BeginTransactionResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BeginTransactionResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.transaction = options.bytes === String ? "" : []; - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - return object; - }; - - /** - * Converts this BeginTransactionResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.BeginTransactionResponse - * @instance - * @returns {Object.} JSON object - */ - BeginTransactionResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return BeginTransactionResponse; - })(); - - v1beta1.CommitRequest = (function() { - - /** - * Properties of a CommitRequest. - * @memberof google.firestore.v1beta1 - * @interface ICommitRequest - * @property {string|null} [database] CommitRequest database - * @property {Array.|null} [writes] CommitRequest writes - * @property {Uint8Array|null} [transaction] CommitRequest transaction - */ - - /** - * Constructs a new CommitRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a CommitRequest. - * @implements ICommitRequest - * @constructor - * @param {google.firestore.v1beta1.ICommitRequest=} [properties] Properties to set - */ - function CommitRequest(properties) { - this.writes = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CommitRequest database. - * @member {string} database - * @memberof google.firestore.v1beta1.CommitRequest - * @instance - */ - CommitRequest.prototype.database = ""; - - /** - * CommitRequest writes. - * @member {Array.} writes - * @memberof google.firestore.v1beta1.CommitRequest - * @instance - */ - CommitRequest.prototype.writes = $util.emptyArray; - - /** - * CommitRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.CommitRequest - * @instance - */ - CommitRequest.prototype.transaction = $util.newBuffer([]); - - /** - * Creates a new CommitRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {google.firestore.v1beta1.ICommitRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.CommitRequest} CommitRequest instance - */ - CommitRequest.create = function create(properties) { - return new CommitRequest(properties); - }; - - /** - * Encodes the specified CommitRequest message. Does not implicitly {@link google.firestore.v1beta1.CommitRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {google.firestore.v1beta1.ICommitRequest} message CommitRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CommitRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.database != null && message.hasOwnProperty("database")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); - if (message.writes != null && message.writes.length) - for (var i = 0; i < message.writes.length; ++i) - $root.google.firestore.v1beta1.Write.encode(message.writes[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.transaction); - return writer; - }; - - /** - * Encodes the specified CommitRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.CommitRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {google.firestore.v1beta1.ICommitRequest} message CommitRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CommitRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a CommitRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.CommitRequest} CommitRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CommitRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.CommitRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.database = reader.string(); - break; - case 2: - if (!(message.writes && message.writes.length)) - message.writes = []; - message.writes.push($root.google.firestore.v1beta1.Write.decode(reader, reader.uint32())); - break; - case 3: - message.transaction = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a CommitRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.CommitRequest} CommitRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CommitRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a CommitRequest message. - * @function verify - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - CommitRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.database != null && message.hasOwnProperty("database")) - if (!$util.isString(message.database)) - return "database: string expected"; - if (message.writes != null && message.hasOwnProperty("writes")) { - if (!Array.isArray(message.writes)) - return "writes: array expected"; - for (var i = 0; i < message.writes.length; ++i) { - var error = $root.google.firestore.v1beta1.Write.verify(message.writes[i]); - if (error) - return "writes." + error; - } - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - return null; - }; - - /** - * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.CommitRequest} CommitRequest - */ - CommitRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.CommitRequest) - return object; - var message = new $root.google.firestore.v1beta1.CommitRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.writes) { - if (!Array.isArray(object.writes)) - throw TypeError(".google.firestore.v1beta1.CommitRequest.writes: array expected"); - message.writes = []; - for (var i = 0; i < object.writes.length; ++i) { - if (typeof object.writes[i] !== "object") - throw TypeError(".google.firestore.v1beta1.CommitRequest.writes: object expected"); - message.writes[i] = $root.google.firestore.v1beta1.Write.fromObject(object.writes[i]); - } - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - return message; - }; - - /** - * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.CommitRequest - * @static - * @param {google.firestore.v1beta1.CommitRequest} message CommitRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CommitRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.writes = []; - if (options.defaults) { - object.database = ""; - object.transaction = options.bytes === String ? "" : []; - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.writes && message.writes.length) { - object.writes = []; - for (var j = 0; j < message.writes.length; ++j) - object.writes[j] = $root.google.firestore.v1beta1.Write.toObject(message.writes[j], options); - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - return object; - }; - - /** - * Converts this CommitRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.CommitRequest - * @instance - * @returns {Object.} JSON object - */ - CommitRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return CommitRequest; - })(); - - v1beta1.CommitResponse = (function() { - - /** - * Properties of a CommitResponse. - * @memberof google.firestore.v1beta1 - * @interface ICommitResponse - * @property {Array.|null} [writeResults] CommitResponse writeResults - * @property {google.protobuf.ITimestamp|null} [commitTime] CommitResponse commitTime - */ - - /** - * Constructs a new CommitResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a CommitResponse. - * @implements ICommitResponse - * @constructor - * @param {google.firestore.v1beta1.ICommitResponse=} [properties] Properties to set - */ - function CommitResponse(properties) { - this.writeResults = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CommitResponse writeResults. - * @member {Array.} writeResults - * @memberof google.firestore.v1beta1.CommitResponse - * @instance - */ - CommitResponse.prototype.writeResults = $util.emptyArray; - - /** - * CommitResponse commitTime. - * @member {google.protobuf.ITimestamp|null|undefined} commitTime - * @memberof google.firestore.v1beta1.CommitResponse - * @instance - */ - CommitResponse.prototype.commitTime = null; - - /** - * Creates a new CommitResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {google.firestore.v1beta1.ICommitResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.CommitResponse} CommitResponse instance - */ - CommitResponse.create = function create(properties) { - return new CommitResponse(properties); - }; - - /** - * Encodes the specified CommitResponse message. Does not implicitly {@link google.firestore.v1beta1.CommitResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {google.firestore.v1beta1.ICommitResponse} message CommitResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CommitResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.writeResults != null && message.writeResults.length) - for (var i = 0; i < message.writeResults.length; ++i) - $root.google.firestore.v1beta1.WriteResult.encode(message.writeResults[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.commitTime != null && message.hasOwnProperty("commitTime")) - $root.google.protobuf.Timestamp.encode(message.commitTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified CommitResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.CommitResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {google.firestore.v1beta1.ICommitResponse} message CommitResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CommitResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a CommitResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.CommitResponse} CommitResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CommitResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.CommitResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.writeResults && message.writeResults.length)) - message.writeResults = []; - message.writeResults.push($root.google.firestore.v1beta1.WriteResult.decode(reader, reader.uint32())); - break; - case 2: - message.commitTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a CommitResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.CommitResponse} CommitResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CommitResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a CommitResponse message. - * @function verify - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - CommitResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.writeResults != null && message.hasOwnProperty("writeResults")) { - if (!Array.isArray(message.writeResults)) - return "writeResults: array expected"; - for (var i = 0; i < message.writeResults.length; ++i) { - var error = $root.google.firestore.v1beta1.WriteResult.verify(message.writeResults[i]); - if (error) - return "writeResults." + error; - } - } - if (message.commitTime != null && message.hasOwnProperty("commitTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.commitTime); - if (error) - return "commitTime." + error; - } - return null; - }; - - /** - * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.CommitResponse} CommitResponse - */ - CommitResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.CommitResponse) - return object; - var message = new $root.google.firestore.v1beta1.CommitResponse(); - if (object.writeResults) { - if (!Array.isArray(object.writeResults)) - throw TypeError(".google.firestore.v1beta1.CommitResponse.writeResults: array expected"); - message.writeResults = []; - for (var i = 0; i < object.writeResults.length; ++i) { - if (typeof object.writeResults[i] !== "object") - throw TypeError(".google.firestore.v1beta1.CommitResponse.writeResults: object expected"); - message.writeResults[i] = $root.google.firestore.v1beta1.WriteResult.fromObject(object.writeResults[i]); - } - } - if (object.commitTime != null) { - if (typeof object.commitTime !== "object") - throw TypeError(".google.firestore.v1beta1.CommitResponse.commitTime: object expected"); - message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); - } - return message; - }; - - /** - * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.CommitResponse - * @static - * @param {google.firestore.v1beta1.CommitResponse} message CommitResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CommitResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.writeResults = []; - if (options.defaults) - object.commitTime = null; - if (message.writeResults && message.writeResults.length) { - object.writeResults = []; - for (var j = 0; j < message.writeResults.length; ++j) - object.writeResults[j] = $root.google.firestore.v1beta1.WriteResult.toObject(message.writeResults[j], options); - } - if (message.commitTime != null && message.hasOwnProperty("commitTime")) - object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); - return object; - }; - - /** - * Converts this CommitResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.CommitResponse - * @instance - * @returns {Object.} JSON object - */ - CommitResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return CommitResponse; - })(); - - v1beta1.RollbackRequest = (function() { - - /** - * Properties of a RollbackRequest. - * @memberof google.firestore.v1beta1 - * @interface IRollbackRequest - * @property {string|null} [database] RollbackRequest database - * @property {Uint8Array|null} [transaction] RollbackRequest transaction - */ - - /** - * Constructs a new RollbackRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a RollbackRequest. - * @implements IRollbackRequest - * @constructor - * @param {google.firestore.v1beta1.IRollbackRequest=} [properties] Properties to set - */ - function RollbackRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * RollbackRequest database. - * @member {string} database - * @memberof google.firestore.v1beta1.RollbackRequest - * @instance - */ - RollbackRequest.prototype.database = ""; - - /** - * RollbackRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.RollbackRequest - * @instance - */ - RollbackRequest.prototype.transaction = $util.newBuffer([]); - - /** - * Creates a new RollbackRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {google.firestore.v1beta1.IRollbackRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.RollbackRequest} RollbackRequest instance - */ - RollbackRequest.create = function create(properties) { - return new RollbackRequest(properties); - }; - - /** - * Encodes the specified RollbackRequest message. Does not implicitly {@link google.firestore.v1beta1.RollbackRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {google.firestore.v1beta1.IRollbackRequest} message RollbackRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - RollbackRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.database != null && message.hasOwnProperty("database")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.transaction); - return writer; - }; - - /** - * Encodes the specified RollbackRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.RollbackRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {google.firestore.v1beta1.IRollbackRequest} message RollbackRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - RollbackRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a RollbackRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.RollbackRequest} RollbackRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - RollbackRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.RollbackRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.database = reader.string(); - break; - case 2: - message.transaction = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a RollbackRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.RollbackRequest} RollbackRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - RollbackRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a RollbackRequest message. - * @function verify - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - RollbackRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.database != null && message.hasOwnProperty("database")) - if (!$util.isString(message.database)) - return "database: string expected"; - if (message.transaction != null && message.hasOwnProperty("transaction")) - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - return null; - }; - - /** - * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.RollbackRequest} RollbackRequest - */ - RollbackRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.RollbackRequest) - return object; - var message = new $root.google.firestore.v1beta1.RollbackRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - return message; - }; - - /** - * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.RollbackRequest - * @static - * @param {google.firestore.v1beta1.RollbackRequest} message RollbackRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RollbackRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.database = ""; - object.transaction = options.bytes === String ? "" : []; - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - return object; - }; - - /** - * Converts this RollbackRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.RollbackRequest - * @instance - * @returns {Object.} JSON object - */ - RollbackRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return RollbackRequest; - })(); - - v1beta1.RunQueryRequest = (function() { - - /** - * Properties of a RunQueryRequest. - * @memberof google.firestore.v1beta1 - * @interface IRunQueryRequest - * @property {string|null} [parent] RunQueryRequest parent - * @property {google.firestore.v1beta1.IStructuredQuery|null} [structuredQuery] RunQueryRequest structuredQuery - * @property {Uint8Array|null} [transaction] RunQueryRequest transaction - * @property {google.firestore.v1beta1.ITransactionOptions|null} [newTransaction] RunQueryRequest newTransaction - * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryRequest readTime - */ - - /** - * Constructs a new RunQueryRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a RunQueryRequest. - * @implements IRunQueryRequest - * @constructor - * @param {google.firestore.v1beta1.IRunQueryRequest=} [properties] Properties to set - */ - function RunQueryRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * RunQueryRequest parent. - * @member {string} parent - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.parent = ""; - - /** - * RunQueryRequest structuredQuery. - * @member {google.firestore.v1beta1.IStructuredQuery|null|undefined} structuredQuery - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.structuredQuery = null; - - /** - * RunQueryRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.transaction = $util.newBuffer([]); - - /** - * RunQueryRequest newTransaction. - * @member {google.firestore.v1beta1.ITransactionOptions|null|undefined} newTransaction - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.newTransaction = null; - - /** - * RunQueryRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * RunQueryRequest queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - Object.defineProperty(RunQueryRequest.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * RunQueryRequest consistencySelector. - * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - */ - Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new RunQueryRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {google.firestore.v1beta1.IRunQueryRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.RunQueryRequest} RunQueryRequest instance - */ - RunQueryRequest.create = function create(properties) { - return new RunQueryRequest(properties); - }; - - /** - * Encodes the specified RunQueryRequest message. Does not implicitly {@link google.firestore.v1beta1.RunQueryRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {google.firestore.v1beta1.IRunQueryRequest} message RunQueryRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - RunQueryRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.parent != null && message.hasOwnProperty("parent")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) - $root.google.firestore.v1beta1.StructuredQuery.encode(message.structuredQuery, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 5, wireType 2 =*/42).bytes(message.transaction); - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) - $root.google.firestore.v1beta1.TransactionOptions.encode(message.newTransaction, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified RunQueryRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.RunQueryRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {google.firestore.v1beta1.IRunQueryRequest} message RunQueryRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - RunQueryRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a RunQueryRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.RunQueryRequest} RunQueryRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - RunQueryRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.RunQueryRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.parent = reader.string(); - break; - case 2: - message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.decode(reader, reader.uint32()); - break; - case 5: - message.transaction = reader.bytes(); - break; - case 6: - message.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.decode(reader, reader.uint32()); - break; - case 7: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a RunQueryRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.RunQueryRequest} RunQueryRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - RunQueryRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a RunQueryRequest message. - * @function verify - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - RunQueryRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.parent != null && message.hasOwnProperty("parent")) - if (!$util.isString(message.parent)) - return "parent: string expected"; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - properties.queryType = 1; - { - var error = $root.google.firestore.v1beta1.StructuredQuery.verify(message.structuredQuery); - if (error) - return "structuredQuery." + error; - } - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - properties.consistencySelector = 1; - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - if (properties.consistencySelector === 1) - return "consistencySelector: multiple values"; - properties.consistencySelector = 1; - { - var error = $root.google.firestore.v1beta1.TransactionOptions.verify(message.newTransaction); - if (error) - return "newTransaction." + error; - } - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - if (properties.consistencySelector === 1) - return "consistencySelector: multiple values"; - properties.consistencySelector = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - } - return null; - }; - - /** - * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.RunQueryRequest} RunQueryRequest - */ - RunQueryRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.RunQueryRequest) - return object; - var message = new $root.google.firestore.v1beta1.RunQueryRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1beta1.RunQueryRequest.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.fromObject(object.structuredQuery); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - if (object.newTransaction != null) { - if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1beta1.RunQueryRequest.newTransaction: object expected"); - message.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.fromObject(object.newTransaction); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.RunQueryRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.RunQueryRequest - * @static - * @param {google.firestore.v1beta1.RunQueryRequest} message RunQueryRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RunQueryRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.parent = ""; - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.toObject(message.structuredQuery, options); - if (options.oneofs) - object.queryType = "structuredQuery"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - object.newTransaction = $root.google.firestore.v1beta1.TransactionOptions.toObject(message.newTransaction, options); - if (options.oneofs) - object.consistencySelector = "newTransaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; - - /** - * Converts this RunQueryRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.RunQueryRequest - * @instance - * @returns {Object.} JSON object - */ - RunQueryRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return RunQueryRequest; - })(); - - v1beta1.RunQueryResponse = (function() { - - /** - * Properties of a RunQueryResponse. - * @memberof google.firestore.v1beta1 - * @interface IRunQueryResponse - * @property {Uint8Array|null} [transaction] RunQueryResponse transaction - * @property {google.firestore.v1beta1.IDocument|null} [document] RunQueryResponse document - * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime - * @property {number|null} [skippedResults] RunQueryResponse skippedResults - */ - - /** - * Constructs a new RunQueryResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a RunQueryResponse. - * @implements IRunQueryResponse - * @constructor - * @param {google.firestore.v1beta1.IRunQueryResponse=} [properties] Properties to set - */ - function RunQueryResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * RunQueryResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1beta1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.transaction = $util.newBuffer([]); - - /** - * RunQueryResponse document. - * @member {google.firestore.v1beta1.IDocument|null|undefined} document - * @memberof google.firestore.v1beta1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.document = null; - - /** - * RunQueryResponse readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.readTime = null; - - /** - * RunQueryResponse skippedResults. - * @member {number} skippedResults - * @memberof google.firestore.v1beta1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.skippedResults = 0; - - /** - * Creates a new RunQueryResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {google.firestore.v1beta1.IRunQueryResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.RunQueryResponse} RunQueryResponse instance - */ - RunQueryResponse.create = function create(properties) { - return new RunQueryResponse(properties); - }; - - /** - * Encodes the specified RunQueryResponse message. Does not implicitly {@link google.firestore.v1beta1.RunQueryResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {google.firestore.v1beta1.IRunQueryResponse} message RunQueryResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - RunQueryResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.document != null && message.hasOwnProperty("document")) - $root.google.firestore.v1beta1.Document.encode(message.document, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.transaction != null && message.hasOwnProperty("transaction")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.transaction); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.skippedResults); - return writer; - }; - - /** - * Encodes the specified RunQueryResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.RunQueryResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {google.firestore.v1beta1.IRunQueryResponse} message RunQueryResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - RunQueryResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a RunQueryResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.RunQueryResponse} RunQueryResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - RunQueryResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.RunQueryResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.transaction = reader.bytes(); - break; - case 1: - message.document = $root.google.firestore.v1beta1.Document.decode(reader, reader.uint32()); - break; - case 3: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - case 4: - message.skippedResults = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a RunQueryResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.RunQueryResponse} RunQueryResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - RunQueryResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a RunQueryResponse message. - * @function verify - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - RunQueryResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.transaction != null && message.hasOwnProperty("transaction")) - if (!(message.transaction && typeof message.transaction.length === "number" || $util.isString(message.transaction))) - return "transaction: buffer expected"; - if (message.document != null && message.hasOwnProperty("document")) { - var error = $root.google.firestore.v1beta1.Document.verify(message.document); - if (error) - return "document." + error; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) - if (!$util.isInteger(message.skippedResults)) - return "skippedResults: integer expected"; - return null; - }; - - /** - * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.RunQueryResponse} RunQueryResponse - */ - RunQueryResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.RunQueryResponse) - return object; - var message = new $root.google.firestore.v1beta1.RunQueryResponse(); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length) - message.transaction = object.transaction; - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1beta1.RunQueryResponse.document: object expected"); - message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.RunQueryResponse.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.skippedResults != null) - message.skippedResults = object.skippedResults | 0; - return message; - }; - - /** - * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.RunQueryResponse - * @static - * @param {google.firestore.v1beta1.RunQueryResponse} message RunQueryResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RunQueryResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.document = null; - object.transaction = options.bytes === String ? "" : []; - object.readTime = null; - object.skippedResults = 0; - } - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) - object.skippedResults = message.skippedResults; - return object; - }; - - /** - * Converts this RunQueryResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.RunQueryResponse - * @instance - * @returns {Object.} JSON object - */ - RunQueryResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return RunQueryResponse; - })(); - - v1beta1.WriteRequest = (function() { - - /** - * Properties of a WriteRequest. - * @memberof google.firestore.v1beta1 - * @interface IWriteRequest - * @property {string|null} [database] WriteRequest database - * @property {string|null} [streamId] WriteRequest streamId - * @property {Array.|null} [writes] WriteRequest writes - * @property {Uint8Array|null} [streamToken] WriteRequest streamToken - * @property {Object.|null} [labels] WriteRequest labels - */ - - /** - * Constructs a new WriteRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a WriteRequest. - * @implements IWriteRequest - * @constructor - * @param {google.firestore.v1beta1.IWriteRequest=} [properties] Properties to set - */ - function WriteRequest(properties) { - this.writes = []; - this.labels = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * WriteRequest database. - * @member {string} database - * @memberof google.firestore.v1beta1.WriteRequest - * @instance - */ - WriteRequest.prototype.database = ""; - - /** - * WriteRequest streamId. - * @member {string} streamId - * @memberof google.firestore.v1beta1.WriteRequest - * @instance - */ - WriteRequest.prototype.streamId = ""; - - /** - * WriteRequest writes. - * @member {Array.} writes - * @memberof google.firestore.v1beta1.WriteRequest - * @instance - */ - WriteRequest.prototype.writes = $util.emptyArray; - - /** - * WriteRequest streamToken. - * @member {Uint8Array} streamToken - * @memberof google.firestore.v1beta1.WriteRequest - * @instance - */ - WriteRequest.prototype.streamToken = $util.newBuffer([]); - - /** - * WriteRequest labels. - * @member {Object.} labels - * @memberof google.firestore.v1beta1.WriteRequest - * @instance - */ - WriteRequest.prototype.labels = $util.emptyObject; - - /** - * Creates a new WriteRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {google.firestore.v1beta1.IWriteRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.WriteRequest} WriteRequest instance - */ - WriteRequest.create = function create(properties) { - return new WriteRequest(properties); - }; - - /** - * Encodes the specified WriteRequest message. Does not implicitly {@link google.firestore.v1beta1.WriteRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {google.firestore.v1beta1.IWriteRequest} message WriteRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - WriteRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.database != null && message.hasOwnProperty("database")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); - if (message.streamId != null && message.hasOwnProperty("streamId")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.streamId); - if (message.writes != null && message.writes.length) - for (var i = 0; i < message.writes.length; ++i) - $root.google.firestore.v1beta1.Write.encode(message.writes[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.streamToken); - if (message.labels != null && message.hasOwnProperty("labels")) - for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) - writer.uint32(/* id 5, wireType 2 =*/42).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); - return writer; - }; - - /** - * Encodes the specified WriteRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.WriteRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {google.firestore.v1beta1.IWriteRequest} message WriteRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - WriteRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a WriteRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.WriteRequest} WriteRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - WriteRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.WriteRequest(), key; - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.database = reader.string(); - break; - case 2: - message.streamId = reader.string(); - break; - case 3: - if (!(message.writes && message.writes.length)) - message.writes = []; - message.writes.push($root.google.firestore.v1beta1.Write.decode(reader, reader.uint32())); - break; - case 4: - message.streamToken = reader.bytes(); - break; - case 5: - reader.skip().pos++; - if (message.labels === $util.emptyObject) - message.labels = {}; - key = reader.string(); - reader.pos++; - message.labels[key] = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a WriteRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.WriteRequest} WriteRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - WriteRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a WriteRequest message. - * @function verify - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - WriteRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.database != null && message.hasOwnProperty("database")) - if (!$util.isString(message.database)) - return "database: string expected"; - if (message.streamId != null && message.hasOwnProperty("streamId")) - if (!$util.isString(message.streamId)) - return "streamId: string expected"; - if (message.writes != null && message.hasOwnProperty("writes")) { - if (!Array.isArray(message.writes)) - return "writes: array expected"; - for (var i = 0; i < message.writes.length; ++i) { - var error = $root.google.firestore.v1beta1.Write.verify(message.writes[i]); - if (error) - return "writes." + error; - } - } - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - if (!(message.streamToken && typeof message.streamToken.length === "number" || $util.isString(message.streamToken))) - return "streamToken: buffer expected"; - if (message.labels != null && message.hasOwnProperty("labels")) { - if (!$util.isObject(message.labels)) - return "labels: object expected"; - var key = Object.keys(message.labels); - for (var i = 0; i < key.length; ++i) - if (!$util.isString(message.labels[key[i]])) - return "labels: string{k:string} expected"; - } - return null; - }; - - /** - * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.WriteRequest} WriteRequest - */ - WriteRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.WriteRequest) - return object; - var message = new $root.google.firestore.v1beta1.WriteRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.streamId != null) - message.streamId = String(object.streamId); - if (object.writes) { - if (!Array.isArray(object.writes)) - throw TypeError(".google.firestore.v1beta1.WriteRequest.writes: array expected"); - message.writes = []; - for (var i = 0; i < object.writes.length; ++i) { - if (typeof object.writes[i] !== "object") - throw TypeError(".google.firestore.v1beta1.WriteRequest.writes: object expected"); - message.writes[i] = $root.google.firestore.v1beta1.Write.fromObject(object.writes[i]); - } - } - if (object.streamToken != null) - if (typeof object.streamToken === "string") - $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); - else if (object.streamToken.length) - message.streamToken = object.streamToken; - if (object.labels) { - if (typeof object.labels !== "object") - throw TypeError(".google.firestore.v1beta1.WriteRequest.labels: object expected"); - message.labels = {}; - for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) - message.labels[keys[i]] = String(object.labels[keys[i]]); - } - return message; - }; - - /** - * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.WriteRequest - * @static - * @param {google.firestore.v1beta1.WriteRequest} message WriteRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - WriteRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.writes = []; - if (options.objects || options.defaults) - object.labels = {}; - if (options.defaults) { - object.database = ""; - object.streamId = ""; - object.streamToken = options.bytes === String ? "" : []; - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.streamId != null && message.hasOwnProperty("streamId")) - object.streamId = message.streamId; - if (message.writes && message.writes.length) { - object.writes = []; - for (var j = 0; j < message.writes.length; ++j) - object.writes[j] = $root.google.firestore.v1beta1.Write.toObject(message.writes[j], options); - } - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; - var keys2; - if (message.labels && (keys2 = Object.keys(message.labels)).length) { - object.labels = {}; - for (var j = 0; j < keys2.length; ++j) - object.labels[keys2[j]] = message.labels[keys2[j]]; - } - return object; - }; - - /** - * Converts this WriteRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.WriteRequest - * @instance - * @returns {Object.} JSON object - */ - WriteRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return WriteRequest; - })(); - - v1beta1.WriteResponse = (function() { - - /** - * Properties of a WriteResponse. - * @memberof google.firestore.v1beta1 - * @interface IWriteResponse - * @property {string|null} [streamId] WriteResponse streamId - * @property {Uint8Array|null} [streamToken] WriteResponse streamToken - * @property {Array.|null} [writeResults] WriteResponse writeResults - * @property {google.protobuf.ITimestamp|null} [commitTime] WriteResponse commitTime - */ - - /** - * Constructs a new WriteResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a WriteResponse. - * @implements IWriteResponse - * @constructor - * @param {google.firestore.v1beta1.IWriteResponse=} [properties] Properties to set - */ - function WriteResponse(properties) { - this.writeResults = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * WriteResponse streamId. - * @member {string} streamId - * @memberof google.firestore.v1beta1.WriteResponse - * @instance - */ - WriteResponse.prototype.streamId = ""; - - /** - * WriteResponse streamToken. - * @member {Uint8Array} streamToken - * @memberof google.firestore.v1beta1.WriteResponse - * @instance - */ - WriteResponse.prototype.streamToken = $util.newBuffer([]); - - /** - * WriteResponse writeResults. - * @member {Array.} writeResults - * @memberof google.firestore.v1beta1.WriteResponse - * @instance - */ - WriteResponse.prototype.writeResults = $util.emptyArray; - - /** - * WriteResponse commitTime. - * @member {google.protobuf.ITimestamp|null|undefined} commitTime - * @memberof google.firestore.v1beta1.WriteResponse - * @instance - */ - WriteResponse.prototype.commitTime = null; - - /** - * Creates a new WriteResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {google.firestore.v1beta1.IWriteResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.WriteResponse} WriteResponse instance - */ - WriteResponse.create = function create(properties) { - return new WriteResponse(properties); - }; - - /** - * Encodes the specified WriteResponse message. Does not implicitly {@link google.firestore.v1beta1.WriteResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {google.firestore.v1beta1.IWriteResponse} message WriteResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - WriteResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.streamId != null && message.hasOwnProperty("streamId")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.streamId); - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.streamToken); - if (message.writeResults != null && message.writeResults.length) - for (var i = 0; i < message.writeResults.length; ++i) - $root.google.firestore.v1beta1.WriteResult.encode(message.writeResults[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.commitTime != null && message.hasOwnProperty("commitTime")) - $root.google.protobuf.Timestamp.encode(message.commitTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified WriteResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.WriteResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {google.firestore.v1beta1.IWriteResponse} message WriteResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - WriteResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a WriteResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.WriteResponse} WriteResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - WriteResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.WriteResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.streamId = reader.string(); - break; - case 2: - message.streamToken = reader.bytes(); - break; - case 3: - if (!(message.writeResults && message.writeResults.length)) - message.writeResults = []; - message.writeResults.push($root.google.firestore.v1beta1.WriteResult.decode(reader, reader.uint32())); - break; - case 4: - message.commitTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a WriteResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.WriteResponse} WriteResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - WriteResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a WriteResponse message. - * @function verify - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - WriteResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.streamId != null && message.hasOwnProperty("streamId")) - if (!$util.isString(message.streamId)) - return "streamId: string expected"; - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - if (!(message.streamToken && typeof message.streamToken.length === "number" || $util.isString(message.streamToken))) - return "streamToken: buffer expected"; - if (message.writeResults != null && message.hasOwnProperty("writeResults")) { - if (!Array.isArray(message.writeResults)) - return "writeResults: array expected"; - for (var i = 0; i < message.writeResults.length; ++i) { - var error = $root.google.firestore.v1beta1.WriteResult.verify(message.writeResults[i]); - if (error) - return "writeResults." + error; - } - } - if (message.commitTime != null && message.hasOwnProperty("commitTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.commitTime); - if (error) - return "commitTime." + error; - } - return null; - }; - - /** - * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.WriteResponse} WriteResponse - */ - WriteResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.WriteResponse) - return object; - var message = new $root.google.firestore.v1beta1.WriteResponse(); - if (object.streamId != null) - message.streamId = String(object.streamId); - if (object.streamToken != null) - if (typeof object.streamToken === "string") - $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); - else if (object.streamToken.length) - message.streamToken = object.streamToken; - if (object.writeResults) { - if (!Array.isArray(object.writeResults)) - throw TypeError(".google.firestore.v1beta1.WriteResponse.writeResults: array expected"); - message.writeResults = []; - for (var i = 0; i < object.writeResults.length; ++i) { - if (typeof object.writeResults[i] !== "object") - throw TypeError(".google.firestore.v1beta1.WriteResponse.writeResults: object expected"); - message.writeResults[i] = $root.google.firestore.v1beta1.WriteResult.fromObject(object.writeResults[i]); - } - } - if (object.commitTime != null) { - if (typeof object.commitTime !== "object") - throw TypeError(".google.firestore.v1beta1.WriteResponse.commitTime: object expected"); - message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); - } - return message; - }; - - /** - * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.WriteResponse - * @static - * @param {google.firestore.v1beta1.WriteResponse} message WriteResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - WriteResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.writeResults = []; - if (options.defaults) { - object.streamId = ""; - object.streamToken = options.bytes === String ? "" : []; - object.commitTime = null; - } - if (message.streamId != null && message.hasOwnProperty("streamId")) - object.streamId = message.streamId; - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; - if (message.writeResults && message.writeResults.length) { - object.writeResults = []; - for (var j = 0; j < message.writeResults.length; ++j) - object.writeResults[j] = $root.google.firestore.v1beta1.WriteResult.toObject(message.writeResults[j], options); - } - if (message.commitTime != null && message.hasOwnProperty("commitTime")) - object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); - return object; - }; - - /** - * Converts this WriteResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.WriteResponse - * @instance - * @returns {Object.} JSON object - */ - WriteResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return WriteResponse; - })(); - - v1beta1.ListenRequest = (function() { - - /** - * Properties of a ListenRequest. - * @memberof google.firestore.v1beta1 - * @interface IListenRequest - * @property {string|null} [database] ListenRequest database - * @property {google.firestore.v1beta1.ITarget|null} [addTarget] ListenRequest addTarget - * @property {number|null} [removeTarget] ListenRequest removeTarget - * @property {Object.|null} [labels] ListenRequest labels - */ - - /** - * Constructs a new ListenRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a ListenRequest. - * @implements IListenRequest - * @constructor - * @param {google.firestore.v1beta1.IListenRequest=} [properties] Properties to set - */ - function ListenRequest(properties) { - this.labels = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListenRequest database. - * @member {string} database - * @memberof google.firestore.v1beta1.ListenRequest - * @instance - */ - ListenRequest.prototype.database = ""; - - /** - * ListenRequest addTarget. - * @member {google.firestore.v1beta1.ITarget|null|undefined} addTarget - * @memberof google.firestore.v1beta1.ListenRequest - * @instance - */ - ListenRequest.prototype.addTarget = null; - - /** - * ListenRequest removeTarget. - * @member {number} removeTarget - * @memberof google.firestore.v1beta1.ListenRequest - * @instance - */ - ListenRequest.prototype.removeTarget = 0; - - /** - * ListenRequest labels. - * @member {Object.} labels - * @memberof google.firestore.v1beta1.ListenRequest - * @instance - */ - ListenRequest.prototype.labels = $util.emptyObject; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * ListenRequest targetChange. - * @member {"addTarget"|"removeTarget"|undefined} targetChange - * @memberof google.firestore.v1beta1.ListenRequest - * @instance - */ - Object.defineProperty(ListenRequest.prototype, "targetChange", { - get: $util.oneOfGetter($oneOfFields = ["addTarget", "removeTarget"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new ListenRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {google.firestore.v1beta1.IListenRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ListenRequest} ListenRequest instance - */ - ListenRequest.create = function create(properties) { - return new ListenRequest(properties); - }; - - /** - * Encodes the specified ListenRequest message. Does not implicitly {@link google.firestore.v1beta1.ListenRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {google.firestore.v1beta1.IListenRequest} message ListenRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListenRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.database != null && message.hasOwnProperty("database")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); - if (message.addTarget != null && message.hasOwnProperty("addTarget")) - $root.google.firestore.v1beta1.Target.encode(message.addTarget, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.removeTarget); - if (message.labels != null && message.hasOwnProperty("labels")) - for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) - writer.uint32(/* id 4, wireType 2 =*/34).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); - return writer; - }; - - /** - * Encodes the specified ListenRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListenRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {google.firestore.v1beta1.IListenRequest} message ListenRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListenRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListenRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ListenRequest} ListenRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListenRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ListenRequest(), key; - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.database = reader.string(); - break; - case 2: - message.addTarget = $root.google.firestore.v1beta1.Target.decode(reader, reader.uint32()); - break; - case 3: - message.removeTarget = reader.int32(); - break; - case 4: - reader.skip().pos++; - if (message.labels === $util.emptyObject) - message.labels = {}; - key = reader.string(); - reader.pos++; - message.labels[key] = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListenRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ListenRequest} ListenRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListenRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListenRequest message. - * @function verify - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListenRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.database != null && message.hasOwnProperty("database")) - if (!$util.isString(message.database)) - return "database: string expected"; - if (message.addTarget != null && message.hasOwnProperty("addTarget")) { - properties.targetChange = 1; - { - var error = $root.google.firestore.v1beta1.Target.verify(message.addTarget); - if (error) - return "addTarget." + error; - } - } - if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) { - if (properties.targetChange === 1) - return "targetChange: multiple values"; - properties.targetChange = 1; - if (!$util.isInteger(message.removeTarget)) - return "removeTarget: integer expected"; - } - if (message.labels != null && message.hasOwnProperty("labels")) { - if (!$util.isObject(message.labels)) - return "labels: object expected"; - var key = Object.keys(message.labels); - for (var i = 0; i < key.length; ++i) - if (!$util.isString(message.labels[key[i]])) - return "labels: string{k:string} expected"; - } - return null; - }; - - /** - * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ListenRequest} ListenRequest - */ - ListenRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ListenRequest) - return object; - var message = new $root.google.firestore.v1beta1.ListenRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.addTarget != null) { - if (typeof object.addTarget !== "object") - throw TypeError(".google.firestore.v1beta1.ListenRequest.addTarget: object expected"); - message.addTarget = $root.google.firestore.v1beta1.Target.fromObject(object.addTarget); - } - if (object.removeTarget != null) - message.removeTarget = object.removeTarget | 0; - if (object.labels) { - if (typeof object.labels !== "object") - throw TypeError(".google.firestore.v1beta1.ListenRequest.labels: object expected"); - message.labels = {}; - for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) - message.labels[keys[i]] = String(object.labels[keys[i]]); - } - return message; - }; - - /** - * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ListenRequest - * @static - * @param {google.firestore.v1beta1.ListenRequest} message ListenRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListenRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.labels = {}; - if (options.defaults) - object.database = ""; - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.addTarget != null && message.hasOwnProperty("addTarget")) { - object.addTarget = $root.google.firestore.v1beta1.Target.toObject(message.addTarget, options); - if (options.oneofs) - object.targetChange = "addTarget"; - } - if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) { - object.removeTarget = message.removeTarget; - if (options.oneofs) - object.targetChange = "removeTarget"; - } - var keys2; - if (message.labels && (keys2 = Object.keys(message.labels)).length) { - object.labels = {}; - for (var j = 0; j < keys2.length; ++j) - object.labels[keys2[j]] = message.labels[keys2[j]]; - } - return object; - }; - - /** - * Converts this ListenRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ListenRequest - * @instance - * @returns {Object.} JSON object - */ - ListenRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListenRequest; - })(); - - v1beta1.ListenResponse = (function() { - - /** - * Properties of a ListenResponse. - * @memberof google.firestore.v1beta1 - * @interface IListenResponse - * @property {google.firestore.v1beta1.ITargetChange|null} [targetChange] ListenResponse targetChange - * @property {google.firestore.v1beta1.IDocumentChange|null} [documentChange] ListenResponse documentChange - * @property {google.firestore.v1beta1.IDocumentDelete|null} [documentDelete] ListenResponse documentDelete - * @property {google.firestore.v1beta1.IDocumentRemove|null} [documentRemove] ListenResponse documentRemove - * @property {google.firestore.v1beta1.IExistenceFilter|null} [filter] ListenResponse filter - */ - - /** - * Constructs a new ListenResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a ListenResponse. - * @implements IListenResponse - * @constructor - * @param {google.firestore.v1beta1.IListenResponse=} [properties] Properties to set - */ - function ListenResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListenResponse targetChange. - * @member {google.firestore.v1beta1.ITargetChange|null|undefined} targetChange - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - */ - ListenResponse.prototype.targetChange = null; - - /** - * ListenResponse documentChange. - * @member {google.firestore.v1beta1.IDocumentChange|null|undefined} documentChange - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - */ - ListenResponse.prototype.documentChange = null; - - /** - * ListenResponse documentDelete. - * @member {google.firestore.v1beta1.IDocumentDelete|null|undefined} documentDelete - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - */ - ListenResponse.prototype.documentDelete = null; - - /** - * ListenResponse documentRemove. - * @member {google.firestore.v1beta1.IDocumentRemove|null|undefined} documentRemove - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - */ - ListenResponse.prototype.documentRemove = null; - - /** - * ListenResponse filter. - * @member {google.firestore.v1beta1.IExistenceFilter|null|undefined} filter - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - */ - ListenResponse.prototype.filter = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * ListenResponse responseType. - * @member {"targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"|undefined} responseType - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - */ - Object.defineProperty(ListenResponse.prototype, "responseType", { - get: $util.oneOfGetter($oneOfFields = ["targetChange", "documentChange", "documentDelete", "documentRemove", "filter"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new ListenResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {google.firestore.v1beta1.IListenResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ListenResponse} ListenResponse instance - */ - ListenResponse.create = function create(properties) { - return new ListenResponse(properties); - }; - - /** - * Encodes the specified ListenResponse message. Does not implicitly {@link google.firestore.v1beta1.ListenResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {google.firestore.v1beta1.IListenResponse} message ListenResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListenResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.targetChange != null && message.hasOwnProperty("targetChange")) - $root.google.firestore.v1beta1.TargetChange.encode(message.targetChange, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.documentChange != null && message.hasOwnProperty("documentChange")) - $root.google.firestore.v1beta1.DocumentChange.encode(message.documentChange, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) - $root.google.firestore.v1beta1.DocumentDelete.encode(message.documentDelete, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.filter != null && message.hasOwnProperty("filter")) - $root.google.firestore.v1beta1.ExistenceFilter.encode(message.filter, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) - $root.google.firestore.v1beta1.DocumentRemove.encode(message.documentRemove, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified ListenResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListenResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {google.firestore.v1beta1.IListenResponse} message ListenResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListenResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListenResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ListenResponse} ListenResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListenResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ListenResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.targetChange = $root.google.firestore.v1beta1.TargetChange.decode(reader, reader.uint32()); - break; - case 3: - message.documentChange = $root.google.firestore.v1beta1.DocumentChange.decode(reader, reader.uint32()); - break; - case 4: - message.documentDelete = $root.google.firestore.v1beta1.DocumentDelete.decode(reader, reader.uint32()); - break; - case 6: - message.documentRemove = $root.google.firestore.v1beta1.DocumentRemove.decode(reader, reader.uint32()); - break; - case 5: - message.filter = $root.google.firestore.v1beta1.ExistenceFilter.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListenResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ListenResponse} ListenResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListenResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListenResponse message. - * @function verify - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListenResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.targetChange != null && message.hasOwnProperty("targetChange")) { - properties.responseType = 1; - { - var error = $root.google.firestore.v1beta1.TargetChange.verify(message.targetChange); - if (error) - return "targetChange." + error; - } - } - if (message.documentChange != null && message.hasOwnProperty("documentChange")) { - if (properties.responseType === 1) - return "responseType: multiple values"; - properties.responseType = 1; - { - var error = $root.google.firestore.v1beta1.DocumentChange.verify(message.documentChange); - if (error) - return "documentChange." + error; - } - } - if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) { - if (properties.responseType === 1) - return "responseType: multiple values"; - properties.responseType = 1; - { - var error = $root.google.firestore.v1beta1.DocumentDelete.verify(message.documentDelete); - if (error) - return "documentDelete." + error; - } - } - if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) { - if (properties.responseType === 1) - return "responseType: multiple values"; - properties.responseType = 1; - { - var error = $root.google.firestore.v1beta1.DocumentRemove.verify(message.documentRemove); - if (error) - return "documentRemove." + error; - } - } - if (message.filter != null && message.hasOwnProperty("filter")) { - if (properties.responseType === 1) - return "responseType: multiple values"; - properties.responseType = 1; - { - var error = $root.google.firestore.v1beta1.ExistenceFilter.verify(message.filter); - if (error) - return "filter." + error; - } - } - return null; - }; - - /** - * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ListenResponse} ListenResponse - */ - ListenResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ListenResponse) - return object; - var message = new $root.google.firestore.v1beta1.ListenResponse(); - if (object.targetChange != null) { - if (typeof object.targetChange !== "object") - throw TypeError(".google.firestore.v1beta1.ListenResponse.targetChange: object expected"); - message.targetChange = $root.google.firestore.v1beta1.TargetChange.fromObject(object.targetChange); - } - if (object.documentChange != null) { - if (typeof object.documentChange !== "object") - throw TypeError(".google.firestore.v1beta1.ListenResponse.documentChange: object expected"); - message.documentChange = $root.google.firestore.v1beta1.DocumentChange.fromObject(object.documentChange); - } - if (object.documentDelete != null) { - if (typeof object.documentDelete !== "object") - throw TypeError(".google.firestore.v1beta1.ListenResponse.documentDelete: object expected"); - message.documentDelete = $root.google.firestore.v1beta1.DocumentDelete.fromObject(object.documentDelete); - } - if (object.documentRemove != null) { - if (typeof object.documentRemove !== "object") - throw TypeError(".google.firestore.v1beta1.ListenResponse.documentRemove: object expected"); - message.documentRemove = $root.google.firestore.v1beta1.DocumentRemove.fromObject(object.documentRemove); - } - if (object.filter != null) { - if (typeof object.filter !== "object") - throw TypeError(".google.firestore.v1beta1.ListenResponse.filter: object expected"); - message.filter = $root.google.firestore.v1beta1.ExistenceFilter.fromObject(object.filter); - } - return message; - }; - - /** - * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ListenResponse - * @static - * @param {google.firestore.v1beta1.ListenResponse} message ListenResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListenResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.targetChange != null && message.hasOwnProperty("targetChange")) { - object.targetChange = $root.google.firestore.v1beta1.TargetChange.toObject(message.targetChange, options); - if (options.oneofs) - object.responseType = "targetChange"; - } - if (message.documentChange != null && message.hasOwnProperty("documentChange")) { - object.documentChange = $root.google.firestore.v1beta1.DocumentChange.toObject(message.documentChange, options); - if (options.oneofs) - object.responseType = "documentChange"; - } - if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) { - object.documentDelete = $root.google.firestore.v1beta1.DocumentDelete.toObject(message.documentDelete, options); - if (options.oneofs) - object.responseType = "documentDelete"; - } - if (message.filter != null && message.hasOwnProperty("filter")) { - object.filter = $root.google.firestore.v1beta1.ExistenceFilter.toObject(message.filter, options); - if (options.oneofs) - object.responseType = "filter"; - } - if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) { - object.documentRemove = $root.google.firestore.v1beta1.DocumentRemove.toObject(message.documentRemove, options); - if (options.oneofs) - object.responseType = "documentRemove"; - } - return object; - }; - - /** - * Converts this ListenResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ListenResponse - * @instance - * @returns {Object.} JSON object - */ - ListenResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListenResponse; - })(); - - v1beta1.Target = (function() { - - /** - * Properties of a Target. - * @memberof google.firestore.v1beta1 - * @interface ITarget - * @property {google.firestore.v1beta1.Target.IQueryTarget|null} [query] Target query - * @property {google.firestore.v1beta1.Target.IDocumentsTarget|null} [documents] Target documents - * @property {Uint8Array|null} [resumeToken] Target resumeToken - * @property {google.protobuf.ITimestamp|null} [readTime] Target readTime - * @property {number|null} [targetId] Target targetId - * @property {boolean|null} [once] Target once - */ - - /** - * Constructs a new Target. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Target. - * @implements ITarget - * @constructor - * @param {google.firestore.v1beta1.ITarget=} [properties] Properties to set - */ - function Target(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Target query. - * @member {google.firestore.v1beta1.Target.IQueryTarget|null|undefined} query - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Target.prototype.query = null; - - /** - * Target documents. - * @member {google.firestore.v1beta1.Target.IDocumentsTarget|null|undefined} documents - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Target.prototype.documents = null; - - /** - * Target resumeToken. - * @member {Uint8Array} resumeToken - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Target.prototype.resumeToken = $util.newBuffer([]); - - /** - * Target readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Target.prototype.readTime = null; - - /** - * Target targetId. - * @member {number} targetId - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Target.prototype.targetId = 0; - - /** - * Target once. - * @member {boolean} once - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Target.prototype.once = false; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Target targetType. - * @member {"query"|"documents"|undefined} targetType - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Object.defineProperty(Target.prototype, "targetType", { - get: $util.oneOfGetter($oneOfFields = ["query", "documents"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Target resumeType. - * @member {"resumeToken"|"readTime"|undefined} resumeType - * @memberof google.firestore.v1beta1.Target - * @instance - */ - Object.defineProperty(Target.prototype, "resumeType", { - get: $util.oneOfGetter($oneOfFields = ["resumeToken", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new Target instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Target - * @static - * @param {google.firestore.v1beta1.ITarget=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Target} Target instance - */ - Target.create = function create(properties) { - return new Target(properties); - }; - - /** - * Encodes the specified Target message. Does not implicitly {@link google.firestore.v1beta1.Target.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Target - * @static - * @param {google.firestore.v1beta1.ITarget} message Target message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Target.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.query != null && message.hasOwnProperty("query")) - $root.google.firestore.v1beta1.Target.QueryTarget.encode(message.query, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.documents != null && message.hasOwnProperty("documents")) - $root.google.firestore.v1beta1.Target.DocumentsTarget.encode(message.documents, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) - writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.resumeToken); - if (message.targetId != null && message.hasOwnProperty("targetId")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.targetId); - if (message.once != null && message.hasOwnProperty("once")) - writer.uint32(/* id 6, wireType 0 =*/48).bool(message.once); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Target message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Target.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Target - * @static - * @param {google.firestore.v1beta1.ITarget} message Target message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Target.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Target message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Target - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Target} Target - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Target.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Target(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.query = $root.google.firestore.v1beta1.Target.QueryTarget.decode(reader, reader.uint32()); - break; - case 3: - message.documents = $root.google.firestore.v1beta1.Target.DocumentsTarget.decode(reader, reader.uint32()); - break; - case 4: - message.resumeToken = reader.bytes(); - break; - case 11: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - case 5: - message.targetId = reader.int32(); - break; - case 6: - message.once = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Target message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Target - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Target} Target - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Target.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Target message. - * @function verify - * @memberof google.firestore.v1beta1.Target - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Target.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.query != null && message.hasOwnProperty("query")) { - properties.targetType = 1; - { - var error = $root.google.firestore.v1beta1.Target.QueryTarget.verify(message.query); - if (error) - return "query." + error; - } - } - if (message.documents != null && message.hasOwnProperty("documents")) { - if (properties.targetType === 1) - return "targetType: multiple values"; - properties.targetType = 1; - { - var error = $root.google.firestore.v1beta1.Target.DocumentsTarget.verify(message.documents); - if (error) - return "documents." + error; - } - } - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) { - properties.resumeType = 1; - if (!(message.resumeToken && typeof message.resumeToken.length === "number" || $util.isString(message.resumeToken))) - return "resumeToken: buffer expected"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - if (properties.resumeType === 1) - return "resumeType: multiple values"; - properties.resumeType = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - } - if (message.targetId != null && message.hasOwnProperty("targetId")) - if (!$util.isInteger(message.targetId)) - return "targetId: integer expected"; - if (message.once != null && message.hasOwnProperty("once")) - if (typeof message.once !== "boolean") - return "once: boolean expected"; - return null; - }; - - /** - * Creates a Target message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Target - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Target} Target - */ - Target.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Target) - return object; - var message = new $root.google.firestore.v1beta1.Target(); - if (object.query != null) { - if (typeof object.query !== "object") - throw TypeError(".google.firestore.v1beta1.Target.query: object expected"); - message.query = $root.google.firestore.v1beta1.Target.QueryTarget.fromObject(object.query); - } - if (object.documents != null) { - if (typeof object.documents !== "object") - throw TypeError(".google.firestore.v1beta1.Target.documents: object expected"); - message.documents = $root.google.firestore.v1beta1.Target.DocumentsTarget.fromObject(object.documents); - } - if (object.resumeToken != null) - if (typeof object.resumeToken === "string") - $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); - else if (object.resumeToken.length) - message.resumeToken = object.resumeToken; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.Target.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.targetId != null) - message.targetId = object.targetId | 0; - if (object.once != null) - message.once = Boolean(object.once); - return message; - }; - - /** - * Creates a plain object from a Target message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Target - * @static - * @param {google.firestore.v1beta1.Target} message Target - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Target.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.targetId = 0; - object.once = false; - } - if (message.query != null && message.hasOwnProperty("query")) { - object.query = $root.google.firestore.v1beta1.Target.QueryTarget.toObject(message.query, options); - if (options.oneofs) - object.targetType = "query"; - } - if (message.documents != null && message.hasOwnProperty("documents")) { - object.documents = $root.google.firestore.v1beta1.Target.DocumentsTarget.toObject(message.documents, options); - if (options.oneofs) - object.targetType = "documents"; - } - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) { - object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; - if (options.oneofs) - object.resumeType = "resumeToken"; - } - if (message.targetId != null && message.hasOwnProperty("targetId")) - object.targetId = message.targetId; - if (message.once != null && message.hasOwnProperty("once")) - object.once = message.once; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.resumeType = "readTime"; - } - return object; - }; - - /** - * Converts this Target to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Target - * @instance - * @returns {Object.} JSON object - */ - Target.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - Target.DocumentsTarget = (function() { - - /** - * Properties of a DocumentsTarget. - * @memberof google.firestore.v1beta1.Target - * @interface IDocumentsTarget - * @property {Array.|null} [documents] DocumentsTarget documents - */ - - /** - * Constructs a new DocumentsTarget. - * @memberof google.firestore.v1beta1.Target - * @classdesc Represents a DocumentsTarget. - * @implements IDocumentsTarget - * @constructor - * @param {google.firestore.v1beta1.Target.IDocumentsTarget=} [properties] Properties to set - */ - function DocumentsTarget(properties) { - this.documents = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DocumentsTarget documents. - * @member {Array.} documents - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @instance - */ - DocumentsTarget.prototype.documents = $util.emptyArray; - - /** - * Creates a new DocumentsTarget instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {google.firestore.v1beta1.Target.IDocumentsTarget=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Target.DocumentsTarget} DocumentsTarget instance - */ - DocumentsTarget.create = function create(properties) { - return new DocumentsTarget(properties); - }; - - /** - * Encodes the specified DocumentsTarget message. Does not implicitly {@link google.firestore.v1beta1.Target.DocumentsTarget.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {google.firestore.v1beta1.Target.IDocumentsTarget} message DocumentsTarget message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentsTarget.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.documents != null && message.documents.length) - for (var i = 0; i < message.documents.length; ++i) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.documents[i]); - return writer; - }; - - /** - * Encodes the specified DocumentsTarget message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Target.DocumentsTarget.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {google.firestore.v1beta1.Target.IDocumentsTarget} message DocumentsTarget message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentsTarget.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DocumentsTarget message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Target.DocumentsTarget} DocumentsTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentsTarget.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Target.DocumentsTarget(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - if (!(message.documents && message.documents.length)) - message.documents = []; - message.documents.push(reader.string()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DocumentsTarget message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Target.DocumentsTarget} DocumentsTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentsTarget.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DocumentsTarget message. - * @function verify - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DocumentsTarget.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.documents != null && message.hasOwnProperty("documents")) { - if (!Array.isArray(message.documents)) - return "documents: array expected"; - for (var i = 0; i < message.documents.length; ++i) - if (!$util.isString(message.documents[i])) - return "documents: string[] expected"; - } - return null; - }; - - /** - * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Target.DocumentsTarget} DocumentsTarget - */ - DocumentsTarget.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Target.DocumentsTarget) - return object; - var message = new $root.google.firestore.v1beta1.Target.DocumentsTarget(); - if (object.documents) { - if (!Array.isArray(object.documents)) - throw TypeError(".google.firestore.v1beta1.Target.DocumentsTarget.documents: array expected"); - message.documents = []; - for (var i = 0; i < object.documents.length; ++i) - message.documents[i] = String(object.documents[i]); - } - return message; - }; - - /** - * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @static - * @param {google.firestore.v1beta1.Target.DocumentsTarget} message DocumentsTarget - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentsTarget.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.documents = []; - if (message.documents && message.documents.length) { - object.documents = []; - for (var j = 0; j < message.documents.length; ++j) - object.documents[j] = message.documents[j]; - } - return object; - }; - - /** - * Converts this DocumentsTarget to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Target.DocumentsTarget - * @instance - * @returns {Object.} JSON object - */ - DocumentsTarget.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DocumentsTarget; - })(); - - Target.QueryTarget = (function() { - - /** - * Properties of a QueryTarget. - * @memberof google.firestore.v1beta1.Target - * @interface IQueryTarget - * @property {string|null} [parent] QueryTarget parent - * @property {google.firestore.v1beta1.IStructuredQuery|null} [structuredQuery] QueryTarget structuredQuery - */ - - /** - * Constructs a new QueryTarget. - * @memberof google.firestore.v1beta1.Target - * @classdesc Represents a QueryTarget. - * @implements IQueryTarget - * @constructor - * @param {google.firestore.v1beta1.Target.IQueryTarget=} [properties] Properties to set - */ - function QueryTarget(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * QueryTarget parent. - * @member {string} parent - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @instance - */ - QueryTarget.prototype.parent = ""; - - /** - * QueryTarget structuredQuery. - * @member {google.firestore.v1beta1.IStructuredQuery|null|undefined} structuredQuery - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @instance - */ - QueryTarget.prototype.structuredQuery = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * QueryTarget queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @instance - */ - Object.defineProperty(QueryTarget.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new QueryTarget instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {google.firestore.v1beta1.Target.IQueryTarget=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Target.QueryTarget} QueryTarget instance - */ - QueryTarget.create = function create(properties) { - return new QueryTarget(properties); - }; - - /** - * Encodes the specified QueryTarget message. Does not implicitly {@link google.firestore.v1beta1.Target.QueryTarget.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {google.firestore.v1beta1.Target.IQueryTarget} message QueryTarget message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - QueryTarget.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.parent != null && message.hasOwnProperty("parent")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) - $root.google.firestore.v1beta1.StructuredQuery.encode(message.structuredQuery, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified QueryTarget message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Target.QueryTarget.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {google.firestore.v1beta1.Target.IQueryTarget} message QueryTarget message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - QueryTarget.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a QueryTarget message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Target.QueryTarget} QueryTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - QueryTarget.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Target.QueryTarget(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.parent = reader.string(); - break; - case 2: - message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a QueryTarget message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Target.QueryTarget} QueryTarget - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - QueryTarget.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a QueryTarget message. - * @function verify - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - QueryTarget.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.parent != null && message.hasOwnProperty("parent")) - if (!$util.isString(message.parent)) - return "parent: string expected"; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - properties.queryType = 1; - { - var error = $root.google.firestore.v1beta1.StructuredQuery.verify(message.structuredQuery); - if (error) - return "structuredQuery." + error; - } - } - return null; - }; - - /** - * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Target.QueryTarget} QueryTarget - */ - QueryTarget.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Target.QueryTarget) - return object; - var message = new $root.google.firestore.v1beta1.Target.QueryTarget(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1beta1.Target.QueryTarget.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.fromObject(object.structuredQuery); - } - return message; - }; - - /** - * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @static - * @param {google.firestore.v1beta1.Target.QueryTarget} message QueryTarget - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - QueryTarget.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.parent = ""; - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1beta1.StructuredQuery.toObject(message.structuredQuery, options); - if (options.oneofs) - object.queryType = "structuredQuery"; - } - return object; - }; - - /** - * Converts this QueryTarget to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Target.QueryTarget - * @instance - * @returns {Object.} JSON object - */ - QueryTarget.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return QueryTarget; - })(); - - return Target; - })(); - - v1beta1.TargetChange = (function() { - - /** - * Properties of a TargetChange. - * @memberof google.firestore.v1beta1 - * @interface ITargetChange - * @property {google.firestore.v1beta1.TargetChange.TargetChangeType|null} [targetChangeType] TargetChange targetChangeType - * @property {Array.|null} [targetIds] TargetChange targetIds - * @property {google.rpc.IStatus|null} [cause] TargetChange cause - * @property {Uint8Array|null} [resumeToken] TargetChange resumeToken - * @property {google.protobuf.ITimestamp|null} [readTime] TargetChange readTime - */ - - /** - * Constructs a new TargetChange. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a TargetChange. - * @implements ITargetChange - * @constructor - * @param {google.firestore.v1beta1.ITargetChange=} [properties] Properties to set - */ - function TargetChange(properties) { - this.targetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * TargetChange targetChangeType. - * @member {google.firestore.v1beta1.TargetChange.TargetChangeType} targetChangeType - * @memberof google.firestore.v1beta1.TargetChange - * @instance - */ - TargetChange.prototype.targetChangeType = 0; - - /** - * TargetChange targetIds. - * @member {Array.} targetIds - * @memberof google.firestore.v1beta1.TargetChange - * @instance - */ - TargetChange.prototype.targetIds = $util.emptyArray; - - /** - * TargetChange cause. - * @member {google.rpc.IStatus|null|undefined} cause - * @memberof google.firestore.v1beta1.TargetChange - * @instance - */ - TargetChange.prototype.cause = null; - - /** - * TargetChange resumeToken. - * @member {Uint8Array} resumeToken - * @memberof google.firestore.v1beta1.TargetChange - * @instance - */ - TargetChange.prototype.resumeToken = $util.newBuffer([]); - - /** - * TargetChange readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.TargetChange - * @instance - */ - TargetChange.prototype.readTime = null; - - /** - * Creates a new TargetChange instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {google.firestore.v1beta1.ITargetChange=} [properties] Properties to set - * @returns {google.firestore.v1beta1.TargetChange} TargetChange instance - */ - TargetChange.create = function create(properties) { - return new TargetChange(properties); - }; - - /** - * Encodes the specified TargetChange message. Does not implicitly {@link google.firestore.v1beta1.TargetChange.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {google.firestore.v1beta1.ITargetChange} message TargetChange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - TargetChange.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.targetChangeType); - if (message.targetIds != null && message.targetIds.length) { - writer.uint32(/* id 2, wireType 2 =*/18).fork(); - for (var i = 0; i < message.targetIds.length; ++i) - writer.int32(message.targetIds[i]); - writer.ldelim(); - } - if (message.cause != null && message.hasOwnProperty("cause")) - $root.google.rpc.Status.encode(message.cause, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) - writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.resumeToken); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified TargetChange message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TargetChange.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {google.firestore.v1beta1.ITargetChange} message TargetChange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - TargetChange.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a TargetChange message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.TargetChange} TargetChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - TargetChange.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.TargetChange(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.targetChangeType = reader.int32(); - break; - case 2: - if (!(message.targetIds && message.targetIds.length)) - message.targetIds = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.targetIds.push(reader.int32()); - } else - message.targetIds.push(reader.int32()); - break; - case 3: - message.cause = $root.google.rpc.Status.decode(reader, reader.uint32()); - break; - case 4: - message.resumeToken = reader.bytes(); - break; - case 6: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a TargetChange message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.TargetChange} TargetChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - TargetChange.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a TargetChange message. - * @function verify - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - TargetChange.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) - switch (message.targetChangeType) { - default: - return "targetChangeType: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - break; - } - if (message.targetIds != null && message.hasOwnProperty("targetIds")) { - if (!Array.isArray(message.targetIds)) - return "targetIds: array expected"; - for (var i = 0; i < message.targetIds.length; ++i) - if (!$util.isInteger(message.targetIds[i])) - return "targetIds: integer[] expected"; - } - if (message.cause != null && message.hasOwnProperty("cause")) { - var error = $root.google.rpc.Status.verify(message.cause); - if (error) - return "cause." + error; - } - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) - if (!(message.resumeToken && typeof message.resumeToken.length === "number" || $util.isString(message.resumeToken))) - return "resumeToken: buffer expected"; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - return null; - }; - - /** - * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.TargetChange} TargetChange - */ - TargetChange.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.TargetChange) - return object; - var message = new $root.google.firestore.v1beta1.TargetChange(); - switch (object.targetChangeType) { - case "NO_CHANGE": - case 0: - message.targetChangeType = 0; - break; - case "ADD": - case 1: - message.targetChangeType = 1; - break; - case "REMOVE": - case 2: - message.targetChangeType = 2; - break; - case "CURRENT": - case 3: - message.targetChangeType = 3; - break; - case "RESET": - case 4: - message.targetChangeType = 4; - break; - } - if (object.targetIds) { - if (!Array.isArray(object.targetIds)) - throw TypeError(".google.firestore.v1beta1.TargetChange.targetIds: array expected"); - message.targetIds = []; - for (var i = 0; i < object.targetIds.length; ++i) - message.targetIds[i] = object.targetIds[i] | 0; - } - if (object.cause != null) { - if (typeof object.cause !== "object") - throw TypeError(".google.firestore.v1beta1.TargetChange.cause: object expected"); - message.cause = $root.google.rpc.Status.fromObject(object.cause); - } - if (object.resumeToken != null) - if (typeof object.resumeToken === "string") - $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); - else if (object.resumeToken.length) - message.resumeToken = object.resumeToken; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.TargetChange.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a TargetChange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.TargetChange - * @static - * @param {google.firestore.v1beta1.TargetChange} message TargetChange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - TargetChange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.targetIds = []; - if (options.defaults) { - object.targetChangeType = options.enums === String ? "NO_CHANGE" : 0; - object.cause = null; - object.resumeToken = options.bytes === String ? "" : []; - object.readTime = null; - } - if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) - object.targetChangeType = options.enums === String ? $root.google.firestore.v1beta1.TargetChange.TargetChangeType[message.targetChangeType] : message.targetChangeType; - if (message.targetIds && message.targetIds.length) { - object.targetIds = []; - for (var j = 0; j < message.targetIds.length; ++j) - object.targetIds[j] = message.targetIds[j]; - } - if (message.cause != null && message.hasOwnProperty("cause")) - object.cause = $root.google.rpc.Status.toObject(message.cause, options); - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) - object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - return object; - }; - - /** - * Converts this TargetChange to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.TargetChange - * @instance - * @returns {Object.} JSON object - */ - TargetChange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * TargetChangeType enum. - * @name google.firestore.v1beta1.TargetChange.TargetChangeType - * @enum {string} - * @property {number} NO_CHANGE=0 NO_CHANGE value - * @property {number} ADD=1 ADD value - * @property {number} REMOVE=2 REMOVE value - * @property {number} CURRENT=3 CURRENT value - * @property {number} RESET=4 RESET value - */ - TargetChange.TargetChangeType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "NO_CHANGE"] = 0; - values[valuesById[1] = "ADD"] = 1; - values[valuesById[2] = "REMOVE"] = 2; - values[valuesById[3] = "CURRENT"] = 3; - values[valuesById[4] = "RESET"] = 4; - return values; - })(); - - return TargetChange; - })(); - - v1beta1.ListCollectionIdsRequest = (function() { - - /** - * Properties of a ListCollectionIdsRequest. - * @memberof google.firestore.v1beta1 - * @interface IListCollectionIdsRequest - * @property {string|null} [parent] ListCollectionIdsRequest parent - * @property {number|null} [pageSize] ListCollectionIdsRequest pageSize - * @property {string|null} [pageToken] ListCollectionIdsRequest pageToken - */ - - /** - * Constructs a new ListCollectionIdsRequest. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a ListCollectionIdsRequest. - * @implements IListCollectionIdsRequest - * @constructor - * @param {google.firestore.v1beta1.IListCollectionIdsRequest=} [properties] Properties to set - */ - function ListCollectionIdsRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListCollectionIdsRequest parent. - * @member {string} parent - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.parent = ""; - - /** - * ListCollectionIdsRequest pageSize. - * @member {number} pageSize - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.pageSize = 0; - - /** - * ListCollectionIdsRequest pageToken. - * @member {string} pageToken - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.pageToken = ""; - - /** - * Creates a new ListCollectionIdsRequest instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {google.firestore.v1beta1.IListCollectionIdsRequest=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ListCollectionIdsRequest} ListCollectionIdsRequest instance - */ - ListCollectionIdsRequest.create = function create(properties) { - return new ListCollectionIdsRequest(properties); - }; - - /** - * Encodes the specified ListCollectionIdsRequest message. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsRequest.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {google.firestore.v1beta1.IListCollectionIdsRequest} message ListCollectionIdsRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListCollectionIdsRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.parent != null && message.hasOwnProperty("parent")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); - return writer; - }; - - /** - * Encodes the specified ListCollectionIdsRequest message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {google.firestore.v1beta1.IListCollectionIdsRequest} message ListCollectionIdsRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListCollectionIdsRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListCollectionIdsRequest message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ListCollectionIdsRequest} ListCollectionIdsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListCollectionIdsRequest.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ListCollectionIdsRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.parent = reader.string(); - break; - case 2: - message.pageSize = reader.int32(); - break; - case 3: - message.pageToken = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListCollectionIdsRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ListCollectionIdsRequest} ListCollectionIdsRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListCollectionIdsRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListCollectionIdsRequest message. - * @function verify - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListCollectionIdsRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.parent != null && message.hasOwnProperty("parent")) - if (!$util.isString(message.parent)) - return "parent: string expected"; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - if (!$util.isInteger(message.pageSize)) - return "pageSize: integer expected"; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - if (!$util.isString(message.pageToken)) - return "pageToken: string expected"; - return null; - }; - - /** - * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ListCollectionIdsRequest} ListCollectionIdsRequest - */ - ListCollectionIdsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ListCollectionIdsRequest) - return object; - var message = new $root.google.firestore.v1beta1.ListCollectionIdsRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.pageSize != null) - message.pageSize = object.pageSize | 0; - if (object.pageToken != null) - message.pageToken = String(object.pageToken); - return message; - }; - - /** - * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @static - * @param {google.firestore.v1beta1.ListCollectionIdsRequest} message ListCollectionIdsRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListCollectionIdsRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - object.pageSize = 0; - object.pageToken = ""; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - object.pageSize = message.pageSize; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - object.pageToken = message.pageToken; - return object; - }; - - /** - * Converts this ListCollectionIdsRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ListCollectionIdsRequest - * @instance - * @returns {Object.} JSON object - */ - ListCollectionIdsRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListCollectionIdsRequest; - })(); - - v1beta1.ListCollectionIdsResponse = (function() { - - /** - * Properties of a ListCollectionIdsResponse. - * @memberof google.firestore.v1beta1 - * @interface IListCollectionIdsResponse - * @property {Array.|null} [collectionIds] ListCollectionIdsResponse collectionIds - * @property {string|null} [nextPageToken] ListCollectionIdsResponse nextPageToken - */ - - /** - * Constructs a new ListCollectionIdsResponse. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a ListCollectionIdsResponse. - * @implements IListCollectionIdsResponse - * @constructor - * @param {google.firestore.v1beta1.IListCollectionIdsResponse=} [properties] Properties to set - */ - function ListCollectionIdsResponse(properties) { - this.collectionIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListCollectionIdsResponse collectionIds. - * @member {Array.} collectionIds - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @instance - */ - ListCollectionIdsResponse.prototype.collectionIds = $util.emptyArray; - - /** - * ListCollectionIdsResponse nextPageToken. - * @member {string} nextPageToken - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @instance - */ - ListCollectionIdsResponse.prototype.nextPageToken = ""; - - /** - * Creates a new ListCollectionIdsResponse instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {google.firestore.v1beta1.IListCollectionIdsResponse=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ListCollectionIdsResponse} ListCollectionIdsResponse instance - */ - ListCollectionIdsResponse.create = function create(properties) { - return new ListCollectionIdsResponse(properties); - }; - - /** - * Encodes the specified ListCollectionIdsResponse message. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsResponse.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {google.firestore.v1beta1.IListCollectionIdsResponse} message ListCollectionIdsResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListCollectionIdsResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.collectionIds != null && message.collectionIds.length) - for (var i = 0; i < message.collectionIds.length; ++i) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.collectionIds[i]); - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); - return writer; - }; - - /** - * Encodes the specified ListCollectionIdsResponse message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ListCollectionIdsResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {google.firestore.v1beta1.IListCollectionIdsResponse} message ListCollectionIdsResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListCollectionIdsResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListCollectionIdsResponse message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ListCollectionIdsResponse} ListCollectionIdsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListCollectionIdsResponse.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ListCollectionIdsResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.collectionIds && message.collectionIds.length)) - message.collectionIds = []; - message.collectionIds.push(reader.string()); - break; - case 2: - message.nextPageToken = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListCollectionIdsResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ListCollectionIdsResponse} ListCollectionIdsResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListCollectionIdsResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListCollectionIdsResponse message. - * @function verify - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListCollectionIdsResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.collectionIds != null && message.hasOwnProperty("collectionIds")) { - if (!Array.isArray(message.collectionIds)) - return "collectionIds: array expected"; - for (var i = 0; i < message.collectionIds.length; ++i) - if (!$util.isString(message.collectionIds[i])) - return "collectionIds: string[] expected"; - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - if (!$util.isString(message.nextPageToken)) - return "nextPageToken: string expected"; - return null; - }; - - /** - * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ListCollectionIdsResponse} ListCollectionIdsResponse - */ - ListCollectionIdsResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ListCollectionIdsResponse) - return object; - var message = new $root.google.firestore.v1beta1.ListCollectionIdsResponse(); - if (object.collectionIds) { - if (!Array.isArray(object.collectionIds)) - throw TypeError(".google.firestore.v1beta1.ListCollectionIdsResponse.collectionIds: array expected"); - message.collectionIds = []; - for (var i = 0; i < object.collectionIds.length; ++i) - message.collectionIds[i] = String(object.collectionIds[i]); - } - if (object.nextPageToken != null) - message.nextPageToken = String(object.nextPageToken); - return message; - }; - - /** - * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @static - * @param {google.firestore.v1beta1.ListCollectionIdsResponse} message ListCollectionIdsResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListCollectionIdsResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.collectionIds = []; - if (options.defaults) - object.nextPageToken = ""; - if (message.collectionIds && message.collectionIds.length) { - object.collectionIds = []; - for (var j = 0; j < message.collectionIds.length; ++j) - object.collectionIds[j] = message.collectionIds[j]; - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - object.nextPageToken = message.nextPageToken; - return object; - }; - - /** - * Converts this ListCollectionIdsResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ListCollectionIdsResponse - * @instance - * @returns {Object.} JSON object - */ - ListCollectionIdsResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListCollectionIdsResponse; - })(); - - v1beta1.DocumentMask = (function() { - - /** - * Properties of a DocumentMask. - * @memberof google.firestore.v1beta1 - * @interface IDocumentMask - * @property {Array.|null} [fieldPaths] DocumentMask fieldPaths - */ - - /** - * Constructs a new DocumentMask. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a DocumentMask. - * @implements IDocumentMask - * @constructor - * @param {google.firestore.v1beta1.IDocumentMask=} [properties] Properties to set - */ - function DocumentMask(properties) { - this.fieldPaths = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DocumentMask fieldPaths. - * @member {Array.} fieldPaths - * @memberof google.firestore.v1beta1.DocumentMask - * @instance - */ - DocumentMask.prototype.fieldPaths = $util.emptyArray; - - /** - * Creates a new DocumentMask instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {google.firestore.v1beta1.IDocumentMask=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DocumentMask} DocumentMask instance - */ - DocumentMask.create = function create(properties) { - return new DocumentMask(properties); - }; - - /** - * Encodes the specified DocumentMask message. Does not implicitly {@link google.firestore.v1beta1.DocumentMask.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {google.firestore.v1beta1.IDocumentMask} message DocumentMask message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentMask.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.fieldPaths != null && message.fieldPaths.length) - for (var i = 0; i < message.fieldPaths.length; ++i) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.fieldPaths[i]); - return writer; - }; - - /** - * Encodes the specified DocumentMask message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentMask.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {google.firestore.v1beta1.IDocumentMask} message DocumentMask message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentMask.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DocumentMask message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DocumentMask} DocumentMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentMask.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DocumentMask(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.fieldPaths && message.fieldPaths.length)) - message.fieldPaths = []; - message.fieldPaths.push(reader.string()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DocumentMask message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DocumentMask} DocumentMask - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentMask.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DocumentMask message. - * @function verify - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DocumentMask.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.fieldPaths != null && message.hasOwnProperty("fieldPaths")) { - if (!Array.isArray(message.fieldPaths)) - return "fieldPaths: array expected"; - for (var i = 0; i < message.fieldPaths.length; ++i) - if (!$util.isString(message.fieldPaths[i])) - return "fieldPaths: string[] expected"; - } - return null; - }; - - /** - * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DocumentMask} DocumentMask - */ - DocumentMask.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DocumentMask) - return object; - var message = new $root.google.firestore.v1beta1.DocumentMask(); - if (object.fieldPaths) { - if (!Array.isArray(object.fieldPaths)) - throw TypeError(".google.firestore.v1beta1.DocumentMask.fieldPaths: array expected"); - message.fieldPaths = []; - for (var i = 0; i < object.fieldPaths.length; ++i) - message.fieldPaths[i] = String(object.fieldPaths[i]); - } - return message; - }; - - /** - * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DocumentMask - * @static - * @param {google.firestore.v1beta1.DocumentMask} message DocumentMask - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentMask.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.fieldPaths = []; - if (message.fieldPaths && message.fieldPaths.length) { - object.fieldPaths = []; - for (var j = 0; j < message.fieldPaths.length; ++j) - object.fieldPaths[j] = message.fieldPaths[j]; - } - return object; - }; - - /** - * Converts this DocumentMask to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DocumentMask - * @instance - * @returns {Object.} JSON object - */ - DocumentMask.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DocumentMask; - })(); - - v1beta1.Precondition = (function() { - - /** - * Properties of a Precondition. - * @memberof google.firestore.v1beta1 - * @interface IPrecondition - * @property {boolean|null} [exists] Precondition exists - * @property {google.protobuf.ITimestamp|null} [updateTime] Precondition updateTime - */ - - /** - * Constructs a new Precondition. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Precondition. - * @implements IPrecondition - * @constructor - * @param {google.firestore.v1beta1.IPrecondition=} [properties] Properties to set - */ - function Precondition(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Precondition exists. - * @member {boolean} exists - * @memberof google.firestore.v1beta1.Precondition - * @instance - */ - Precondition.prototype.exists = false; - - /** - * Precondition updateTime. - * @member {google.protobuf.ITimestamp|null|undefined} updateTime - * @memberof google.firestore.v1beta1.Precondition - * @instance - */ - Precondition.prototype.updateTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Precondition conditionType. - * @member {"exists"|"updateTime"|undefined} conditionType - * @memberof google.firestore.v1beta1.Precondition - * @instance - */ - Object.defineProperty(Precondition.prototype, "conditionType", { - get: $util.oneOfGetter($oneOfFields = ["exists", "updateTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new Precondition instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {google.firestore.v1beta1.IPrecondition=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Precondition} Precondition instance - */ - Precondition.create = function create(properties) { - return new Precondition(properties); - }; - - /** - * Encodes the specified Precondition message. Does not implicitly {@link google.firestore.v1beta1.Precondition.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {google.firestore.v1beta1.IPrecondition} message Precondition message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Precondition.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.exists != null && message.hasOwnProperty("exists")) - writer.uint32(/* id 1, wireType 0 =*/8).bool(message.exists); - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - $root.google.protobuf.Timestamp.encode(message.updateTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Precondition message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Precondition.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {google.firestore.v1beta1.IPrecondition} message Precondition message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Precondition.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Precondition message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Precondition} Precondition - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Precondition.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Precondition(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.exists = reader.bool(); - break; - case 2: - message.updateTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Precondition message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Precondition} Precondition - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Precondition.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Precondition message. - * @function verify - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Precondition.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.exists != null && message.hasOwnProperty("exists")) { - properties.conditionType = 1; - if (typeof message.exists !== "boolean") - return "exists: boolean expected"; - } - if (message.updateTime != null && message.hasOwnProperty("updateTime")) { - if (properties.conditionType === 1) - return "conditionType: multiple values"; - properties.conditionType = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.updateTime); - if (error) - return "updateTime." + error; - } - } - return null; - }; - - /** - * Creates a Precondition message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Precondition} Precondition - */ - Precondition.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Precondition) - return object; - var message = new $root.google.firestore.v1beta1.Precondition(); - if (object.exists != null) - message.exists = Boolean(object.exists); - if (object.updateTime != null) { - if (typeof object.updateTime !== "object") - throw TypeError(".google.firestore.v1beta1.Precondition.updateTime: object expected"); - message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); - } - return message; - }; - - /** - * Creates a plain object from a Precondition message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Precondition - * @static - * @param {google.firestore.v1beta1.Precondition} message Precondition - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Precondition.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.exists != null && message.hasOwnProperty("exists")) { - object.exists = message.exists; - if (options.oneofs) - object.conditionType = "exists"; - } - if (message.updateTime != null && message.hasOwnProperty("updateTime")) { - object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); - if (options.oneofs) - object.conditionType = "updateTime"; - } - return object; - }; - - /** - * Converts this Precondition to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Precondition - * @instance - * @returns {Object.} JSON object - */ - Precondition.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Precondition; - })(); - - v1beta1.TransactionOptions = (function() { - - /** - * Properties of a TransactionOptions. - * @memberof google.firestore.v1beta1 - * @interface ITransactionOptions - * @property {google.firestore.v1beta1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly - * @property {google.firestore.v1beta1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite - */ - - /** - * Constructs a new TransactionOptions. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a TransactionOptions. - * @implements ITransactionOptions - * @constructor - * @param {google.firestore.v1beta1.ITransactionOptions=} [properties] Properties to set - */ - function TransactionOptions(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * TransactionOptions readOnly. - * @member {google.firestore.v1beta1.TransactionOptions.IReadOnly|null|undefined} readOnly - * @memberof google.firestore.v1beta1.TransactionOptions - * @instance - */ - TransactionOptions.prototype.readOnly = null; - - /** - * TransactionOptions readWrite. - * @member {google.firestore.v1beta1.TransactionOptions.IReadWrite|null|undefined} readWrite - * @memberof google.firestore.v1beta1.TransactionOptions - * @instance - */ - TransactionOptions.prototype.readWrite = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * TransactionOptions mode. - * @member {"readOnly"|"readWrite"|undefined} mode - * @memberof google.firestore.v1beta1.TransactionOptions - * @instance - */ - Object.defineProperty(TransactionOptions.prototype, "mode", { - get: $util.oneOfGetter($oneOfFields = ["readOnly", "readWrite"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new TransactionOptions instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {google.firestore.v1beta1.ITransactionOptions=} [properties] Properties to set - * @returns {google.firestore.v1beta1.TransactionOptions} TransactionOptions instance - */ - TransactionOptions.create = function create(properties) { - return new TransactionOptions(properties); - }; - - /** - * Encodes the specified TransactionOptions message. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {google.firestore.v1beta1.ITransactionOptions} message TransactionOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - TransactionOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.readOnly != null && message.hasOwnProperty("readOnly")) - $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.encode(message.readOnly, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.readWrite != null && message.hasOwnProperty("readWrite")) - $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.encode(message.readWrite, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified TransactionOptions message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {google.firestore.v1beta1.ITransactionOptions} message TransactionOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - TransactionOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a TransactionOptions message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.TransactionOptions} TransactionOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - TransactionOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.TransactionOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.readOnly = $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.decode(reader, reader.uint32()); - break; - case 3: - message.readWrite = $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a TransactionOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.TransactionOptions} TransactionOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - TransactionOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a TransactionOptions message. - * @function verify - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - TransactionOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.readOnly != null && message.hasOwnProperty("readOnly")) { - properties.mode = 1; - { - var error = $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.verify(message.readOnly); - if (error) - return "readOnly." + error; - } - } - if (message.readWrite != null && message.hasOwnProperty("readWrite")) { - if (properties.mode === 1) - return "mode: multiple values"; - properties.mode = 1; - { - var error = $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.verify(message.readWrite); - if (error) - return "readWrite." + error; - } - } - return null; - }; - - /** - * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.TransactionOptions} TransactionOptions - */ - TransactionOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.TransactionOptions) - return object; - var message = new $root.google.firestore.v1beta1.TransactionOptions(); - if (object.readOnly != null) { - if (typeof object.readOnly !== "object") - throw TypeError(".google.firestore.v1beta1.TransactionOptions.readOnly: object expected"); - message.readOnly = $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.fromObject(object.readOnly); - } - if (object.readWrite != null) { - if (typeof object.readWrite !== "object") - throw TypeError(".google.firestore.v1beta1.TransactionOptions.readWrite: object expected"); - message.readWrite = $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.fromObject(object.readWrite); - } - return message; - }; - - /** - * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.TransactionOptions - * @static - * @param {google.firestore.v1beta1.TransactionOptions} message TransactionOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - TransactionOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.readOnly != null && message.hasOwnProperty("readOnly")) { - object.readOnly = $root.google.firestore.v1beta1.TransactionOptions.ReadOnly.toObject(message.readOnly, options); - if (options.oneofs) - object.mode = "readOnly"; - } - if (message.readWrite != null && message.hasOwnProperty("readWrite")) { - object.readWrite = $root.google.firestore.v1beta1.TransactionOptions.ReadWrite.toObject(message.readWrite, options); - if (options.oneofs) - object.mode = "readWrite"; - } - return object; - }; - - /** - * Converts this TransactionOptions to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.TransactionOptions - * @instance - * @returns {Object.} JSON object - */ - TransactionOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - TransactionOptions.ReadWrite = (function() { - - /** - * Properties of a ReadWrite. - * @memberof google.firestore.v1beta1.TransactionOptions - * @interface IReadWrite - * @property {Uint8Array|null} [retryTransaction] ReadWrite retryTransaction - */ - - /** - * Constructs a new ReadWrite. - * @memberof google.firestore.v1beta1.TransactionOptions - * @classdesc Represents a ReadWrite. - * @implements IReadWrite - * @constructor - * @param {google.firestore.v1beta1.TransactionOptions.IReadWrite=} [properties] Properties to set - */ - function ReadWrite(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ReadWrite retryTransaction. - * @member {Uint8Array} retryTransaction - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @instance - */ - ReadWrite.prototype.retryTransaction = $util.newBuffer([]); - - /** - * Creates a new ReadWrite instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {google.firestore.v1beta1.TransactionOptions.IReadWrite=} [properties] Properties to set - * @returns {google.firestore.v1beta1.TransactionOptions.ReadWrite} ReadWrite instance - */ - ReadWrite.create = function create(properties) { - return new ReadWrite(properties); - }; - - /** - * Encodes the specified ReadWrite message. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadWrite.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {google.firestore.v1beta1.TransactionOptions.IReadWrite} message ReadWrite message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ReadWrite.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) - writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.retryTransaction); - return writer; - }; - - /** - * Encodes the specified ReadWrite message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadWrite.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {google.firestore.v1beta1.TransactionOptions.IReadWrite} message ReadWrite message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ReadWrite.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ReadWrite message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.TransactionOptions.ReadWrite} ReadWrite - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ReadWrite.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.TransactionOptions.ReadWrite(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.retryTransaction = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ReadWrite message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.TransactionOptions.ReadWrite} ReadWrite - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ReadWrite.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ReadWrite message. - * @function verify - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ReadWrite.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) - if (!(message.retryTransaction && typeof message.retryTransaction.length === "number" || $util.isString(message.retryTransaction))) - return "retryTransaction: buffer expected"; - return null; - }; - - /** - * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.TransactionOptions.ReadWrite} ReadWrite - */ - ReadWrite.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.TransactionOptions.ReadWrite) - return object; - var message = new $root.google.firestore.v1beta1.TransactionOptions.ReadWrite(); - if (object.retryTransaction != null) - if (typeof object.retryTransaction === "string") - $util.base64.decode(object.retryTransaction, message.retryTransaction = $util.newBuffer($util.base64.length(object.retryTransaction)), 0); - else if (object.retryTransaction.length) - message.retryTransaction = object.retryTransaction; - return message; - }; - - /** - * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @static - * @param {google.firestore.v1beta1.TransactionOptions.ReadWrite} message ReadWrite - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ReadWrite.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.retryTransaction = options.bytes === String ? "" : []; - if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) - object.retryTransaction = options.bytes === String ? $util.base64.encode(message.retryTransaction, 0, message.retryTransaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.retryTransaction) : message.retryTransaction; - return object; - }; - - /** - * Converts this ReadWrite to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.TransactionOptions.ReadWrite - * @instance - * @returns {Object.} JSON object - */ - ReadWrite.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ReadWrite; - })(); - - TransactionOptions.ReadOnly = (function() { - - /** - * Properties of a ReadOnly. - * @memberof google.firestore.v1beta1.TransactionOptions - * @interface IReadOnly - * @property {google.protobuf.ITimestamp|null} [readTime] ReadOnly readTime - */ - - /** - * Constructs a new ReadOnly. - * @memberof google.firestore.v1beta1.TransactionOptions - * @classdesc Represents a ReadOnly. - * @implements IReadOnly - * @constructor - * @param {google.firestore.v1beta1.TransactionOptions.IReadOnly=} [properties] Properties to set - */ - function ReadOnly(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ReadOnly readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @instance - */ - ReadOnly.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * ReadOnly consistencySelector. - * @member {"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @instance - */ - Object.defineProperty(ReadOnly.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new ReadOnly instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {google.firestore.v1beta1.TransactionOptions.IReadOnly=} [properties] Properties to set - * @returns {google.firestore.v1beta1.TransactionOptions.ReadOnly} ReadOnly instance - */ - ReadOnly.create = function create(properties) { - return new ReadOnly(properties); - }; - - /** - * Encodes the specified ReadOnly message. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadOnly.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {google.firestore.v1beta1.TransactionOptions.IReadOnly} message ReadOnly message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ReadOnly.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified ReadOnly message, length delimited. Does not implicitly {@link google.firestore.v1beta1.TransactionOptions.ReadOnly.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {google.firestore.v1beta1.TransactionOptions.IReadOnly} message ReadOnly message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ReadOnly.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ReadOnly message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.TransactionOptions.ReadOnly} ReadOnly - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ReadOnly.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.TransactionOptions.ReadOnly(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ReadOnly message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.TransactionOptions.ReadOnly} ReadOnly - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ReadOnly.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ReadOnly message. - * @function verify - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ReadOnly.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - properties.consistencySelector = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - } - return null; - }; - - /** - * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.TransactionOptions.ReadOnly} ReadOnly - */ - ReadOnly.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.TransactionOptions.ReadOnly) - return object; - var message = new $root.google.firestore.v1beta1.TransactionOptions.ReadOnly(); - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.TransactionOptions.ReadOnly.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @static - * @param {google.firestore.v1beta1.TransactionOptions.ReadOnly} message ReadOnly - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ReadOnly.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; - - /** - * Converts this ReadOnly to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.TransactionOptions.ReadOnly - * @instance - * @returns {Object.} JSON object - */ - ReadOnly.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ReadOnly; - })(); - - return TransactionOptions; - })(); - - v1beta1.Document = (function() { - - /** - * Properties of a Document. - * @memberof google.firestore.v1beta1 - * @interface IDocument - * @property {string|null} [name] Document name - * @property {Object.|null} [fields] Document fields - * @property {google.protobuf.ITimestamp|null} [createTime] Document createTime - * @property {google.protobuf.ITimestamp|null} [updateTime] Document updateTime - */ - - /** - * Constructs a new Document. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Document. - * @implements IDocument - * @constructor - * @param {google.firestore.v1beta1.IDocument=} [properties] Properties to set - */ - function Document(properties) { - this.fields = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Document name. - * @member {string} name - * @memberof google.firestore.v1beta1.Document - * @instance - */ - Document.prototype.name = ""; - - /** - * Document fields. - * @member {Object.} fields - * @memberof google.firestore.v1beta1.Document - * @instance - */ - Document.prototype.fields = $util.emptyObject; - - /** - * Document createTime. - * @member {google.protobuf.ITimestamp|null|undefined} createTime - * @memberof google.firestore.v1beta1.Document - * @instance - */ - Document.prototype.createTime = null; - - /** - * Document updateTime. - * @member {google.protobuf.ITimestamp|null|undefined} updateTime - * @memberof google.firestore.v1beta1.Document - * @instance - */ - Document.prototype.updateTime = null; - - /** - * Creates a new Document instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Document - * @static - * @param {google.firestore.v1beta1.IDocument=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Document} Document instance - */ - Document.create = function create(properties) { - return new Document(properties); - }; - - /** - * Encodes the specified Document message. Does not implicitly {@link google.firestore.v1beta1.Document.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Document - * @static - * @param {google.firestore.v1beta1.IDocument} message Document message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Document.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.fields != null && message.hasOwnProperty("fields")) - for (var keys = Object.keys(message.fields), i = 0; i < keys.length; ++i) { - writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); - $root.google.firestore.v1beta1.Value.encode(message.fields[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); - } - if (message.createTime != null && message.hasOwnProperty("createTime")) - $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - $root.google.protobuf.Timestamp.encode(message.updateTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Document message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Document.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Document - * @static - * @param {google.firestore.v1beta1.IDocument} message Document message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Document.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Document message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Document - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Document} Document - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Document.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Document(), key; - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - reader.skip().pos++; - if (message.fields === $util.emptyObject) - message.fields = {}; - key = reader.string(); - reader.pos++; - message.fields[key] = $root.google.firestore.v1beta1.Value.decode(reader, reader.uint32()); - break; - case 3: - message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - case 4: - message.updateTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Document message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Document - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Document} Document - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Document.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Document message. - * @function verify - * @memberof google.firestore.v1beta1.Document - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Document.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.fields != null && message.hasOwnProperty("fields")) { - if (!$util.isObject(message.fields)) - return "fields: object expected"; - var key = Object.keys(message.fields); - for (var i = 0; i < key.length; ++i) { - var error = $root.google.firestore.v1beta1.Value.verify(message.fields[key[i]]); - if (error) - return "fields." + error; - } - } - if (message.createTime != null && message.hasOwnProperty("createTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.createTime); - if (error) - return "createTime." + error; - } - if (message.updateTime != null && message.hasOwnProperty("updateTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.updateTime); - if (error) - return "updateTime." + error; - } - return null; - }; - - /** - * Creates a Document message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Document - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Document} Document - */ - Document.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Document) - return object; - var message = new $root.google.firestore.v1beta1.Document(); - if (object.name != null) - message.name = String(object.name); - if (object.fields) { - if (typeof object.fields !== "object") - throw TypeError(".google.firestore.v1beta1.Document.fields: object expected"); - message.fields = {}; - for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { - if (typeof object.fields[keys[i]] !== "object") - throw TypeError(".google.firestore.v1beta1.Document.fields: object expected"); - message.fields[keys[i]] = $root.google.firestore.v1beta1.Value.fromObject(object.fields[keys[i]]); - } - } - if (object.createTime != null) { - if (typeof object.createTime !== "object") - throw TypeError(".google.firestore.v1beta1.Document.createTime: object expected"); - message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); - } - if (object.updateTime != null) { - if (typeof object.updateTime !== "object") - throw TypeError(".google.firestore.v1beta1.Document.updateTime: object expected"); - message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); - } - return message; - }; - - /** - * Creates a plain object from a Document message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Document - * @static - * @param {google.firestore.v1beta1.Document} message Document - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Document.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.fields = {}; - if (options.defaults) { - object.name = ""; - object.createTime = null; - object.updateTime = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - var keys2; - if (message.fields && (keys2 = Object.keys(message.fields)).length) { - object.fields = {}; - for (var j = 0; j < keys2.length; ++j) - object.fields[keys2[j]] = $root.google.firestore.v1beta1.Value.toObject(message.fields[keys2[j]], options); - } - if (message.createTime != null && message.hasOwnProperty("createTime")) - object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); - return object; - }; - - /** - * Converts this Document to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Document - * @instance - * @returns {Object.} JSON object - */ - Document.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Document; - })(); - - v1beta1.Value = (function() { - - /** - * Properties of a Value. - * @memberof google.firestore.v1beta1 - * @interface IValue - * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue - * @property {boolean|null} [booleanValue] Value booleanValue - * @property {number|string|null} [integerValue] Value integerValue - * @property {number|null} [doubleValue] Value doubleValue - * @property {google.protobuf.ITimestamp|null} [timestampValue] Value timestampValue - * @property {string|null} [stringValue] Value stringValue - * @property {Uint8Array|null} [bytesValue] Value bytesValue - * @property {string|null} [referenceValue] Value referenceValue - * @property {google.type.ILatLng|null} [geoPointValue] Value geoPointValue - * @property {google.firestore.v1beta1.IArrayValue|null} [arrayValue] Value arrayValue - * @property {google.firestore.v1beta1.IMapValue|null} [mapValue] Value mapValue - */ - - /** - * Constructs a new Value. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Value. - * @implements IValue - * @constructor - * @param {google.firestore.v1beta1.IValue=} [properties] Properties to set - */ - function Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Value nullValue. - * @member {google.protobuf.NullValue} nullValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.nullValue = 0; - - /** - * Value booleanValue. - * @member {boolean} booleanValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.booleanValue = false; - - /** - * Value integerValue. - * @member {number|string} integerValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.integerValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - - /** - * Value doubleValue. - * @member {number} doubleValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.doubleValue = 0; - - /** - * Value timestampValue. - * @member {google.protobuf.ITimestamp|null|undefined} timestampValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.timestampValue = null; - - /** - * Value stringValue. - * @member {string} stringValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.stringValue = ""; - - /** - * Value bytesValue. - * @member {Uint8Array} bytesValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.bytesValue = $util.newBuffer([]); - - /** - * Value referenceValue. - * @member {string} referenceValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.referenceValue = ""; - - /** - * Value geoPointValue. - * @member {google.type.ILatLng|null|undefined} geoPointValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.geoPointValue = null; - - /** - * Value arrayValue. - * @member {google.firestore.v1beta1.IArrayValue|null|undefined} arrayValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.arrayValue = null; - - /** - * Value mapValue. - * @member {google.firestore.v1beta1.IMapValue|null|undefined} mapValue - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Value.prototype.mapValue = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Value valueType. - * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|undefined} valueType - * @memberof google.firestore.v1beta1.Value - * @instance - */ - Object.defineProperty(Value.prototype, "valueType", { - get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new Value instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Value - * @static - * @param {google.firestore.v1beta1.IValue=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Value} Value instance - */ - Value.create = function create(properties) { - return new Value(properties); - }; - - /** - * Encodes the specified Value message. Does not implicitly {@link google.firestore.v1beta1.Value.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Value - * @static - * @param {google.firestore.v1beta1.IValue} message Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Value.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) - writer.uint32(/* id 1, wireType 0 =*/8).bool(message.booleanValue); - if (message.integerValue != null && message.hasOwnProperty("integerValue")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.integerValue); - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) - writer.uint32(/* id 3, wireType 1 =*/25).double(message.doubleValue); - if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message.referenceValue); - if (message.mapValue != null && message.hasOwnProperty("mapValue")) - $root.google.firestore.v1beta1.MapValue.encode(message.mapValue, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) - $root.google.type.LatLng.encode(message.geoPointValue, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) - $root.google.firestore.v1beta1.ArrayValue.encode(message.arrayValue, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); - if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) - $root.google.protobuf.Timestamp.encode(message.timestampValue, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); - if (message.nullValue != null && message.hasOwnProperty("nullValue")) - writer.uint32(/* id 11, wireType 0 =*/88).int32(message.nullValue); - if (message.stringValue != null && message.hasOwnProperty("stringValue")) - writer.uint32(/* id 17, wireType 2 =*/138).string(message.stringValue); - if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) - writer.uint32(/* id 18, wireType 2 =*/146).bytes(message.bytesValue); - return writer; - }; - - /** - * Encodes the specified Value message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Value.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Value - * @static - * @param {google.firestore.v1beta1.IValue} message Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Value.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Value message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Value} Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Value.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Value(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 11: - message.nullValue = reader.int32(); - break; - case 1: - message.booleanValue = reader.bool(); - break; - case 2: - message.integerValue = reader.int64(); - break; - case 3: - message.doubleValue = reader.double(); - break; - case 10: - message.timestampValue = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - case 17: - message.stringValue = reader.string(); - break; - case 18: - message.bytesValue = reader.bytes(); - break; - case 5: - message.referenceValue = reader.string(); - break; - case 8: - message.geoPointValue = $root.google.type.LatLng.decode(reader, reader.uint32()); - break; - case 9: - message.arrayValue = $root.google.firestore.v1beta1.ArrayValue.decode(reader, reader.uint32()); - break; - case 6: - message.mapValue = $root.google.firestore.v1beta1.MapValue.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Value message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Value} Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Value.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Value message. - * @function verify - * @memberof google.firestore.v1beta1.Value - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Value.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.nullValue != null && message.hasOwnProperty("nullValue")) { - properties.valueType = 1; - switch (message.nullValue) { - default: - return "nullValue: enum value expected"; - case 0: - break; - } - } - if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - if (typeof message.booleanValue !== "boolean") - return "booleanValue: boolean expected"; - } - if (message.integerValue != null && message.hasOwnProperty("integerValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - if (!$util.isInteger(message.integerValue) && !(message.integerValue && $util.isInteger(message.integerValue.low) && $util.isInteger(message.integerValue.high))) - return "integerValue: integer|Long expected"; - } - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - if (typeof message.doubleValue !== "number") - return "doubleValue: number expected"; - } - if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - { - var error = $root.google.protobuf.Timestamp.verify(message.timestampValue); - if (error) - return "timestampValue." + error; - } - } - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - if (!$util.isString(message.stringValue)) - return "stringValue: string expected"; - } - if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - if (!(message.bytesValue && typeof message.bytesValue.length === "number" || $util.isString(message.bytesValue))) - return "bytesValue: buffer expected"; - } - if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - if (!$util.isString(message.referenceValue)) - return "referenceValue: string expected"; - } - if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - { - var error = $root.google.type.LatLng.verify(message.geoPointValue); - if (error) - return "geoPointValue." + error; - } - } - if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - { - var error = $root.google.firestore.v1beta1.ArrayValue.verify(message.arrayValue); - if (error) - return "arrayValue." + error; - } - } - if (message.mapValue != null && message.hasOwnProperty("mapValue")) { - if (properties.valueType === 1) - return "valueType: multiple values"; - properties.valueType = 1; - { - var error = $root.google.firestore.v1beta1.MapValue.verify(message.mapValue); - if (error) - return "mapValue." + error; - } - } - return null; - }; - - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Value - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Value} Value - */ - Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Value) - return object; - var message = new $root.google.firestore.v1beta1.Value(); - switch (object.nullValue) { - case "NULL_VALUE": - case 0: - message.nullValue = 0; - break; - } - if (object.booleanValue != null) - message.booleanValue = Boolean(object.booleanValue); - if (object.integerValue != null) - if ($util.Long) - (message.integerValue = $util.Long.fromValue(object.integerValue)).unsigned = false; - else if (typeof object.integerValue === "string") - message.integerValue = parseInt(object.integerValue, 10); - else if (typeof object.integerValue === "number") - message.integerValue = object.integerValue; - else if (typeof object.integerValue === "object") - message.integerValue = new $util.LongBits(object.integerValue.low >>> 0, object.integerValue.high >>> 0).toNumber(); - if (object.doubleValue != null) - message.doubleValue = Number(object.doubleValue); - if (object.timestampValue != null) { - if (typeof object.timestampValue !== "object") - throw TypeError(".google.firestore.v1beta1.Value.timestampValue: object expected"); - message.timestampValue = $root.google.protobuf.Timestamp.fromObject(object.timestampValue); - } - if (object.stringValue != null) - message.stringValue = String(object.stringValue); - if (object.bytesValue != null) - if (typeof object.bytesValue === "string") - $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); - else if (object.bytesValue.length) - message.bytesValue = object.bytesValue; - if (object.referenceValue != null) - message.referenceValue = String(object.referenceValue); - if (object.geoPointValue != null) { - if (typeof object.geoPointValue !== "object") - throw TypeError(".google.firestore.v1beta1.Value.geoPointValue: object expected"); - message.geoPointValue = $root.google.type.LatLng.fromObject(object.geoPointValue); - } - if (object.arrayValue != null) { - if (typeof object.arrayValue !== "object") - throw TypeError(".google.firestore.v1beta1.Value.arrayValue: object expected"); - message.arrayValue = $root.google.firestore.v1beta1.ArrayValue.fromObject(object.arrayValue); - } - if (object.mapValue != null) { - if (typeof object.mapValue !== "object") - throw TypeError(".google.firestore.v1beta1.Value.mapValue: object expected"); - message.mapValue = $root.google.firestore.v1beta1.MapValue.fromObject(object.mapValue); - } - return message; - }; - - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Value - * @static - * @param {google.firestore.v1beta1.Value} message Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) { - object.booleanValue = message.booleanValue; - if (options.oneofs) - object.valueType = "booleanValue"; - } - if (message.integerValue != null && message.hasOwnProperty("integerValue")) { - if (typeof message.integerValue === "number") - object.integerValue = options.longs === String ? String(message.integerValue) : message.integerValue; - else - object.integerValue = options.longs === String ? $util.Long.prototype.toString.call(message.integerValue) : options.longs === Number ? new $util.LongBits(message.integerValue.low >>> 0, message.integerValue.high >>> 0).toNumber() : message.integerValue; - if (options.oneofs) - object.valueType = "integerValue"; - } - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { - object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; - if (options.oneofs) - object.valueType = "doubleValue"; - } - if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) { - object.referenceValue = message.referenceValue; - if (options.oneofs) - object.valueType = "referenceValue"; - } - if (message.mapValue != null && message.hasOwnProperty("mapValue")) { - object.mapValue = $root.google.firestore.v1beta1.MapValue.toObject(message.mapValue, options); - if (options.oneofs) - object.valueType = "mapValue"; - } - if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) { - object.geoPointValue = $root.google.type.LatLng.toObject(message.geoPointValue, options); - if (options.oneofs) - object.valueType = "geoPointValue"; - } - if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { - object.arrayValue = $root.google.firestore.v1beta1.ArrayValue.toObject(message.arrayValue, options); - if (options.oneofs) - object.valueType = "arrayValue"; - } - if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { - object.timestampValue = $root.google.protobuf.Timestamp.toObject(message.timestampValue, options); - if (options.oneofs) - object.valueType = "timestampValue"; - } - if (message.nullValue != null && message.hasOwnProperty("nullValue")) { - object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; - if (options.oneofs) - object.valueType = "nullValue"; - } - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - object.stringValue = message.stringValue; - if (options.oneofs) - object.valueType = "stringValue"; - } - if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { - object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; - if (options.oneofs) - object.valueType = "bytesValue"; - } - return object; - }; - - /** - * Converts this Value to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Value - * @instance - * @returns {Object.} JSON object - */ - Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Value; - })(); - - v1beta1.ArrayValue = (function() { - - /** - * Properties of an ArrayValue. - * @memberof google.firestore.v1beta1 - * @interface IArrayValue - * @property {Array.|null} [values] ArrayValue values - */ - - /** - * Constructs a new ArrayValue. - * @memberof google.firestore.v1beta1 - * @classdesc Represents an ArrayValue. - * @implements IArrayValue - * @constructor - * @param {google.firestore.v1beta1.IArrayValue=} [properties] Properties to set - */ - function ArrayValue(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ArrayValue values. - * @member {Array.} values - * @memberof google.firestore.v1beta1.ArrayValue - * @instance - */ - ArrayValue.prototype.values = $util.emptyArray; - - /** - * Creates a new ArrayValue instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {google.firestore.v1beta1.IArrayValue=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ArrayValue} ArrayValue instance - */ - ArrayValue.create = function create(properties) { - return new ArrayValue(properties); - }; - - /** - * Encodes the specified ArrayValue message. Does not implicitly {@link google.firestore.v1beta1.ArrayValue.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {google.firestore.v1beta1.IArrayValue} message ArrayValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ArrayValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.values != null && message.values.length) - for (var i = 0; i < message.values.length; ++i) - $root.google.firestore.v1beta1.Value.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified ArrayValue message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ArrayValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {google.firestore.v1beta1.IArrayValue} message ArrayValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ArrayValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an ArrayValue message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ArrayValue} ArrayValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ArrayValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ArrayValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.values && message.values.length)) - message.values = []; - message.values.push($root.google.firestore.v1beta1.Value.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an ArrayValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ArrayValue} ArrayValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ArrayValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an ArrayValue message. - * @function verify - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ArrayValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.values != null && message.hasOwnProperty("values")) { - if (!Array.isArray(message.values)) - return "values: array expected"; - for (var i = 0; i < message.values.length; ++i) { - var error = $root.google.firestore.v1beta1.Value.verify(message.values[i]); - if (error) - return "values." + error; - } - } - return null; - }; - - /** - * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ArrayValue} ArrayValue - */ - ArrayValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ArrayValue) - return object; - var message = new $root.google.firestore.v1beta1.ArrayValue(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".google.firestore.v1beta1.ArrayValue.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".google.firestore.v1beta1.ArrayValue.values: object expected"); - message.values[i] = $root.google.firestore.v1beta1.Value.fromObject(object.values[i]); - } - } - return message; - }; - - /** - * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ArrayValue - * @static - * @param {google.firestore.v1beta1.ArrayValue} message ArrayValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ArrayValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.google.firestore.v1beta1.Value.toObject(message.values[j], options); - } - return object; - }; - - /** - * Converts this ArrayValue to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ArrayValue - * @instance - * @returns {Object.} JSON object - */ - ArrayValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ArrayValue; - })(); - - v1beta1.MapValue = (function() { - - /** - * Properties of a MapValue. - * @memberof google.firestore.v1beta1 - * @interface IMapValue - * @property {Object.|null} [fields] MapValue fields - */ - - /** - * Constructs a new MapValue. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a MapValue. - * @implements IMapValue - * @constructor - * @param {google.firestore.v1beta1.IMapValue=} [properties] Properties to set - */ - function MapValue(properties) { - this.fields = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * MapValue fields. - * @member {Object.} fields - * @memberof google.firestore.v1beta1.MapValue - * @instance - */ - MapValue.prototype.fields = $util.emptyObject; - - /** - * Creates a new MapValue instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {google.firestore.v1beta1.IMapValue=} [properties] Properties to set - * @returns {google.firestore.v1beta1.MapValue} MapValue instance - */ - MapValue.create = function create(properties) { - return new MapValue(properties); - }; - - /** - * Encodes the specified MapValue message. Does not implicitly {@link google.firestore.v1beta1.MapValue.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {google.firestore.v1beta1.IMapValue} message MapValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MapValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.fields != null && message.hasOwnProperty("fields")) - for (var keys = Object.keys(message.fields), i = 0; i < keys.length; ++i) { - writer.uint32(/* id 1, wireType 2 =*/10).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); - $root.google.firestore.v1beta1.Value.encode(message.fields[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); - } - return writer; - }; - - /** - * Encodes the specified MapValue message, length delimited. Does not implicitly {@link google.firestore.v1beta1.MapValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {google.firestore.v1beta1.IMapValue} message MapValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MapValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a MapValue message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.MapValue} MapValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MapValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.MapValue(), key; - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - reader.skip().pos++; - if (message.fields === $util.emptyObject) - message.fields = {}; - key = reader.string(); - reader.pos++; - message.fields[key] = $root.google.firestore.v1beta1.Value.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a MapValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.MapValue} MapValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MapValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a MapValue message. - * @function verify - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - MapValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.fields != null && message.hasOwnProperty("fields")) { - if (!$util.isObject(message.fields)) - return "fields: object expected"; - var key = Object.keys(message.fields); - for (var i = 0; i < key.length; ++i) { - var error = $root.google.firestore.v1beta1.Value.verify(message.fields[key[i]]); - if (error) - return "fields." + error; - } - } - return null; - }; - - /** - * Creates a MapValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.MapValue} MapValue - */ - MapValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.MapValue) - return object; - var message = new $root.google.firestore.v1beta1.MapValue(); - if (object.fields) { - if (typeof object.fields !== "object") - throw TypeError(".google.firestore.v1beta1.MapValue.fields: object expected"); - message.fields = {}; - for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { - if (typeof object.fields[keys[i]] !== "object") - throw TypeError(".google.firestore.v1beta1.MapValue.fields: object expected"); - message.fields[keys[i]] = $root.google.firestore.v1beta1.Value.fromObject(object.fields[keys[i]]); - } - } - return message; - }; - - /** - * Creates a plain object from a MapValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.MapValue - * @static - * @param {google.firestore.v1beta1.MapValue} message MapValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MapValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.fields = {}; - var keys2; - if (message.fields && (keys2 = Object.keys(message.fields)).length) { - object.fields = {}; - for (var j = 0; j < keys2.length; ++j) - object.fields[keys2[j]] = $root.google.firestore.v1beta1.Value.toObject(message.fields[keys2[j]], options); - } - return object; - }; - - /** - * Converts this MapValue to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.MapValue - * @instance - * @returns {Object.} JSON object - */ - MapValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return MapValue; - })(); - - v1beta1.StructuredQuery = (function() { - - /** - * Properties of a StructuredQuery. - * @memberof google.firestore.v1beta1 - * @interface IStructuredQuery - * @property {google.firestore.v1beta1.StructuredQuery.IProjection|null} [select] StructuredQuery select - * @property {Array.|null} [from] StructuredQuery from - * @property {google.firestore.v1beta1.StructuredQuery.IFilter|null} [where] StructuredQuery where - * @property {Array.|null} [orderBy] StructuredQuery orderBy - * @property {google.firestore.v1beta1.ICursor|null} [startAt] StructuredQuery startAt - * @property {google.firestore.v1beta1.ICursor|null} [endAt] StructuredQuery endAt - * @property {number|null} [offset] StructuredQuery offset - * @property {google.protobuf.IInt32Value|null} [limit] StructuredQuery limit - */ - - /** - * Constructs a new StructuredQuery. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a StructuredQuery. - * @implements IStructuredQuery - * @constructor - * @param {google.firestore.v1beta1.IStructuredQuery=} [properties] Properties to set - */ - function StructuredQuery(properties) { - this.from = []; - this.orderBy = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * StructuredQuery select. - * @member {google.firestore.v1beta1.StructuredQuery.IProjection|null|undefined} select - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.select = null; - - /** - * StructuredQuery from. - * @member {Array.} from - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.from = $util.emptyArray; - - /** - * StructuredQuery where. - * @member {google.firestore.v1beta1.StructuredQuery.IFilter|null|undefined} where - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.where = null; - - /** - * StructuredQuery orderBy. - * @member {Array.} orderBy - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.orderBy = $util.emptyArray; - - /** - * StructuredQuery startAt. - * @member {google.firestore.v1beta1.ICursor|null|undefined} startAt - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.startAt = null; - - /** - * StructuredQuery endAt. - * @member {google.firestore.v1beta1.ICursor|null|undefined} endAt - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.endAt = null; - - /** - * StructuredQuery offset. - * @member {number} offset - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.offset = 0; - - /** - * StructuredQuery limit. - * @member {google.protobuf.IInt32Value|null|undefined} limit - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.limit = null; - - /** - * Creates a new StructuredQuery instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {google.firestore.v1beta1.IStructuredQuery=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery} StructuredQuery instance - */ - StructuredQuery.create = function create(properties) { - return new StructuredQuery(properties); - }; - - /** - * Encodes the specified StructuredQuery message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {google.firestore.v1beta1.IStructuredQuery} message StructuredQuery message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - StructuredQuery.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.select != null && message.hasOwnProperty("select")) - $root.google.firestore.v1beta1.StructuredQuery.Projection.encode(message.select, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.from != null && message.from.length) - for (var i = 0; i < message.from.length; ++i) - $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.encode(message.from[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.where != null && message.hasOwnProperty("where")) - $root.google.firestore.v1beta1.StructuredQuery.Filter.encode(message.where, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.orderBy != null && message.orderBy.length) - for (var i = 0; i < message.orderBy.length; ++i) - $root.google.firestore.v1beta1.StructuredQuery.Order.encode(message.orderBy[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.limit != null && message.hasOwnProperty("limit")) - $root.google.protobuf.Int32Value.encode(message.limit, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.offset != null && message.hasOwnProperty("offset")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.offset); - if (message.startAt != null && message.hasOwnProperty("startAt")) - $root.google.firestore.v1beta1.Cursor.encode(message.startAt, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - if (message.endAt != null && message.hasOwnProperty("endAt")) - $root.google.firestore.v1beta1.Cursor.encode(message.endAt, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified StructuredQuery message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {google.firestore.v1beta1.IStructuredQuery} message StructuredQuery message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - StructuredQuery.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a StructuredQuery message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery} StructuredQuery - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - StructuredQuery.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.select = $root.google.firestore.v1beta1.StructuredQuery.Projection.decode(reader, reader.uint32()); - break; - case 2: - if (!(message.from && message.from.length)) - message.from = []; - message.from.push($root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.decode(reader, reader.uint32())); - break; - case 3: - message.where = $root.google.firestore.v1beta1.StructuredQuery.Filter.decode(reader, reader.uint32()); - break; - case 4: - if (!(message.orderBy && message.orderBy.length)) - message.orderBy = []; - message.orderBy.push($root.google.firestore.v1beta1.StructuredQuery.Order.decode(reader, reader.uint32())); - break; - case 7: - message.startAt = $root.google.firestore.v1beta1.Cursor.decode(reader, reader.uint32()); - break; - case 8: - message.endAt = $root.google.firestore.v1beta1.Cursor.decode(reader, reader.uint32()); - break; - case 6: - message.offset = reader.int32(); - break; - case 5: - message.limit = $root.google.protobuf.Int32Value.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a StructuredQuery message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery} StructuredQuery - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - StructuredQuery.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a StructuredQuery message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - StructuredQuery.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.select != null && message.hasOwnProperty("select")) { - var error = $root.google.firestore.v1beta1.StructuredQuery.Projection.verify(message.select); - if (error) - return "select." + error; - } - if (message.from != null && message.hasOwnProperty("from")) { - if (!Array.isArray(message.from)) - return "from: array expected"; - for (var i = 0; i < message.from.length; ++i) { - var error = $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.verify(message.from[i]); - if (error) - return "from." + error; - } - } - if (message.where != null && message.hasOwnProperty("where")) { - var error = $root.google.firestore.v1beta1.StructuredQuery.Filter.verify(message.where); - if (error) - return "where." + error; - } - if (message.orderBy != null && message.hasOwnProperty("orderBy")) { - if (!Array.isArray(message.orderBy)) - return "orderBy: array expected"; - for (var i = 0; i < message.orderBy.length; ++i) { - var error = $root.google.firestore.v1beta1.StructuredQuery.Order.verify(message.orderBy[i]); - if (error) - return "orderBy." + error; - } - } - if (message.startAt != null && message.hasOwnProperty("startAt")) { - var error = $root.google.firestore.v1beta1.Cursor.verify(message.startAt); - if (error) - return "startAt." + error; - } - if (message.endAt != null && message.hasOwnProperty("endAt")) { - var error = $root.google.firestore.v1beta1.Cursor.verify(message.endAt); - if (error) - return "endAt." + error; - } - if (message.offset != null && message.hasOwnProperty("offset")) - if (!$util.isInteger(message.offset)) - return "offset: integer expected"; - if (message.limit != null && message.hasOwnProperty("limit")) { - var error = $root.google.protobuf.Int32Value.verify(message.limit); - if (error) - return "limit." + error; - } - return null; - }; - - /** - * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery} StructuredQuery - */ - StructuredQuery.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery(); - if (object.select != null) { - if (typeof object.select !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.select: object expected"); - message.select = $root.google.firestore.v1beta1.StructuredQuery.Projection.fromObject(object.select); - } - if (object.from) { - if (!Array.isArray(object.from)) - throw TypeError(".google.firestore.v1beta1.StructuredQuery.from: array expected"); - message.from = []; - for (var i = 0; i < object.from.length; ++i) { - if (typeof object.from[i] !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.from: object expected"); - message.from[i] = $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.fromObject(object.from[i]); - } - } - if (object.where != null) { - if (typeof object.where !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.where: object expected"); - message.where = $root.google.firestore.v1beta1.StructuredQuery.Filter.fromObject(object.where); - } - if (object.orderBy) { - if (!Array.isArray(object.orderBy)) - throw TypeError(".google.firestore.v1beta1.StructuredQuery.orderBy: array expected"); - message.orderBy = []; - for (var i = 0; i < object.orderBy.length; ++i) { - if (typeof object.orderBy[i] !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.orderBy: object expected"); - message.orderBy[i] = $root.google.firestore.v1beta1.StructuredQuery.Order.fromObject(object.orderBy[i]); - } - } - if (object.startAt != null) { - if (typeof object.startAt !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.startAt: object expected"); - message.startAt = $root.google.firestore.v1beta1.Cursor.fromObject(object.startAt); - } - if (object.endAt != null) { - if (typeof object.endAt !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.endAt: object expected"); - message.endAt = $root.google.firestore.v1beta1.Cursor.fromObject(object.endAt); - } - if (object.offset != null) - message.offset = object.offset | 0; - if (object.limit != null) { - if (typeof object.limit !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.limit: object expected"); - message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); - } - return message; - }; - - /** - * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery - * @static - * @param {google.firestore.v1beta1.StructuredQuery} message StructuredQuery - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - StructuredQuery.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.from = []; - object.orderBy = []; - } - if (options.defaults) { - object.select = null; - object.where = null; - object.limit = null; - object.offset = 0; - object.startAt = null; - object.endAt = null; - } - if (message.select != null && message.hasOwnProperty("select")) - object.select = $root.google.firestore.v1beta1.StructuredQuery.Projection.toObject(message.select, options); - if (message.from && message.from.length) { - object.from = []; - for (var j = 0; j < message.from.length; ++j) - object.from[j] = $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector.toObject(message.from[j], options); - } - if (message.where != null && message.hasOwnProperty("where")) - object.where = $root.google.firestore.v1beta1.StructuredQuery.Filter.toObject(message.where, options); - if (message.orderBy && message.orderBy.length) { - object.orderBy = []; - for (var j = 0; j < message.orderBy.length; ++j) - object.orderBy[j] = $root.google.firestore.v1beta1.StructuredQuery.Order.toObject(message.orderBy[j], options); - } - if (message.limit != null && message.hasOwnProperty("limit")) - object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); - if (message.offset != null && message.hasOwnProperty("offset")) - object.offset = message.offset; - if (message.startAt != null && message.hasOwnProperty("startAt")) - object.startAt = $root.google.firestore.v1beta1.Cursor.toObject(message.startAt, options); - if (message.endAt != null && message.hasOwnProperty("endAt")) - object.endAt = $root.google.firestore.v1beta1.Cursor.toObject(message.endAt, options); - return object; - }; - - /** - * Converts this StructuredQuery to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery - * @instance - * @returns {Object.} JSON object - */ - StructuredQuery.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - StructuredQuery.CollectionSelector = (function() { - - /** - * Properties of a CollectionSelector. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface ICollectionSelector - * @property {string|null} [collectionId] CollectionSelector collectionId - * @property {boolean|null} [allDescendants] CollectionSelector allDescendants - */ - - /** - * Constructs a new CollectionSelector. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents a CollectionSelector. - * @implements ICollectionSelector - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.ICollectionSelector=} [properties] Properties to set - */ - function CollectionSelector(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CollectionSelector collectionId. - * @member {string} collectionId - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @instance - */ - CollectionSelector.prototype.collectionId = ""; - - /** - * CollectionSelector allDescendants. - * @member {boolean} allDescendants - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @instance - */ - CollectionSelector.prototype.allDescendants = false; - - /** - * Creates a new CollectionSelector instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {google.firestore.v1beta1.StructuredQuery.ICollectionSelector=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.CollectionSelector} CollectionSelector instance - */ - CollectionSelector.create = function create(properties) { - return new CollectionSelector(properties); - }; - - /** - * Encodes the specified CollectionSelector message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CollectionSelector.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {google.firestore.v1beta1.StructuredQuery.ICollectionSelector} message CollectionSelector message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CollectionSelector.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.collectionId); - if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) - writer.uint32(/* id 3, wireType 0 =*/24).bool(message.allDescendants); - return writer; - }; - - /** - * Encodes the specified CollectionSelector message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CollectionSelector.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {google.firestore.v1beta1.StructuredQuery.ICollectionSelector} message CollectionSelector message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CollectionSelector.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a CollectionSelector message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.CollectionSelector} CollectionSelector - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CollectionSelector.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.collectionId = reader.string(); - break; - case 3: - message.allDescendants = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a CollectionSelector message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.CollectionSelector} CollectionSelector - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CollectionSelector.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a CollectionSelector message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - CollectionSelector.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - if (!$util.isString(message.collectionId)) - return "collectionId: string expected"; - if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) - if (typeof message.allDescendants !== "boolean") - return "allDescendants: boolean expected"; - return null; - }; - - /** - * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.CollectionSelector} CollectionSelector - */ - CollectionSelector.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.CollectionSelector(); - if (object.collectionId != null) - message.collectionId = String(object.collectionId); - if (object.allDescendants != null) - message.allDescendants = Boolean(object.allDescendants); - return message; - }; - - /** - * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @static - * @param {google.firestore.v1beta1.StructuredQuery.CollectionSelector} message CollectionSelector - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CollectionSelector.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.collectionId = ""; - object.allDescendants = false; - } - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - object.collectionId = message.collectionId; - if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) - object.allDescendants = message.allDescendants; - return object; - }; - - /** - * Converts this CollectionSelector to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.CollectionSelector - * @instance - * @returns {Object.} JSON object - */ - CollectionSelector.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return CollectionSelector; - })(); - - StructuredQuery.Filter = (function() { - - /** - * Properties of a Filter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface IFilter - * @property {google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null} [compositeFilter] Filter compositeFilter - * @property {google.firestore.v1beta1.StructuredQuery.IFieldFilter|null} [fieldFilter] Filter fieldFilter - * @property {google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null} [unaryFilter] Filter unaryFilter - */ - - /** - * Constructs a new Filter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents a Filter. - * @implements IFilter - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.IFilter=} [properties] Properties to set - */ - function Filter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Filter compositeFilter. - * @member {google.firestore.v1beta1.StructuredQuery.ICompositeFilter|null|undefined} compositeFilter - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @instance - */ - Filter.prototype.compositeFilter = null; - - /** - * Filter fieldFilter. - * @member {google.firestore.v1beta1.StructuredQuery.IFieldFilter|null|undefined} fieldFilter - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @instance - */ - Filter.prototype.fieldFilter = null; - - /** - * Filter unaryFilter. - * @member {google.firestore.v1beta1.StructuredQuery.IUnaryFilter|null|undefined} unaryFilter - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @instance - */ - Filter.prototype.unaryFilter = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Filter filterType. - * @member {"compositeFilter"|"fieldFilter"|"unaryFilter"|undefined} filterType - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @instance - */ - Object.defineProperty(Filter.prototype, "filterType", { - get: $util.oneOfGetter($oneOfFields = ["compositeFilter", "fieldFilter", "unaryFilter"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new Filter instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFilter=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.Filter} Filter instance - */ - Filter.create = function create(properties) { - return new Filter(properties); - }; - - /** - * Encodes the specified Filter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Filter.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFilter} message Filter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Filter.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) - $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.encode(message.compositeFilter, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) - $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.encode(message.fieldFilter, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) - $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.encode(message.unaryFilter, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Filter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Filter.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFilter} message Filter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Filter.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Filter message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.Filter} Filter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Filter.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.Filter(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.compositeFilter = $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.decode(reader, reader.uint32()); - break; - case 2: - message.fieldFilter = $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.decode(reader, reader.uint32()); - break; - case 3: - message.unaryFilter = $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Filter message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.Filter} Filter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Filter.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Filter message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Filter.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) { - properties.filterType = 1; - { - var error = $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.verify(message.compositeFilter); - if (error) - return "compositeFilter." + error; - } - } - if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) { - if (properties.filterType === 1) - return "filterType: multiple values"; - properties.filterType = 1; - { - var error = $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.verify(message.fieldFilter); - if (error) - return "fieldFilter." + error; - } - } - if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) { - if (properties.filterType === 1) - return "filterType: multiple values"; - properties.filterType = 1; - { - var error = $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.verify(message.unaryFilter); - if (error) - return "unaryFilter." + error; - } - } - return null; - }; - - /** - * Creates a Filter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.Filter} Filter - */ - Filter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.Filter) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.Filter(); - if (object.compositeFilter != null) { - if (typeof object.compositeFilter !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.Filter.compositeFilter: object expected"); - message.compositeFilter = $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.fromObject(object.compositeFilter); - } - if (object.fieldFilter != null) { - if (typeof object.fieldFilter !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.Filter.fieldFilter: object expected"); - message.fieldFilter = $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.fromObject(object.fieldFilter); - } - if (object.unaryFilter != null) { - if (typeof object.unaryFilter !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.Filter.unaryFilter: object expected"); - message.unaryFilter = $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.fromObject(object.unaryFilter); - } - return message; - }; - - /** - * Creates a plain object from a Filter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.Filter} message Filter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Filter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) { - object.compositeFilter = $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.toObject(message.compositeFilter, options); - if (options.oneofs) - object.filterType = "compositeFilter"; - } - if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) { - object.fieldFilter = $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.toObject(message.fieldFilter, options); - if (options.oneofs) - object.filterType = "fieldFilter"; - } - if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) { - object.unaryFilter = $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.toObject(message.unaryFilter, options); - if (options.oneofs) - object.filterType = "unaryFilter"; - } - return object; - }; - - /** - * Converts this Filter to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.Filter - * @instance - * @returns {Object.} JSON object - */ - Filter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Filter; - })(); - - StructuredQuery.CompositeFilter = (function() { - - /** - * Properties of a CompositeFilter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface ICompositeFilter - * @property {google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator|null} [op] CompositeFilter op - * @property {Array.|null} [filters] CompositeFilter filters - */ - - /** - * Constructs a new CompositeFilter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents a CompositeFilter. - * @implements ICompositeFilter - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.ICompositeFilter=} [properties] Properties to set - */ - function CompositeFilter(properties) { - this.filters = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CompositeFilter op. - * @member {google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator} op - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @instance - */ - CompositeFilter.prototype.op = 0; - - /** - * CompositeFilter filters. - * @member {Array.} filters - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @instance - */ - CompositeFilter.prototype.filters = $util.emptyArray; - - /** - * Creates a new CompositeFilter instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.ICompositeFilter=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.CompositeFilter} CompositeFilter instance - */ - CompositeFilter.create = function create(properties) { - return new CompositeFilter(properties); - }; - - /** - * Encodes the specified CompositeFilter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CompositeFilter.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.ICompositeFilter} message CompositeFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CompositeFilter.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.op != null && message.hasOwnProperty("op")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.op); - if (message.filters != null && message.filters.length) - for (var i = 0; i < message.filters.length; ++i) - $root.google.firestore.v1beta1.StructuredQuery.Filter.encode(message.filters[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified CompositeFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.CompositeFilter.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.ICompositeFilter} message CompositeFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CompositeFilter.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a CompositeFilter message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.CompositeFilter} CompositeFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CompositeFilter.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.op = reader.int32(); - break; - case 2: - if (!(message.filters && message.filters.length)) - message.filters = []; - message.filters.push($root.google.firestore.v1beta1.StructuredQuery.Filter.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a CompositeFilter message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.CompositeFilter} CompositeFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CompositeFilter.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a CompositeFilter message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - CompositeFilter.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.op != null && message.hasOwnProperty("op")) - switch (message.op) { - default: - return "op: enum value expected"; - case 0: - case 1: - break; - } - if (message.filters != null && message.hasOwnProperty("filters")) { - if (!Array.isArray(message.filters)) - return "filters: array expected"; - for (var i = 0; i < message.filters.length; ++i) { - var error = $root.google.firestore.v1beta1.StructuredQuery.Filter.verify(message.filters[i]); - if (error) - return "filters." + error; - } - } - return null; - }; - - /** - * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.CompositeFilter} CompositeFilter - */ - CompositeFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter(); - switch (object.op) { - case "OPERATOR_UNSPECIFIED": - case 0: - message.op = 0; - break; - case "AND": - case 1: - message.op = 1; - break; - } - if (object.filters) { - if (!Array.isArray(object.filters)) - throw TypeError(".google.firestore.v1beta1.StructuredQuery.CompositeFilter.filters: array expected"); - message.filters = []; - for (var i = 0; i < object.filters.length; ++i) { - if (typeof object.filters[i] !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.CompositeFilter.filters: object expected"); - message.filters[i] = $root.google.firestore.v1beta1.StructuredQuery.Filter.fromObject(object.filters[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.CompositeFilter} message CompositeFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CompositeFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.filters = []; - if (options.defaults) - object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; - if (message.op != null && message.hasOwnProperty("op")) - object.op = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator[message.op] : message.op; - if (message.filters && message.filters.length) { - object.filters = []; - for (var j = 0; j < message.filters.length; ++j) - object.filters[j] = $root.google.firestore.v1beta1.StructuredQuery.Filter.toObject(message.filters[j], options); - } - return object; - }; - - /** - * Converts this CompositeFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.CompositeFilter - * @instance - * @returns {Object.} JSON object - */ - CompositeFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Operator enum. - * @name google.firestore.v1beta1.StructuredQuery.CompositeFilter.Operator - * @enum {string} - * @property {number} OPERATOR_UNSPECIFIED=0 OPERATOR_UNSPECIFIED value - * @property {number} AND=1 AND value - */ - CompositeFilter.Operator = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = 0; - values[valuesById[1] = "AND"] = 1; - return values; - })(); - - return CompositeFilter; - })(); - - StructuredQuery.FieldFilter = (function() { - - /** - * Properties of a FieldFilter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface IFieldFilter - * @property {google.firestore.v1beta1.StructuredQuery.IFieldReference|null} [field] FieldFilter field - * @property {google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator|null} [op] FieldFilter op - * @property {google.firestore.v1beta1.IValue|null} [value] FieldFilter value - */ - - /** - * Constructs a new FieldFilter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents a FieldFilter. - * @implements IFieldFilter - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.IFieldFilter=} [properties] Properties to set - */ - function FieldFilter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldFilter field. - * @member {google.firestore.v1beta1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @instance - */ - FieldFilter.prototype.field = null; - - /** - * FieldFilter op. - * @member {google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator} op - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @instance - */ - FieldFilter.prototype.op = 0; - - /** - * FieldFilter value. - * @member {google.firestore.v1beta1.IValue|null|undefined} value - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @instance - */ - FieldFilter.prototype.value = null; - - /** - * Creates a new FieldFilter instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFieldFilter=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.FieldFilter} FieldFilter instance - */ - FieldFilter.create = function create(properties) { - return new FieldFilter(properties); - }; - - /** - * Encodes the specified FieldFilter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldFilter.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFieldFilter} message FieldFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldFilter.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.field != null && message.hasOwnProperty("field")) - $root.google.firestore.v1beta1.StructuredQuery.FieldReference.encode(message.field, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.op != null && message.hasOwnProperty("op")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.op); - if (message.value != null && message.hasOwnProperty("value")) - $root.google.firestore.v1beta1.Value.encode(message.value, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified FieldFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldFilter.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFieldFilter} message FieldFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldFilter.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FieldFilter message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.FieldFilter} FieldFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldFilter.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.FieldFilter(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.decode(reader, reader.uint32()); - break; - case 2: - message.op = reader.int32(); - break; - case 3: - message.value = $root.google.firestore.v1beta1.Value.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FieldFilter message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.FieldFilter} FieldFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldFilter.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FieldFilter message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FieldFilter.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.field != null && message.hasOwnProperty("field")) { - var error = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.verify(message.field); - if (error) - return "field." + error; - } - if (message.op != null && message.hasOwnProperty("op")) - switch (message.op) { - default: - return "op: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 7: - break; - } - if (message.value != null && message.hasOwnProperty("value")) { - var error = $root.google.firestore.v1beta1.Value.verify(message.value); - if (error) - return "value." + error; - } - return null; - }; - - /** - * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.FieldFilter} FieldFilter - */ - FieldFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.FieldFilter) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.FieldFilter(); - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.FieldFilter.field: object expected"); - message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.field); - } - switch (object.op) { - case "OPERATOR_UNSPECIFIED": - case 0: - message.op = 0; - break; - case "LESS_THAN": - case 1: - message.op = 1; - break; - case "LESS_THAN_OR_EQUAL": - case 2: - message.op = 2; - break; - case "GREATER_THAN": - case 3: - message.op = 3; - break; - case "GREATER_THAN_OR_EQUAL": - case 4: - message.op = 4; - break; - case "EQUAL": - case 5: - message.op = 5; - break; - case "ARRAY_CONTAINS": - case 7: - message.op = 7; - break; - } - if (object.value != null) { - if (typeof object.value !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.FieldFilter.value: object expected"); - message.value = $root.google.firestore.v1beta1.Value.fromObject(object.value); - } - return message; - }; - - /** - * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.FieldFilter} message FieldFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.field = null; - object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; - object.value = null; - } - if (message.field != null && message.hasOwnProperty("field")) - object.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.field, options); - if (message.op != null && message.hasOwnProperty("op")) - object.op = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator[message.op] : message.op; - if (message.value != null && message.hasOwnProperty("value")) - object.value = $root.google.firestore.v1beta1.Value.toObject(message.value, options); - return object; - }; - - /** - * Converts this FieldFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.FieldFilter - * @instance - * @returns {Object.} JSON object - */ - FieldFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Operator enum. - * @name google.firestore.v1beta1.StructuredQuery.FieldFilter.Operator - * @enum {string} - * @property {number} OPERATOR_UNSPECIFIED=0 OPERATOR_UNSPECIFIED value - * @property {number} LESS_THAN=1 LESS_THAN value - * @property {number} LESS_THAN_OR_EQUAL=2 LESS_THAN_OR_EQUAL value - * @property {number} GREATER_THAN=3 GREATER_THAN value - * @property {number} GREATER_THAN_OR_EQUAL=4 GREATER_THAN_OR_EQUAL value - * @property {number} EQUAL=5 EQUAL value - * @property {number} ARRAY_CONTAINS=7 ARRAY_CONTAINS value - */ - FieldFilter.Operator = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = 0; - values[valuesById[1] = "LESS_THAN"] = 1; - values[valuesById[2] = "LESS_THAN_OR_EQUAL"] = 2; - values[valuesById[3] = "GREATER_THAN"] = 3; - values[valuesById[4] = "GREATER_THAN_OR_EQUAL"] = 4; - values[valuesById[5] = "EQUAL"] = 5; - values[valuesById[7] = "ARRAY_CONTAINS"] = 7; - return values; - })(); - - return FieldFilter; - })(); - - StructuredQuery.UnaryFilter = (function() { - - /** - * Properties of an UnaryFilter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface IUnaryFilter - * @property {google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator|null} [op] UnaryFilter op - * @property {google.firestore.v1beta1.StructuredQuery.IFieldReference|null} [field] UnaryFilter field - */ - - /** - * Constructs a new UnaryFilter. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents an UnaryFilter. - * @implements IUnaryFilter - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.IUnaryFilter=} [properties] Properties to set - */ - function UnaryFilter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * UnaryFilter op. - * @member {google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator} op - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @instance - */ - UnaryFilter.prototype.op = 0; - - /** - * UnaryFilter field. - * @member {google.firestore.v1beta1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @instance - */ - UnaryFilter.prototype.field = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * UnaryFilter operandType. - * @member {"field"|undefined} operandType - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @instance - */ - Object.defineProperty(UnaryFilter.prototype, "operandType", { - get: $util.oneOfGetter($oneOfFields = ["field"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new UnaryFilter instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IUnaryFilter=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.UnaryFilter} UnaryFilter instance - */ - UnaryFilter.create = function create(properties) { - return new UnaryFilter(properties); - }; - - /** - * Encodes the specified UnaryFilter message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.UnaryFilter.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IUnaryFilter} message UnaryFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UnaryFilter.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.op != null && message.hasOwnProperty("op")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.op); - if (message.field != null && message.hasOwnProperty("field")) - $root.google.firestore.v1beta1.StructuredQuery.FieldReference.encode(message.field, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified UnaryFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.UnaryFilter.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IUnaryFilter} message UnaryFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UnaryFilter.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an UnaryFilter message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.UnaryFilter} UnaryFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UnaryFilter.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.op = reader.int32(); - break; - case 2: - message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an UnaryFilter message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.UnaryFilter} UnaryFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UnaryFilter.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an UnaryFilter message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - UnaryFilter.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.op != null && message.hasOwnProperty("op")) - switch (message.op) { - default: - return "op: enum value expected"; - case 0: - case 2: - case 3: - break; - } - if (message.field != null && message.hasOwnProperty("field")) { - properties.operandType = 1; - { - var error = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.verify(message.field); - if (error) - return "field." + error; - } - } - return null; - }; - - /** - * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.UnaryFilter} UnaryFilter - */ - UnaryFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter(); - switch (object.op) { - case "OPERATOR_UNSPECIFIED": - case 0: - message.op = 0; - break; - case "IS_NAN": - case 2: - message.op = 2; - break; - case "IS_NULL": - case 3: - message.op = 3; - break; - } - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.UnaryFilter.field: object expected"); - message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.field); - } - return message; - }; - - /** - * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @static - * @param {google.firestore.v1beta1.StructuredQuery.UnaryFilter} message UnaryFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UnaryFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; - if (message.op != null && message.hasOwnProperty("op")) - object.op = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator[message.op] : message.op; - if (message.field != null && message.hasOwnProperty("field")) { - object.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.field, options); - if (options.oneofs) - object.operandType = "field"; - } - return object; - }; - - /** - * Converts this UnaryFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.UnaryFilter - * @instance - * @returns {Object.} JSON object - */ - UnaryFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Operator enum. - * @name google.firestore.v1beta1.StructuredQuery.UnaryFilter.Operator - * @enum {string} - * @property {number} OPERATOR_UNSPECIFIED=0 OPERATOR_UNSPECIFIED value - * @property {number} IS_NAN=2 IS_NAN value - * @property {number} IS_NULL=3 IS_NULL value - */ - UnaryFilter.Operator = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = 0; - values[valuesById[2] = "IS_NAN"] = 2; - values[valuesById[3] = "IS_NULL"] = 3; - return values; - })(); - - return UnaryFilter; - })(); - - StructuredQuery.Order = (function() { - - /** - * Properties of an Order. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface IOrder - * @property {google.firestore.v1beta1.StructuredQuery.IFieldReference|null} [field] Order field - * @property {google.firestore.v1beta1.StructuredQuery.Direction|null} [direction] Order direction - */ - - /** - * Constructs a new Order. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents an Order. - * @implements IOrder - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.IOrder=} [properties] Properties to set - */ - function Order(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Order field. - * @member {google.firestore.v1beta1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @instance - */ - Order.prototype.field = null; - - /** - * Order direction. - * @member {google.firestore.v1beta1.StructuredQuery.Direction} direction - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @instance - */ - Order.prototype.direction = 0; - - /** - * Creates a new Order instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IOrder=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.Order} Order instance - */ - Order.create = function create(properties) { - return new Order(properties); - }; - - /** - * Encodes the specified Order message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Order.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IOrder} message Order message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Order.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.field != null && message.hasOwnProperty("field")) - $root.google.firestore.v1beta1.StructuredQuery.FieldReference.encode(message.field, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.direction != null && message.hasOwnProperty("direction")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.direction); - return writer; - }; - - /** - * Encodes the specified Order message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Order.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IOrder} message Order message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Order.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an Order message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.Order} Order - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Order.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.Order(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.decode(reader, reader.uint32()); - break; - case 2: - message.direction = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an Order message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.Order} Order - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Order.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an Order message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Order.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.field != null && message.hasOwnProperty("field")) { - var error = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.verify(message.field); - if (error) - return "field." + error; - } - if (message.direction != null && message.hasOwnProperty("direction")) - switch (message.direction) { - default: - return "direction: enum value expected"; - case 0: - case 1: - case 2: - break; - } - return null; - }; - - /** - * Creates an Order message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.Order} Order - */ - Order.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.Order) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.Order(); - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.Order.field: object expected"); - message.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.field); - } - switch (object.direction) { - case "DIRECTION_UNSPECIFIED": - case 0: - message.direction = 0; - break; - case "ASCENDING": - case 1: - message.direction = 1; - break; - case "DESCENDING": - case 2: - message.direction = 2; - break; - } - return message; - }; - - /** - * Creates a plain object from an Order message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @static - * @param {google.firestore.v1beta1.StructuredQuery.Order} message Order - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Order.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.field = null; - object.direction = options.enums === String ? "DIRECTION_UNSPECIFIED" : 0; - } - if (message.field != null && message.hasOwnProperty("field")) - object.field = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.field, options); - if (message.direction != null && message.hasOwnProperty("direction")) - object.direction = options.enums === String ? $root.google.firestore.v1beta1.StructuredQuery.Direction[message.direction] : message.direction; - return object; - }; - - /** - * Converts this Order to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.Order - * @instance - * @returns {Object.} JSON object - */ - Order.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Order; - })(); - - StructuredQuery.FieldReference = (function() { - - /** - * Properties of a FieldReference. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface IFieldReference - * @property {string|null} [fieldPath] FieldReference fieldPath - */ - - /** - * Constructs a new FieldReference. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents a FieldReference. - * @implements IFieldReference - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.IFieldReference=} [properties] Properties to set - */ - function FieldReference(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldReference fieldPath. - * @member {string} fieldPath - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @instance - */ - FieldReference.prototype.fieldPath = ""; - - /** - * Creates a new FieldReference instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFieldReference=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.FieldReference} FieldReference instance - */ - FieldReference.create = function create(properties) { - return new FieldReference(properties); - }; - - /** - * Encodes the specified FieldReference message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldReference.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFieldReference} message FieldReference message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldReference.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.fieldPath); - return writer; - }; - - /** - * Encodes the specified FieldReference message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.FieldReference.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IFieldReference} message FieldReference message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldReference.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FieldReference message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.FieldReference} FieldReference - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldReference.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.FieldReference(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.fieldPath = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FieldReference message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.FieldReference} FieldReference - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldReference.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FieldReference message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FieldReference.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - if (!$util.isString(message.fieldPath)) - return "fieldPath: string expected"; - return null; - }; - - /** - * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.FieldReference} FieldReference - */ - FieldReference.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.FieldReference) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.FieldReference(); - if (object.fieldPath != null) - message.fieldPath = String(object.fieldPath); - return message; - }; - - /** - * Creates a plain object from a FieldReference message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @static - * @param {google.firestore.v1beta1.StructuredQuery.FieldReference} message FieldReference - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldReference.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.fieldPath = ""; - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - object.fieldPath = message.fieldPath; - return object; - }; - - /** - * Converts this FieldReference to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.FieldReference - * @instance - * @returns {Object.} JSON object - */ - FieldReference.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return FieldReference; - })(); - - StructuredQuery.Projection = (function() { - - /** - * Properties of a Projection. - * @memberof google.firestore.v1beta1.StructuredQuery - * @interface IProjection - * @property {Array.|null} [fields] Projection fields - */ - - /** - * Constructs a new Projection. - * @memberof google.firestore.v1beta1.StructuredQuery - * @classdesc Represents a Projection. - * @implements IProjection - * @constructor - * @param {google.firestore.v1beta1.StructuredQuery.IProjection=} [properties] Properties to set - */ - function Projection(properties) { - this.fields = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Projection fields. - * @member {Array.} fields - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @instance - */ - Projection.prototype.fields = $util.emptyArray; - - /** - * Creates a new Projection instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IProjection=} [properties] Properties to set - * @returns {google.firestore.v1beta1.StructuredQuery.Projection} Projection instance - */ - Projection.create = function create(properties) { - return new Projection(properties); - }; - - /** - * Encodes the specified Projection message. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Projection.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IProjection} message Projection message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Projection.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.fields != null && message.fields.length) - for (var i = 0; i < message.fields.length; ++i) - $root.google.firestore.v1beta1.StructuredQuery.FieldReference.encode(message.fields[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Projection message, length delimited. Does not implicitly {@link google.firestore.v1beta1.StructuredQuery.Projection.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {google.firestore.v1beta1.StructuredQuery.IProjection} message Projection message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Projection.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Projection message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.StructuredQuery.Projection} Projection - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Projection.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.StructuredQuery.Projection(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - if (!(message.fields && message.fields.length)) - message.fields = []; - message.fields.push($root.google.firestore.v1beta1.StructuredQuery.FieldReference.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Projection message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.StructuredQuery.Projection} Projection - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Projection.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Projection message. - * @function verify - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Projection.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.fields != null && message.hasOwnProperty("fields")) { - if (!Array.isArray(message.fields)) - return "fields: array expected"; - for (var i = 0; i < message.fields.length; ++i) { - var error = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.verify(message.fields[i]); - if (error) - return "fields." + error; - } - } - return null; - }; - - /** - * Creates a Projection message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.StructuredQuery.Projection} Projection - */ - Projection.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.StructuredQuery.Projection) - return object; - var message = new $root.google.firestore.v1beta1.StructuredQuery.Projection(); - if (object.fields) { - if (!Array.isArray(object.fields)) - throw TypeError(".google.firestore.v1beta1.StructuredQuery.Projection.fields: array expected"); - message.fields = []; - for (var i = 0; i < object.fields.length; ++i) { - if (typeof object.fields[i] !== "object") - throw TypeError(".google.firestore.v1beta1.StructuredQuery.Projection.fields: object expected"); - message.fields[i] = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.fromObject(object.fields[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a Projection message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @static - * @param {google.firestore.v1beta1.StructuredQuery.Projection} message Projection - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Projection.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.fields = []; - if (message.fields && message.fields.length) { - object.fields = []; - for (var j = 0; j < message.fields.length; ++j) - object.fields[j] = $root.google.firestore.v1beta1.StructuredQuery.FieldReference.toObject(message.fields[j], options); - } - return object; - }; - - /** - * Converts this Projection to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.StructuredQuery.Projection - * @instance - * @returns {Object.} JSON object - */ - Projection.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Projection; - })(); - - /** - * Direction enum. - * @name google.firestore.v1beta1.StructuredQuery.Direction - * @enum {string} - * @property {number} DIRECTION_UNSPECIFIED=0 DIRECTION_UNSPECIFIED value - * @property {number} ASCENDING=1 ASCENDING value - * @property {number} DESCENDING=2 DESCENDING value - */ - StructuredQuery.Direction = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "DIRECTION_UNSPECIFIED"] = 0; - values[valuesById[1] = "ASCENDING"] = 1; - values[valuesById[2] = "DESCENDING"] = 2; - return values; - })(); - - return StructuredQuery; - })(); - - v1beta1.Cursor = (function() { - - /** - * Properties of a Cursor. - * @memberof google.firestore.v1beta1 - * @interface ICursor - * @property {Array.|null} [values] Cursor values - * @property {boolean|null} [before] Cursor before - */ - - /** - * Constructs a new Cursor. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Cursor. - * @implements ICursor - * @constructor - * @param {google.firestore.v1beta1.ICursor=} [properties] Properties to set - */ - function Cursor(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Cursor values. - * @member {Array.} values - * @memberof google.firestore.v1beta1.Cursor - * @instance - */ - Cursor.prototype.values = $util.emptyArray; - - /** - * Cursor before. - * @member {boolean} before - * @memberof google.firestore.v1beta1.Cursor - * @instance - */ - Cursor.prototype.before = false; - - /** - * Creates a new Cursor instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {google.firestore.v1beta1.ICursor=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Cursor} Cursor instance - */ - Cursor.create = function create(properties) { - return new Cursor(properties); - }; - - /** - * Encodes the specified Cursor message. Does not implicitly {@link google.firestore.v1beta1.Cursor.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {google.firestore.v1beta1.ICursor} message Cursor message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Cursor.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.values != null && message.values.length) - for (var i = 0; i < message.values.length; ++i) - $root.google.firestore.v1beta1.Value.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.before != null && message.hasOwnProperty("before")) - writer.uint32(/* id 2, wireType 0 =*/16).bool(message.before); - return writer; - }; - - /** - * Encodes the specified Cursor message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Cursor.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {google.firestore.v1beta1.ICursor} message Cursor message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Cursor.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Cursor message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Cursor} Cursor - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Cursor.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Cursor(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.values && message.values.length)) - message.values = []; - message.values.push($root.google.firestore.v1beta1.Value.decode(reader, reader.uint32())); - break; - case 2: - message.before = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Cursor message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Cursor} Cursor - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Cursor.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Cursor message. - * @function verify - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Cursor.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.values != null && message.hasOwnProperty("values")) { - if (!Array.isArray(message.values)) - return "values: array expected"; - for (var i = 0; i < message.values.length; ++i) { - var error = $root.google.firestore.v1beta1.Value.verify(message.values[i]); - if (error) - return "values." + error; - } - } - if (message.before != null && message.hasOwnProperty("before")) - if (typeof message.before !== "boolean") - return "before: boolean expected"; - return null; - }; - - /** - * Creates a Cursor message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Cursor} Cursor - */ - Cursor.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Cursor) - return object; - var message = new $root.google.firestore.v1beta1.Cursor(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".google.firestore.v1beta1.Cursor.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".google.firestore.v1beta1.Cursor.values: object expected"); - message.values[i] = $root.google.firestore.v1beta1.Value.fromObject(object.values[i]); - } - } - if (object.before != null) - message.before = Boolean(object.before); - return message; - }; - - /** - * Creates a plain object from a Cursor message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Cursor - * @static - * @param {google.firestore.v1beta1.Cursor} message Cursor - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Cursor.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (options.defaults) - object.before = false; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.google.firestore.v1beta1.Value.toObject(message.values[j], options); - } - if (message.before != null && message.hasOwnProperty("before")) - object.before = message.before; - return object; - }; - - /** - * Converts this Cursor to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Cursor - * @instance - * @returns {Object.} JSON object - */ - Cursor.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Cursor; - })(); - - v1beta1.Write = (function() { - - /** - * Properties of a Write. - * @memberof google.firestore.v1beta1 - * @interface IWrite - * @property {google.firestore.v1beta1.IDocument|null} [update] Write update - * @property {string|null} ["delete"] Write delete - * @property {google.firestore.v1beta1.IDocumentTransform|null} [transform] Write transform - * @property {google.firestore.v1beta1.IDocumentMask|null} [updateMask] Write updateMask - * @property {google.firestore.v1beta1.IPrecondition|null} [currentDocument] Write currentDocument - */ - - /** - * Constructs a new Write. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a Write. - * @implements IWrite - * @constructor - * @param {google.firestore.v1beta1.IWrite=} [properties] Properties to set - */ - function Write(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Write update. - * @member {google.firestore.v1beta1.IDocument|null|undefined} update - * @memberof google.firestore.v1beta1.Write - * @instance - */ - Write.prototype.update = null; - - /** - * Write delete. - * @member {string} delete - * @memberof google.firestore.v1beta1.Write - * @instance - */ - Write.prototype["delete"] = ""; - - /** - * Write transform. - * @member {google.firestore.v1beta1.IDocumentTransform|null|undefined} transform - * @memberof google.firestore.v1beta1.Write - * @instance - */ - Write.prototype.transform = null; - - /** - * Write updateMask. - * @member {google.firestore.v1beta1.IDocumentMask|null|undefined} updateMask - * @memberof google.firestore.v1beta1.Write - * @instance - */ - Write.prototype.updateMask = null; - - /** - * Write currentDocument. - * @member {google.firestore.v1beta1.IPrecondition|null|undefined} currentDocument - * @memberof google.firestore.v1beta1.Write - * @instance - */ - Write.prototype.currentDocument = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Write operation. - * @member {"update"|"delete"|"transform"|undefined} operation - * @memberof google.firestore.v1beta1.Write - * @instance - */ - Object.defineProperty(Write.prototype, "operation", { - get: $util.oneOfGetter($oneOfFields = ["update", "delete", "transform"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new Write instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.Write - * @static - * @param {google.firestore.v1beta1.IWrite=} [properties] Properties to set - * @returns {google.firestore.v1beta1.Write} Write instance - */ - Write.create = function create(properties) { - return new Write(properties); - }; - - /** - * Encodes the specified Write message. Does not implicitly {@link google.firestore.v1beta1.Write.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.Write - * @static - * @param {google.firestore.v1beta1.IWrite} message Write message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Write.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.update != null && message.hasOwnProperty("update")) - $root.google.firestore.v1beta1.Document.encode(message.update, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message["delete"] != null && message.hasOwnProperty("delete")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message["delete"]); - if (message.updateMask != null && message.hasOwnProperty("updateMask")) - $root.google.firestore.v1beta1.DocumentMask.encode(message.updateMask, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - $root.google.firestore.v1beta1.Precondition.encode(message.currentDocument, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.transform != null && message.hasOwnProperty("transform")) - $root.google.firestore.v1beta1.DocumentTransform.encode(message.transform, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Write message, length delimited. Does not implicitly {@link google.firestore.v1beta1.Write.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.Write - * @static - * @param {google.firestore.v1beta1.IWrite} message Write message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Write.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Write message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.Write - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.Write} Write - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Write.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.Write(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.update = $root.google.firestore.v1beta1.Document.decode(reader, reader.uint32()); - break; - case 2: - message["delete"] = reader.string(); - break; - case 6: - message.transform = $root.google.firestore.v1beta1.DocumentTransform.decode(reader, reader.uint32()); - break; - case 3: - message.updateMask = $root.google.firestore.v1beta1.DocumentMask.decode(reader, reader.uint32()); - break; - case 4: - message.currentDocument = $root.google.firestore.v1beta1.Precondition.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Write message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.Write - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.Write} Write - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Write.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Write message. - * @function verify - * @memberof google.firestore.v1beta1.Write - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Write.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.update != null && message.hasOwnProperty("update")) { - properties.operation = 1; - { - var error = $root.google.firestore.v1beta1.Document.verify(message.update); - if (error) - return "update." + error; - } - } - if (message["delete"] != null && message.hasOwnProperty("delete")) { - if (properties.operation === 1) - return "operation: multiple values"; - properties.operation = 1; - if (!$util.isString(message["delete"])) - return "delete: string expected"; - } - if (message.transform != null && message.hasOwnProperty("transform")) { - if (properties.operation === 1) - return "operation: multiple values"; - properties.operation = 1; - { - var error = $root.google.firestore.v1beta1.DocumentTransform.verify(message.transform); - if (error) - return "transform." + error; - } - } - if (message.updateMask != null && message.hasOwnProperty("updateMask")) { - var error = $root.google.firestore.v1beta1.DocumentMask.verify(message.updateMask); - if (error) - return "updateMask." + error; - } - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) { - var error = $root.google.firestore.v1beta1.Precondition.verify(message.currentDocument); - if (error) - return "currentDocument." + error; - } - return null; - }; - - /** - * Creates a Write message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.Write - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.Write} Write - */ - Write.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.Write) - return object; - var message = new $root.google.firestore.v1beta1.Write(); - if (object.update != null) { - if (typeof object.update !== "object") - throw TypeError(".google.firestore.v1beta1.Write.update: object expected"); - message.update = $root.google.firestore.v1beta1.Document.fromObject(object.update); - } - if (object["delete"] != null) - message["delete"] = String(object["delete"]); - if (object.transform != null) { - if (typeof object.transform !== "object") - throw TypeError(".google.firestore.v1beta1.Write.transform: object expected"); - message.transform = $root.google.firestore.v1beta1.DocumentTransform.fromObject(object.transform); - } - if (object.updateMask != null) { - if (typeof object.updateMask !== "object") - throw TypeError(".google.firestore.v1beta1.Write.updateMask: object expected"); - message.updateMask = $root.google.firestore.v1beta1.DocumentMask.fromObject(object.updateMask); - } - if (object.currentDocument != null) { - if (typeof object.currentDocument !== "object") - throw TypeError(".google.firestore.v1beta1.Write.currentDocument: object expected"); - message.currentDocument = $root.google.firestore.v1beta1.Precondition.fromObject(object.currentDocument); - } - return message; - }; - - /** - * Creates a plain object from a Write message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.Write - * @static - * @param {google.firestore.v1beta1.Write} message Write - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Write.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.updateMask = null; - object.currentDocument = null; - } - if (message.update != null && message.hasOwnProperty("update")) { - object.update = $root.google.firestore.v1beta1.Document.toObject(message.update, options); - if (options.oneofs) - object.operation = "update"; - } - if (message["delete"] != null && message.hasOwnProperty("delete")) { - object["delete"] = message["delete"]; - if (options.oneofs) - object.operation = "delete"; - } - if (message.updateMask != null && message.hasOwnProperty("updateMask")) - object.updateMask = $root.google.firestore.v1beta1.DocumentMask.toObject(message.updateMask, options); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - object.currentDocument = $root.google.firestore.v1beta1.Precondition.toObject(message.currentDocument, options); - if (message.transform != null && message.hasOwnProperty("transform")) { - object.transform = $root.google.firestore.v1beta1.DocumentTransform.toObject(message.transform, options); - if (options.oneofs) - object.operation = "transform"; - } - return object; - }; - - /** - * Converts this Write to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.Write - * @instance - * @returns {Object.} JSON object - */ - Write.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Write; - })(); - - v1beta1.DocumentTransform = (function() { - - /** - * Properties of a DocumentTransform. - * @memberof google.firestore.v1beta1 - * @interface IDocumentTransform - * @property {string|null} [document] DocumentTransform document - * @property {Array.|null} [fieldTransforms] DocumentTransform fieldTransforms - */ - - /** - * Constructs a new DocumentTransform. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a DocumentTransform. - * @implements IDocumentTransform - * @constructor - * @param {google.firestore.v1beta1.IDocumentTransform=} [properties] Properties to set - */ - function DocumentTransform(properties) { - this.fieldTransforms = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DocumentTransform document. - * @member {string} document - * @memberof google.firestore.v1beta1.DocumentTransform - * @instance - */ - DocumentTransform.prototype.document = ""; - - /** - * DocumentTransform fieldTransforms. - * @member {Array.} fieldTransforms - * @memberof google.firestore.v1beta1.DocumentTransform - * @instance - */ - DocumentTransform.prototype.fieldTransforms = $util.emptyArray; - - /** - * Creates a new DocumentTransform instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {google.firestore.v1beta1.IDocumentTransform=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DocumentTransform} DocumentTransform instance - */ - DocumentTransform.create = function create(properties) { - return new DocumentTransform(properties); - }; - - /** - * Encodes the specified DocumentTransform message. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {google.firestore.v1beta1.IDocumentTransform} message DocumentTransform message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentTransform.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.document != null && message.hasOwnProperty("document")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.document); - if (message.fieldTransforms != null && message.fieldTransforms.length) - for (var i = 0; i < message.fieldTransforms.length; ++i) - $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.encode(message.fieldTransforms[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified DocumentTransform message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {google.firestore.v1beta1.IDocumentTransform} message DocumentTransform message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentTransform.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DocumentTransform message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DocumentTransform} DocumentTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentTransform.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DocumentTransform(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.document = reader.string(); - break; - case 2: - if (!(message.fieldTransforms && message.fieldTransforms.length)) - message.fieldTransforms = []; - message.fieldTransforms.push($root.google.firestore.v1beta1.DocumentTransform.FieldTransform.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DocumentTransform message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DocumentTransform} DocumentTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentTransform.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DocumentTransform message. - * @function verify - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DocumentTransform.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.document != null && message.hasOwnProperty("document")) - if (!$util.isString(message.document)) - return "document: string expected"; - if (message.fieldTransforms != null && message.hasOwnProperty("fieldTransforms")) { - if (!Array.isArray(message.fieldTransforms)) - return "fieldTransforms: array expected"; - for (var i = 0; i < message.fieldTransforms.length; ++i) { - var error = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.verify(message.fieldTransforms[i]); - if (error) - return "fieldTransforms." + error; - } - } - return null; - }; - - /** - * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DocumentTransform} DocumentTransform - */ - DocumentTransform.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DocumentTransform) - return object; - var message = new $root.google.firestore.v1beta1.DocumentTransform(); - if (object.document != null) - message.document = String(object.document); - if (object.fieldTransforms) { - if (!Array.isArray(object.fieldTransforms)) - throw TypeError(".google.firestore.v1beta1.DocumentTransform.fieldTransforms: array expected"); - message.fieldTransforms = []; - for (var i = 0; i < object.fieldTransforms.length; ++i) { - if (typeof object.fieldTransforms[i] !== "object") - throw TypeError(".google.firestore.v1beta1.DocumentTransform.fieldTransforms: object expected"); - message.fieldTransforms[i] = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.fromObject(object.fieldTransforms[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DocumentTransform - * @static - * @param {google.firestore.v1beta1.DocumentTransform} message DocumentTransform - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentTransform.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.fieldTransforms = []; - if (options.defaults) - object.document = ""; - if (message.document != null && message.hasOwnProperty("document")) - object.document = message.document; - if (message.fieldTransforms && message.fieldTransforms.length) { - object.fieldTransforms = []; - for (var j = 0; j < message.fieldTransforms.length; ++j) - object.fieldTransforms[j] = $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.toObject(message.fieldTransforms[j], options); - } - return object; - }; - - /** - * Converts this DocumentTransform to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DocumentTransform - * @instance - * @returns {Object.} JSON object - */ - DocumentTransform.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - DocumentTransform.FieldTransform = (function() { - - /** - * Properties of a FieldTransform. - * @memberof google.firestore.v1beta1.DocumentTransform - * @interface IFieldTransform - * @property {string|null} [fieldPath] FieldTransform fieldPath - * @property {google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue|null} [setToServerValue] FieldTransform setToServerValue - * @property {google.firestore.v1beta1.IArrayValue|null} [appendMissingElements] FieldTransform appendMissingElements - * @property {google.firestore.v1beta1.IArrayValue|null} [removeAllFromArray] FieldTransform removeAllFromArray - */ - - /** - * Constructs a new FieldTransform. - * @memberof google.firestore.v1beta1.DocumentTransform - * @classdesc Represents a FieldTransform. - * @implements IFieldTransform - * @constructor - * @param {google.firestore.v1beta1.DocumentTransform.IFieldTransform=} [properties] Properties to set - */ - function FieldTransform(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldTransform fieldPath. - * @member {string} fieldPath - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.fieldPath = ""; - - /** - * FieldTransform setToServerValue. - * @member {google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue} setToServerValue - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.setToServerValue = 0; - - /** - * FieldTransform appendMissingElements. - * @member {google.firestore.v1beta1.IArrayValue|null|undefined} appendMissingElements - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.appendMissingElements = null; - - /** - * FieldTransform removeAllFromArray. - * @member {google.firestore.v1beta1.IArrayValue|null|undefined} removeAllFromArray - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.removeAllFromArray = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * FieldTransform transformType. - * @member {"setToServerValue"|"appendMissingElements"|"removeAllFromArray"|undefined} transformType - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @instance - */ - Object.defineProperty(FieldTransform.prototype, "transformType", { - get: $util.oneOfGetter($oneOfFields = ["setToServerValue", "appendMissingElements", "removeAllFromArray"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new FieldTransform instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {google.firestore.v1beta1.DocumentTransform.IFieldTransform=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DocumentTransform.FieldTransform} FieldTransform instance - */ - FieldTransform.create = function create(properties) { - return new FieldTransform(properties); - }; - - /** - * Encodes the specified FieldTransform message. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.FieldTransform.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {google.firestore.v1beta1.DocumentTransform.IFieldTransform} message FieldTransform message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldTransform.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.fieldPath); - if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.setToServerValue); - if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) - $root.google.firestore.v1beta1.ArrayValue.encode(message.appendMissingElements, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) - $root.google.firestore.v1beta1.ArrayValue.encode(message.removeAllFromArray, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified FieldTransform message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentTransform.FieldTransform.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {google.firestore.v1beta1.DocumentTransform.IFieldTransform} message FieldTransform message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldTransform.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FieldTransform message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DocumentTransform.FieldTransform} FieldTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldTransform.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DocumentTransform.FieldTransform(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.fieldPath = reader.string(); - break; - case 2: - message.setToServerValue = reader.int32(); - break; - case 6: - message.appendMissingElements = $root.google.firestore.v1beta1.ArrayValue.decode(reader, reader.uint32()); - break; - case 7: - message.removeAllFromArray = $root.google.firestore.v1beta1.ArrayValue.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FieldTransform message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DocumentTransform.FieldTransform} FieldTransform - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldTransform.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FieldTransform message. - * @function verify - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FieldTransform.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - if (!$util.isString(message.fieldPath)) - return "fieldPath: string expected"; - if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) { - properties.transformType = 1; - switch (message.setToServerValue) { - default: - return "setToServerValue: enum value expected"; - case 0: - case 1: - break; - } - } - if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) { - if (properties.transformType === 1) - return "transformType: multiple values"; - properties.transformType = 1; - { - var error = $root.google.firestore.v1beta1.ArrayValue.verify(message.appendMissingElements); - if (error) - return "appendMissingElements." + error; - } - } - if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) { - if (properties.transformType === 1) - return "transformType: multiple values"; - properties.transformType = 1; - { - var error = $root.google.firestore.v1beta1.ArrayValue.verify(message.removeAllFromArray); - if (error) - return "removeAllFromArray." + error; - } - } - return null; - }; - - /** - * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DocumentTransform.FieldTransform} FieldTransform - */ - FieldTransform.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DocumentTransform.FieldTransform) - return object; - var message = new $root.google.firestore.v1beta1.DocumentTransform.FieldTransform(); - if (object.fieldPath != null) - message.fieldPath = String(object.fieldPath); - switch (object.setToServerValue) { - case "SERVER_VALUE_UNSPECIFIED": - case 0: - message.setToServerValue = 0; - break; - case "REQUEST_TIME": - case 1: - message.setToServerValue = 1; - break; - } - if (object.appendMissingElements != null) { - if (typeof object.appendMissingElements !== "object") - throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.appendMissingElements: object expected"); - message.appendMissingElements = $root.google.firestore.v1beta1.ArrayValue.fromObject(object.appendMissingElements); - } - if (object.removeAllFromArray != null) { - if (typeof object.removeAllFromArray !== "object") - throw TypeError(".google.firestore.v1beta1.DocumentTransform.FieldTransform.removeAllFromArray: object expected"); - message.removeAllFromArray = $root.google.firestore.v1beta1.ArrayValue.fromObject(object.removeAllFromArray); - } - return message; - }; - - /** - * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @static - * @param {google.firestore.v1beta1.DocumentTransform.FieldTransform} message FieldTransform - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldTransform.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.fieldPath = ""; - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - object.fieldPath = message.fieldPath; - if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) { - object.setToServerValue = options.enums === String ? $root.google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] : message.setToServerValue; - if (options.oneofs) - object.transformType = "setToServerValue"; - } - if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) { - object.appendMissingElements = $root.google.firestore.v1beta1.ArrayValue.toObject(message.appendMissingElements, options); - if (options.oneofs) - object.transformType = "appendMissingElements"; - } - if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) { - object.removeAllFromArray = $root.google.firestore.v1beta1.ArrayValue.toObject(message.removeAllFromArray, options); - if (options.oneofs) - object.transformType = "removeAllFromArray"; - } - return object; - }; - - /** - * Converts this FieldTransform to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DocumentTransform.FieldTransform - * @instance - * @returns {Object.} JSON object - */ - FieldTransform.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * ServerValue enum. - * @name google.firestore.v1beta1.DocumentTransform.FieldTransform.ServerValue - * @enum {string} - * @property {number} SERVER_VALUE_UNSPECIFIED=0 SERVER_VALUE_UNSPECIFIED value - * @property {number} REQUEST_TIME=1 REQUEST_TIME value - */ - FieldTransform.ServerValue = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "SERVER_VALUE_UNSPECIFIED"] = 0; - values[valuesById[1] = "REQUEST_TIME"] = 1; - return values; - })(); - - return FieldTransform; - })(); - - return DocumentTransform; - })(); - - v1beta1.WriteResult = (function() { - - /** - * Properties of a WriteResult. - * @memberof google.firestore.v1beta1 - * @interface IWriteResult - * @property {google.protobuf.ITimestamp|null} [updateTime] WriteResult updateTime - * @property {Array.|null} [transformResults] WriteResult transformResults - */ - - /** - * Constructs a new WriteResult. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a WriteResult. - * @implements IWriteResult - * @constructor - * @param {google.firestore.v1beta1.IWriteResult=} [properties] Properties to set - */ - function WriteResult(properties) { - this.transformResults = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * WriteResult updateTime. - * @member {google.protobuf.ITimestamp|null|undefined} updateTime - * @memberof google.firestore.v1beta1.WriteResult - * @instance - */ - WriteResult.prototype.updateTime = null; - - /** - * WriteResult transformResults. - * @member {Array.} transformResults - * @memberof google.firestore.v1beta1.WriteResult - * @instance - */ - WriteResult.prototype.transformResults = $util.emptyArray; - - /** - * Creates a new WriteResult instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {google.firestore.v1beta1.IWriteResult=} [properties] Properties to set - * @returns {google.firestore.v1beta1.WriteResult} WriteResult instance - */ - WriteResult.create = function create(properties) { - return new WriteResult(properties); - }; - - /** - * Encodes the specified WriteResult message. Does not implicitly {@link google.firestore.v1beta1.WriteResult.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {google.firestore.v1beta1.IWriteResult} message WriteResult message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - WriteResult.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - $root.google.protobuf.Timestamp.encode(message.updateTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.transformResults != null && message.transformResults.length) - for (var i = 0; i < message.transformResults.length; ++i) - $root.google.firestore.v1beta1.Value.encode(message.transformResults[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified WriteResult message, length delimited. Does not implicitly {@link google.firestore.v1beta1.WriteResult.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {google.firestore.v1beta1.IWriteResult} message WriteResult message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - WriteResult.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a WriteResult message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.WriteResult} WriteResult - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - WriteResult.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.WriteResult(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.updateTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - case 2: - if (!(message.transformResults && message.transformResults.length)) - message.transformResults = []; - message.transformResults.push($root.google.firestore.v1beta1.Value.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a WriteResult message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.WriteResult} WriteResult - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - WriteResult.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a WriteResult message. - * @function verify - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - WriteResult.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.updateTime != null && message.hasOwnProperty("updateTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.updateTime); - if (error) - return "updateTime." + error; - } - if (message.transformResults != null && message.hasOwnProperty("transformResults")) { - if (!Array.isArray(message.transformResults)) - return "transformResults: array expected"; - for (var i = 0; i < message.transformResults.length; ++i) { - var error = $root.google.firestore.v1beta1.Value.verify(message.transformResults[i]); - if (error) - return "transformResults." + error; - } - } - return null; - }; - - /** - * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.WriteResult} WriteResult - */ - WriteResult.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.WriteResult) - return object; - var message = new $root.google.firestore.v1beta1.WriteResult(); - if (object.updateTime != null) { - if (typeof object.updateTime !== "object") - throw TypeError(".google.firestore.v1beta1.WriteResult.updateTime: object expected"); - message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); - } - if (object.transformResults) { - if (!Array.isArray(object.transformResults)) - throw TypeError(".google.firestore.v1beta1.WriteResult.transformResults: array expected"); - message.transformResults = []; - for (var i = 0; i < object.transformResults.length; ++i) { - if (typeof object.transformResults[i] !== "object") - throw TypeError(".google.firestore.v1beta1.WriteResult.transformResults: object expected"); - message.transformResults[i] = $root.google.firestore.v1beta1.Value.fromObject(object.transformResults[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a WriteResult message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.WriteResult - * @static - * @param {google.firestore.v1beta1.WriteResult} message WriteResult - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - WriteResult.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.transformResults = []; - if (options.defaults) - object.updateTime = null; - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); - if (message.transformResults && message.transformResults.length) { - object.transformResults = []; - for (var j = 0; j < message.transformResults.length; ++j) - object.transformResults[j] = $root.google.firestore.v1beta1.Value.toObject(message.transformResults[j], options); - } - return object; - }; - - /** - * Converts this WriteResult to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.WriteResult - * @instance - * @returns {Object.} JSON object - */ - WriteResult.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return WriteResult; - })(); - - v1beta1.DocumentChange = (function() { - - /** - * Properties of a DocumentChange. - * @memberof google.firestore.v1beta1 - * @interface IDocumentChange - * @property {google.firestore.v1beta1.IDocument|null} [document] DocumentChange document - * @property {Array.|null} [targetIds] DocumentChange targetIds - * @property {Array.|null} [removedTargetIds] DocumentChange removedTargetIds - */ - - /** - * Constructs a new DocumentChange. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a DocumentChange. - * @implements IDocumentChange - * @constructor - * @param {google.firestore.v1beta1.IDocumentChange=} [properties] Properties to set - */ - function DocumentChange(properties) { - this.targetIds = []; - this.removedTargetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DocumentChange document. - * @member {google.firestore.v1beta1.IDocument|null|undefined} document - * @memberof google.firestore.v1beta1.DocumentChange - * @instance - */ - DocumentChange.prototype.document = null; - - /** - * DocumentChange targetIds. - * @member {Array.} targetIds - * @memberof google.firestore.v1beta1.DocumentChange - * @instance - */ - DocumentChange.prototype.targetIds = $util.emptyArray; - - /** - * DocumentChange removedTargetIds. - * @member {Array.} removedTargetIds - * @memberof google.firestore.v1beta1.DocumentChange - * @instance - */ - DocumentChange.prototype.removedTargetIds = $util.emptyArray; - - /** - * Creates a new DocumentChange instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {google.firestore.v1beta1.IDocumentChange=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DocumentChange} DocumentChange instance - */ - DocumentChange.create = function create(properties) { - return new DocumentChange(properties); - }; - - /** - * Encodes the specified DocumentChange message. Does not implicitly {@link google.firestore.v1beta1.DocumentChange.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {google.firestore.v1beta1.IDocumentChange} message DocumentChange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentChange.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.document != null && message.hasOwnProperty("document")) - $root.google.firestore.v1beta1.Document.encode(message.document, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.targetIds != null && message.targetIds.length) { - writer.uint32(/* id 5, wireType 2 =*/42).fork(); - for (var i = 0; i < message.targetIds.length; ++i) - writer.int32(message.targetIds[i]); - writer.ldelim(); - } - if (message.removedTargetIds != null && message.removedTargetIds.length) { - writer.uint32(/* id 6, wireType 2 =*/50).fork(); - for (var i = 0; i < message.removedTargetIds.length; ++i) - writer.int32(message.removedTargetIds[i]); - writer.ldelim(); - } - return writer; - }; - - /** - * Encodes the specified DocumentChange message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentChange.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {google.firestore.v1beta1.IDocumentChange} message DocumentChange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentChange.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DocumentChange message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DocumentChange} DocumentChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentChange.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DocumentChange(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.document = $root.google.firestore.v1beta1.Document.decode(reader, reader.uint32()); - break; - case 5: - if (!(message.targetIds && message.targetIds.length)) - message.targetIds = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.targetIds.push(reader.int32()); - } else - message.targetIds.push(reader.int32()); - break; - case 6: - if (!(message.removedTargetIds && message.removedTargetIds.length)) - message.removedTargetIds = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.removedTargetIds.push(reader.int32()); - } else - message.removedTargetIds.push(reader.int32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DocumentChange message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DocumentChange} DocumentChange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentChange.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DocumentChange message. - * @function verify - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DocumentChange.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.document != null && message.hasOwnProperty("document")) { - var error = $root.google.firestore.v1beta1.Document.verify(message.document); - if (error) - return "document." + error; - } - if (message.targetIds != null && message.hasOwnProperty("targetIds")) { - if (!Array.isArray(message.targetIds)) - return "targetIds: array expected"; - for (var i = 0; i < message.targetIds.length; ++i) - if (!$util.isInteger(message.targetIds[i])) - return "targetIds: integer[] expected"; - } - if (message.removedTargetIds != null && message.hasOwnProperty("removedTargetIds")) { - if (!Array.isArray(message.removedTargetIds)) - return "removedTargetIds: array expected"; - for (var i = 0; i < message.removedTargetIds.length; ++i) - if (!$util.isInteger(message.removedTargetIds[i])) - return "removedTargetIds: integer[] expected"; - } - return null; - }; - - /** - * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DocumentChange} DocumentChange - */ - DocumentChange.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DocumentChange) - return object; - var message = new $root.google.firestore.v1beta1.DocumentChange(); - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1beta1.DocumentChange.document: object expected"); - message.document = $root.google.firestore.v1beta1.Document.fromObject(object.document); - } - if (object.targetIds) { - if (!Array.isArray(object.targetIds)) - throw TypeError(".google.firestore.v1beta1.DocumentChange.targetIds: array expected"); - message.targetIds = []; - for (var i = 0; i < object.targetIds.length; ++i) - message.targetIds[i] = object.targetIds[i] | 0; - } - if (object.removedTargetIds) { - if (!Array.isArray(object.removedTargetIds)) - throw TypeError(".google.firestore.v1beta1.DocumentChange.removedTargetIds: array expected"); - message.removedTargetIds = []; - for (var i = 0; i < object.removedTargetIds.length; ++i) - message.removedTargetIds[i] = object.removedTargetIds[i] | 0; - } - return message; - }; - - /** - * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DocumentChange - * @static - * @param {google.firestore.v1beta1.DocumentChange} message DocumentChange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentChange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.targetIds = []; - object.removedTargetIds = []; - } - if (options.defaults) - object.document = null; - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1beta1.Document.toObject(message.document, options); - if (message.targetIds && message.targetIds.length) { - object.targetIds = []; - for (var j = 0; j < message.targetIds.length; ++j) - object.targetIds[j] = message.targetIds[j]; - } - if (message.removedTargetIds && message.removedTargetIds.length) { - object.removedTargetIds = []; - for (var j = 0; j < message.removedTargetIds.length; ++j) - object.removedTargetIds[j] = message.removedTargetIds[j]; - } - return object; - }; - - /** - * Converts this DocumentChange to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DocumentChange - * @instance - * @returns {Object.} JSON object - */ - DocumentChange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DocumentChange; - })(); - - v1beta1.DocumentDelete = (function() { - - /** - * Properties of a DocumentDelete. - * @memberof google.firestore.v1beta1 - * @interface IDocumentDelete - * @property {string|null} [document] DocumentDelete document - * @property {Array.|null} [removedTargetIds] DocumentDelete removedTargetIds - * @property {google.protobuf.ITimestamp|null} [readTime] DocumentDelete readTime - */ - - /** - * Constructs a new DocumentDelete. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a DocumentDelete. - * @implements IDocumentDelete - * @constructor - * @param {google.firestore.v1beta1.IDocumentDelete=} [properties] Properties to set - */ - function DocumentDelete(properties) { - this.removedTargetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DocumentDelete document. - * @member {string} document - * @memberof google.firestore.v1beta1.DocumentDelete - * @instance - */ - DocumentDelete.prototype.document = ""; - - /** - * DocumentDelete removedTargetIds. - * @member {Array.} removedTargetIds - * @memberof google.firestore.v1beta1.DocumentDelete - * @instance - */ - DocumentDelete.prototype.removedTargetIds = $util.emptyArray; - - /** - * DocumentDelete readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.DocumentDelete - * @instance - */ - DocumentDelete.prototype.readTime = null; - - /** - * Creates a new DocumentDelete instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {google.firestore.v1beta1.IDocumentDelete=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DocumentDelete} DocumentDelete instance - */ - DocumentDelete.create = function create(properties) { - return new DocumentDelete(properties); - }; - - /** - * Encodes the specified DocumentDelete message. Does not implicitly {@link google.firestore.v1beta1.DocumentDelete.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {google.firestore.v1beta1.IDocumentDelete} message DocumentDelete message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentDelete.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.document != null && message.hasOwnProperty("document")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.document); - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.removedTargetIds != null && message.removedTargetIds.length) { - writer.uint32(/* id 6, wireType 2 =*/50).fork(); - for (var i = 0; i < message.removedTargetIds.length; ++i) - writer.int32(message.removedTargetIds[i]); - writer.ldelim(); - } - return writer; - }; - - /** - * Encodes the specified DocumentDelete message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentDelete.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {google.firestore.v1beta1.IDocumentDelete} message DocumentDelete message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentDelete.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DocumentDelete message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DocumentDelete} DocumentDelete - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentDelete.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DocumentDelete(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.document = reader.string(); - break; - case 6: - if (!(message.removedTargetIds && message.removedTargetIds.length)) - message.removedTargetIds = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.removedTargetIds.push(reader.int32()); - } else - message.removedTargetIds.push(reader.int32()); - break; - case 4: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DocumentDelete message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DocumentDelete} DocumentDelete - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentDelete.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DocumentDelete message. - * @function verify - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DocumentDelete.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.document != null && message.hasOwnProperty("document")) - if (!$util.isString(message.document)) - return "document: string expected"; - if (message.removedTargetIds != null && message.hasOwnProperty("removedTargetIds")) { - if (!Array.isArray(message.removedTargetIds)) - return "removedTargetIds: array expected"; - for (var i = 0; i < message.removedTargetIds.length; ++i) - if (!$util.isInteger(message.removedTargetIds[i])) - return "removedTargetIds: integer[] expected"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - return null; - }; - - /** - * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DocumentDelete} DocumentDelete - */ - DocumentDelete.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DocumentDelete) - return object; - var message = new $root.google.firestore.v1beta1.DocumentDelete(); - if (object.document != null) - message.document = String(object.document); - if (object.removedTargetIds) { - if (!Array.isArray(object.removedTargetIds)) - throw TypeError(".google.firestore.v1beta1.DocumentDelete.removedTargetIds: array expected"); - message.removedTargetIds = []; - for (var i = 0; i < object.removedTargetIds.length; ++i) - message.removedTargetIds[i] = object.removedTargetIds[i] | 0; - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.DocumentDelete.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DocumentDelete - * @static - * @param {google.firestore.v1beta1.DocumentDelete} message DocumentDelete - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentDelete.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.removedTargetIds = []; - if (options.defaults) { - object.document = ""; - object.readTime = null; - } - if (message.document != null && message.hasOwnProperty("document")) - object.document = message.document; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (message.removedTargetIds && message.removedTargetIds.length) { - object.removedTargetIds = []; - for (var j = 0; j < message.removedTargetIds.length; ++j) - object.removedTargetIds[j] = message.removedTargetIds[j]; - } - return object; - }; - - /** - * Converts this DocumentDelete to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DocumentDelete - * @instance - * @returns {Object.} JSON object - */ - DocumentDelete.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DocumentDelete; - })(); - - v1beta1.DocumentRemove = (function() { - - /** - * Properties of a DocumentRemove. - * @memberof google.firestore.v1beta1 - * @interface IDocumentRemove - * @property {string|null} [document] DocumentRemove document - * @property {Array.|null} [removedTargetIds] DocumentRemove removedTargetIds - * @property {google.protobuf.ITimestamp|null} [readTime] DocumentRemove readTime - */ - - /** - * Constructs a new DocumentRemove. - * @memberof google.firestore.v1beta1 - * @classdesc Represents a DocumentRemove. - * @implements IDocumentRemove - * @constructor - * @param {google.firestore.v1beta1.IDocumentRemove=} [properties] Properties to set - */ - function DocumentRemove(properties) { - this.removedTargetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DocumentRemove document. - * @member {string} document - * @memberof google.firestore.v1beta1.DocumentRemove - * @instance - */ - DocumentRemove.prototype.document = ""; - - /** - * DocumentRemove removedTargetIds. - * @member {Array.} removedTargetIds - * @memberof google.firestore.v1beta1.DocumentRemove - * @instance - */ - DocumentRemove.prototype.removedTargetIds = $util.emptyArray; - - /** - * DocumentRemove readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1beta1.DocumentRemove - * @instance - */ - DocumentRemove.prototype.readTime = null; - - /** - * Creates a new DocumentRemove instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {google.firestore.v1beta1.IDocumentRemove=} [properties] Properties to set - * @returns {google.firestore.v1beta1.DocumentRemove} DocumentRemove instance - */ - DocumentRemove.create = function create(properties) { - return new DocumentRemove(properties); - }; - - /** - * Encodes the specified DocumentRemove message. Does not implicitly {@link google.firestore.v1beta1.DocumentRemove.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {google.firestore.v1beta1.IDocumentRemove} message DocumentRemove message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentRemove.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.document != null && message.hasOwnProperty("document")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.document); - if (message.removedTargetIds != null && message.removedTargetIds.length) { - writer.uint32(/* id 2, wireType 2 =*/18).fork(); - for (var i = 0; i < message.removedTargetIds.length; ++i) - writer.int32(message.removedTargetIds[i]); - writer.ldelim(); - } - if (message.readTime != null && message.hasOwnProperty("readTime")) - $root.google.protobuf.Timestamp.encode(message.readTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified DocumentRemove message, length delimited. Does not implicitly {@link google.firestore.v1beta1.DocumentRemove.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {google.firestore.v1beta1.IDocumentRemove} message DocumentRemove message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DocumentRemove.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DocumentRemove message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.DocumentRemove} DocumentRemove - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentRemove.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.DocumentRemove(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.document = reader.string(); - break; - case 2: - if (!(message.removedTargetIds && message.removedTargetIds.length)) - message.removedTargetIds = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.removedTargetIds.push(reader.int32()); - } else - message.removedTargetIds.push(reader.int32()); - break; - case 4: - message.readTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DocumentRemove message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.DocumentRemove} DocumentRemove - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DocumentRemove.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DocumentRemove message. - * @function verify - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DocumentRemove.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.document != null && message.hasOwnProperty("document")) - if (!$util.isString(message.document)) - return "document: string expected"; - if (message.removedTargetIds != null && message.hasOwnProperty("removedTargetIds")) { - if (!Array.isArray(message.removedTargetIds)) - return "removedTargetIds: array expected"; - for (var i = 0; i < message.removedTargetIds.length; ++i) - if (!$util.isInteger(message.removedTargetIds[i])) - return "removedTargetIds: integer[] expected"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - var error = $root.google.protobuf.Timestamp.verify(message.readTime); - if (error) - return "readTime." + error; - } - return null; - }; - - /** - * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.DocumentRemove} DocumentRemove - */ - DocumentRemove.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.DocumentRemove) - return object; - var message = new $root.google.firestore.v1beta1.DocumentRemove(); - if (object.document != null) - message.document = String(object.document); - if (object.removedTargetIds) { - if (!Array.isArray(object.removedTargetIds)) - throw TypeError(".google.firestore.v1beta1.DocumentRemove.removedTargetIds: array expected"); - message.removedTargetIds = []; - for (var i = 0; i < object.removedTargetIds.length; ++i) - message.removedTargetIds[i] = object.removedTargetIds[i] | 0; - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1beta1.DocumentRemove.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; - - /** - * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.DocumentRemove - * @static - * @param {google.firestore.v1beta1.DocumentRemove} message DocumentRemove - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentRemove.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.removedTargetIds = []; - if (options.defaults) { - object.document = ""; - object.readTime = null; - } - if (message.document != null && message.hasOwnProperty("document")) - object.document = message.document; - if (message.removedTargetIds && message.removedTargetIds.length) { - object.removedTargetIds = []; - for (var j = 0; j < message.removedTargetIds.length; ++j) - object.removedTargetIds[j] = message.removedTargetIds[j]; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - return object; - }; - - /** - * Converts this DocumentRemove to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.DocumentRemove - * @instance - * @returns {Object.} JSON object - */ - DocumentRemove.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DocumentRemove; - })(); - - v1beta1.ExistenceFilter = (function() { - - /** - * Properties of an ExistenceFilter. - * @memberof google.firestore.v1beta1 - * @interface IExistenceFilter - * @property {number|null} [targetId] ExistenceFilter targetId - * @property {number|null} [count] ExistenceFilter count - */ - - /** - * Constructs a new ExistenceFilter. - * @memberof google.firestore.v1beta1 - * @classdesc Represents an ExistenceFilter. - * @implements IExistenceFilter - * @constructor - * @param {google.firestore.v1beta1.IExistenceFilter=} [properties] Properties to set - */ - function ExistenceFilter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ExistenceFilter targetId. - * @member {number} targetId - * @memberof google.firestore.v1beta1.ExistenceFilter - * @instance - */ - ExistenceFilter.prototype.targetId = 0; - - /** - * ExistenceFilter count. - * @member {number} count - * @memberof google.firestore.v1beta1.ExistenceFilter - * @instance - */ - ExistenceFilter.prototype.count = 0; - - /** - * Creates a new ExistenceFilter instance using the specified properties. - * @function create - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {google.firestore.v1beta1.IExistenceFilter=} [properties] Properties to set - * @returns {google.firestore.v1beta1.ExistenceFilter} ExistenceFilter instance - */ - ExistenceFilter.create = function create(properties) { - return new ExistenceFilter(properties); - }; - - /** - * Encodes the specified ExistenceFilter message. Does not implicitly {@link google.firestore.v1beta1.ExistenceFilter.verify|verify} messages. - * @function encode - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {google.firestore.v1beta1.IExistenceFilter} message ExistenceFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExistenceFilter.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.targetId != null && message.hasOwnProperty("targetId")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.targetId); - if (message.count != null && message.hasOwnProperty("count")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.count); - return writer; - }; - - /** - * Encodes the specified ExistenceFilter message, length delimited. Does not implicitly {@link google.firestore.v1beta1.ExistenceFilter.verify|verify} messages. - * @function encodeDelimited - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {google.firestore.v1beta1.IExistenceFilter} message ExistenceFilter message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExistenceFilter.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an ExistenceFilter message from the specified reader or buffer. - * @function decode - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.firestore.v1beta1.ExistenceFilter} ExistenceFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExistenceFilter.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.firestore.v1beta1.ExistenceFilter(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.targetId = reader.int32(); - break; - case 2: - message.count = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an ExistenceFilter message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.firestore.v1beta1.ExistenceFilter} ExistenceFilter - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExistenceFilter.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an ExistenceFilter message. - * @function verify - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExistenceFilter.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.targetId != null && message.hasOwnProperty("targetId")) - if (!$util.isInteger(message.targetId)) - return "targetId: integer expected"; - if (message.count != null && message.hasOwnProperty("count")) - if (!$util.isInteger(message.count)) - return "count: integer expected"; - return null; - }; - - /** - * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1beta1.ExistenceFilter} ExistenceFilter - */ - ExistenceFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1beta1.ExistenceFilter) - return object; - var message = new $root.google.firestore.v1beta1.ExistenceFilter(); - if (object.targetId != null) - message.targetId = object.targetId | 0; - if (object.count != null) - message.count = object.count | 0; - return message; - }; - - /** - * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1beta1.ExistenceFilter - * @static - * @param {google.firestore.v1beta1.ExistenceFilter} message ExistenceFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExistenceFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.targetId = 0; - object.count = 0; - } - if (message.targetId != null && message.hasOwnProperty("targetId")) - object.targetId = message.targetId; - if (message.count != null && message.hasOwnProperty("count")) - object.count = message.count; - return object; - }; - - /** - * Converts this ExistenceFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1beta1.ExistenceFilter - * @instance - * @returns {Object.} JSON object - */ - ExistenceFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ExistenceFilter; - })(); - - return v1beta1; - })(); - - return firestore; - })(); - - google.api = (function() { - - /** - * Namespace api. - * @memberof google - * @namespace - */ - var api = {}; - - api.Http = (function() { - - /** - * Properties of a Http. - * @memberof google.api - * @interface IHttp - * @property {Array.|null} [rules] Http rules - */ - - /** - * Constructs a new Http. - * @memberof google.api - * @classdesc Represents a Http. - * @implements IHttp - * @constructor - * @param {google.api.IHttp=} [properties] Properties to set - */ - function Http(properties) { - this.rules = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Http rules. - * @member {Array.} rules - * @memberof google.api.Http - * @instance - */ - Http.prototype.rules = $util.emptyArray; - - /** - * Creates a new Http instance using the specified properties. - * @function create - * @memberof google.api.Http - * @static - * @param {google.api.IHttp=} [properties] Properties to set - * @returns {google.api.Http} Http instance - */ - Http.create = function create(properties) { - return new Http(properties); - }; - - /** - * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. - * @function encode - * @memberof google.api.Http - * @static - * @param {google.api.IHttp} message Http message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Http.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.rules != null && message.rules.length) - for (var i = 0; i < message.rules.length; ++i) - $root.google.api.HttpRule.encode(message.rules[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. - * @function encodeDelimited - * @memberof google.api.Http - * @static - * @param {google.api.IHttp} message Http message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Http.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Http message from the specified reader or buffer. - * @function decode - * @memberof google.api.Http - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.api.Http} Http - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Http.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.Http(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.rules && message.rules.length)) - message.rules = []; - message.rules.push($root.google.api.HttpRule.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Http message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.api.Http - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.api.Http} Http - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Http.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Http message. - * @function verify - * @memberof google.api.Http - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Http.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.rules != null && message.hasOwnProperty("rules")) { - if (!Array.isArray(message.rules)) - return "rules: array expected"; - for (var i = 0; i < message.rules.length; ++i) { - var error = $root.google.api.HttpRule.verify(message.rules[i]); - if (error) - return "rules." + error; - } - } - return null; - }; - - /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.Http - * @static - * @param {Object.} object Plain object - * @returns {google.api.Http} Http - */ - Http.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.Http) - return object; - var message = new $root.google.api.Http(); - if (object.rules) { - if (!Array.isArray(object.rules)) - throw TypeError(".google.api.Http.rules: array expected"); - message.rules = []; - for (var i = 0; i < object.rules.length; ++i) { - if (typeof object.rules[i] !== "object") - throw TypeError(".google.api.Http.rules: object expected"); - message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.Http - * @static - * @param {google.api.Http} message Http - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Http.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.rules = []; - if (message.rules && message.rules.length) { - object.rules = []; - for (var j = 0; j < message.rules.length; ++j) - object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); - } - return object; - }; - - /** - * Converts this Http to JSON. - * @function toJSON - * @memberof google.api.Http - * @instance - * @returns {Object.} JSON object - */ - Http.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Http; - })(); - - api.HttpRule = (function() { - - /** - * Properties of a HttpRule. - * @memberof google.api - * @interface IHttpRule - * @property {string|null} [get] HttpRule get - * @property {string|null} [put] HttpRule put - * @property {string|null} [post] HttpRule post - * @property {string|null} ["delete"] HttpRule delete - * @property {string|null} [patch] HttpRule patch - * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom - * @property {string|null} [selector] HttpRule selector - * @property {string|null} [body] HttpRule body - * @property {Array.|null} [additionalBindings] HttpRule additionalBindings - */ - - /** - * Constructs a new HttpRule. - * @memberof google.api - * @classdesc Represents a HttpRule. - * @implements IHttpRule - * @constructor - * @param {google.api.IHttpRule=} [properties] Properties to set - */ - function HttpRule(properties) { - this.additionalBindings = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * HttpRule get. - * @member {string} get - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.get = ""; - - /** - * HttpRule put. - * @member {string} put - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.put = ""; - - /** - * HttpRule post. - * @member {string} post - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.post = ""; - - /** - * HttpRule delete. - * @member {string} delete - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype["delete"] = ""; - - /** - * HttpRule patch. - * @member {string} patch - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.patch = ""; - - /** - * HttpRule custom. - * @member {google.api.ICustomHttpPattern|null|undefined} custom - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.custom = null; - - /** - * HttpRule selector. - * @member {string} selector - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.selector = ""; - - /** - * HttpRule body. - * @member {string} body - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.body = ""; - - /** - * HttpRule additionalBindings. - * @member {Array.} additionalBindings - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.additionalBindings = $util.emptyArray; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * HttpRule pattern. - * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern - * @memberof google.api.HttpRule - * @instance - */ - Object.defineProperty(HttpRule.prototype, "pattern", { - get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new HttpRule instance using the specified properties. - * @function create - * @memberof google.api.HttpRule - * @static - * @param {google.api.IHttpRule=} [properties] Properties to set - * @returns {google.api.HttpRule} HttpRule instance - */ - HttpRule.create = function create(properties) { - return new HttpRule(properties); - }; - - /** - * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. - * @function encode - * @memberof google.api.HttpRule - * @static - * @param {google.api.IHttpRule} message HttpRule message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - HttpRule.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.selector != null && message.hasOwnProperty("selector")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.selector); - if (message.get != null && message.hasOwnProperty("get")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.get); - if (message.put != null && message.hasOwnProperty("put")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.put); - if (message.post != null && message.hasOwnProperty("post")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.post); - if (message["delete"] != null && message.hasOwnProperty("delete")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message["delete"]); - if (message.patch != null && message.hasOwnProperty("patch")) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.patch); - if (message.body != null && message.hasOwnProperty("body")) - writer.uint32(/* id 7, wireType 2 =*/58).string(message.body); - if (message.custom != null && message.hasOwnProperty("custom")) - $root.google.api.CustomHttpPattern.encode(message.custom, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - if (message.additionalBindings != null && message.additionalBindings.length) - for (var i = 0; i < message.additionalBindings.length; ++i) - $root.google.api.HttpRule.encode(message.additionalBindings[i], writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. - * @function encodeDelimited - * @memberof google.api.HttpRule - * @static - * @param {google.api.IHttpRule} message HttpRule message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - HttpRule.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a HttpRule message from the specified reader or buffer. - * @function decode - * @memberof google.api.HttpRule - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.api.HttpRule} HttpRule - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - HttpRule.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.HttpRule(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.get = reader.string(); - break; - case 3: - message.put = reader.string(); - break; - case 4: - message.post = reader.string(); - break; - case 5: - message["delete"] = reader.string(); - break; - case 6: - message.patch = reader.string(); - break; - case 8: - message.custom = $root.google.api.CustomHttpPattern.decode(reader, reader.uint32()); - break; - case 1: - message.selector = reader.string(); - break; - case 7: - message.body = reader.string(); - break; - case 11: - if (!(message.additionalBindings && message.additionalBindings.length)) - message.additionalBindings = []; - message.additionalBindings.push($root.google.api.HttpRule.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a HttpRule message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.api.HttpRule - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.api.HttpRule} HttpRule - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - HttpRule.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a HttpRule message. - * @function verify - * @memberof google.api.HttpRule - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - HttpRule.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.get != null && message.hasOwnProperty("get")) { - properties.pattern = 1; - if (!$util.isString(message.get)) - return "get: string expected"; - } - if (message.put != null && message.hasOwnProperty("put")) { - if (properties.pattern === 1) - return "pattern: multiple values"; - properties.pattern = 1; - if (!$util.isString(message.put)) - return "put: string expected"; - } - if (message.post != null && message.hasOwnProperty("post")) { - if (properties.pattern === 1) - return "pattern: multiple values"; - properties.pattern = 1; - if (!$util.isString(message.post)) - return "post: string expected"; - } - if (message["delete"] != null && message.hasOwnProperty("delete")) { - if (properties.pattern === 1) - return "pattern: multiple values"; - properties.pattern = 1; - if (!$util.isString(message["delete"])) - return "delete: string expected"; - } - if (message.patch != null && message.hasOwnProperty("patch")) { - if (properties.pattern === 1) - return "pattern: multiple values"; - properties.pattern = 1; - if (!$util.isString(message.patch)) - return "patch: string expected"; - } - if (message.custom != null && message.hasOwnProperty("custom")) { - if (properties.pattern === 1) - return "pattern: multiple values"; - properties.pattern = 1; - { - var error = $root.google.api.CustomHttpPattern.verify(message.custom); - if (error) - return "custom." + error; - } - } - if (message.selector != null && message.hasOwnProperty("selector")) - if (!$util.isString(message.selector)) - return "selector: string expected"; - if (message.body != null && message.hasOwnProperty("body")) - if (!$util.isString(message.body)) - return "body: string expected"; - if (message.additionalBindings != null && message.hasOwnProperty("additionalBindings")) { - if (!Array.isArray(message.additionalBindings)) - return "additionalBindings: array expected"; - for (var i = 0; i < message.additionalBindings.length; ++i) { - var error = $root.google.api.HttpRule.verify(message.additionalBindings[i]); - if (error) - return "additionalBindings." + error; - } - } - return null; - }; - - /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.HttpRule - * @static - * @param {Object.} object Plain object - * @returns {google.api.HttpRule} HttpRule - */ - HttpRule.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.HttpRule) - return object; - var message = new $root.google.api.HttpRule(); - if (object.get != null) - message.get = String(object.get); - if (object.put != null) - message.put = String(object.put); - if (object.post != null) - message.post = String(object.post); - if (object["delete"] != null) - message["delete"] = String(object["delete"]); - if (object.patch != null) - message.patch = String(object.patch); - if (object.custom != null) { - if (typeof object.custom !== "object") - throw TypeError(".google.api.HttpRule.custom: object expected"); - message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); - } - if (object.selector != null) - message.selector = String(object.selector); - if (object.body != null) - message.body = String(object.body); - if (object.additionalBindings) { - if (!Array.isArray(object.additionalBindings)) - throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); - message.additionalBindings = []; - for (var i = 0; i < object.additionalBindings.length; ++i) { - if (typeof object.additionalBindings[i] !== "object") - throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); - message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.HttpRule - * @static - * @param {google.api.HttpRule} message HttpRule - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - HttpRule.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.additionalBindings = []; - if (options.defaults) { - object.selector = ""; - object.body = ""; - } - if (message.selector != null && message.hasOwnProperty("selector")) - object.selector = message.selector; - if (message.get != null && message.hasOwnProperty("get")) { - object.get = message.get; - if (options.oneofs) - object.pattern = "get"; - } - if (message.put != null && message.hasOwnProperty("put")) { - object.put = message.put; - if (options.oneofs) - object.pattern = "put"; - } - if (message.post != null && message.hasOwnProperty("post")) { - object.post = message.post; - if (options.oneofs) - object.pattern = "post"; - } - if (message["delete"] != null && message.hasOwnProperty("delete")) { - object["delete"] = message["delete"]; - if (options.oneofs) - object.pattern = "delete"; - } - if (message.patch != null && message.hasOwnProperty("patch")) { - object.patch = message.patch; - if (options.oneofs) - object.pattern = "patch"; - } - if (message.body != null && message.hasOwnProperty("body")) - object.body = message.body; - if (message.custom != null && message.hasOwnProperty("custom")) { - object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); - if (options.oneofs) - object.pattern = "custom"; - } - if (message.additionalBindings && message.additionalBindings.length) { - object.additionalBindings = []; - for (var j = 0; j < message.additionalBindings.length; ++j) - object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); - } - return object; - }; - - /** - * Converts this HttpRule to JSON. - * @function toJSON - * @memberof google.api.HttpRule - * @instance - * @returns {Object.} JSON object - */ - HttpRule.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return HttpRule; - })(); - - api.CustomHttpPattern = (function() { - - /** - * Properties of a CustomHttpPattern. - * @memberof google.api - * @interface ICustomHttpPattern - * @property {string|null} [kind] CustomHttpPattern kind - * @property {string|null} [path] CustomHttpPattern path - */ - - /** - * Constructs a new CustomHttpPattern. - * @memberof google.api - * @classdesc Represents a CustomHttpPattern. - * @implements ICustomHttpPattern - * @constructor - * @param {google.api.ICustomHttpPattern=} [properties] Properties to set - */ - function CustomHttpPattern(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CustomHttpPattern kind. - * @member {string} kind - * @memberof google.api.CustomHttpPattern - * @instance - */ - CustomHttpPattern.prototype.kind = ""; - - /** - * CustomHttpPattern path. - * @member {string} path - * @memberof google.api.CustomHttpPattern - * @instance - */ - CustomHttpPattern.prototype.path = ""; - - /** - * Creates a new CustomHttpPattern instance using the specified properties. - * @function create - * @memberof google.api.CustomHttpPattern - * @static - * @param {google.api.ICustomHttpPattern=} [properties] Properties to set - * @returns {google.api.CustomHttpPattern} CustomHttpPattern instance - */ - CustomHttpPattern.create = function create(properties) { - return new CustomHttpPattern(properties); - }; - - /** - * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. - * @function encode - * @memberof google.api.CustomHttpPattern - * @static - * @param {google.api.ICustomHttpPattern} message CustomHttpPattern message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CustomHttpPattern.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.kind != null && message.hasOwnProperty("kind")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.kind); - if (message.path != null && message.hasOwnProperty("path")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.path); - return writer; - }; - - /** - * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. - * @function encodeDelimited - * @memberof google.api.CustomHttpPattern - * @static - * @param {google.api.ICustomHttpPattern} message CustomHttpPattern message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - CustomHttpPattern.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a CustomHttpPattern message from the specified reader or buffer. - * @function decode - * @memberof google.api.CustomHttpPattern - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.api.CustomHttpPattern} CustomHttpPattern - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CustomHttpPattern.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.CustomHttpPattern(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.kind = reader.string(); - break; - case 2: - message.path = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.api.CustomHttpPattern - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.api.CustomHttpPattern} CustomHttpPattern - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - CustomHttpPattern.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a CustomHttpPattern message. - * @function verify - * @memberof google.api.CustomHttpPattern - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - CustomHttpPattern.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.kind != null && message.hasOwnProperty("kind")) - if (!$util.isString(message.kind)) - return "kind: string expected"; - if (message.path != null && message.hasOwnProperty("path")) - if (!$util.isString(message.path)) - return "path: string expected"; - return null; - }; - - /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.CustomHttpPattern - * @static - * @param {Object.} object Plain object - * @returns {google.api.CustomHttpPattern} CustomHttpPattern - */ - CustomHttpPattern.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.CustomHttpPattern) - return object; - var message = new $root.google.api.CustomHttpPattern(); - if (object.kind != null) - message.kind = String(object.kind); - if (object.path != null) - message.path = String(object.path); - return message; - }; - - /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.CustomHttpPattern - * @static - * @param {google.api.CustomHttpPattern} message CustomHttpPattern - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CustomHttpPattern.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.kind = ""; - object.path = ""; - } - if (message.kind != null && message.hasOwnProperty("kind")) - object.kind = message.kind; - if (message.path != null && message.hasOwnProperty("path")) - object.path = message.path; - return object; - }; - - /** - * Converts this CustomHttpPattern to JSON. - * @function toJSON - * @memberof google.api.CustomHttpPattern - * @instance - * @returns {Object.} JSON object - */ - CustomHttpPattern.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return CustomHttpPattern; - })(); - - return api; - })(); - - google.protobuf = (function() { - - /** - * Namespace protobuf. - * @memberof google - * @namespace - */ - var protobuf = {}; - - protobuf.FileDescriptorSet = (function() { - - /** - * Properties of a FileDescriptorSet. - * @memberof google.protobuf - * @interface IFileDescriptorSet - * @property {Array.|null} [file] FileDescriptorSet file - */ - - /** - * Constructs a new FileDescriptorSet. - * @memberof google.protobuf - * @classdesc Represents a FileDescriptorSet. - * @implements IFileDescriptorSet - * @constructor - * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set - */ - function FileDescriptorSet(properties) { - this.file = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FileDescriptorSet file. - * @member {Array.} file - * @memberof google.protobuf.FileDescriptorSet - * @instance - */ - FileDescriptorSet.prototype.file = $util.emptyArray; - - /** - * Creates a new FileDescriptorSet instance using the specified properties. - * @function create - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set - * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet instance - */ - FileDescriptorSet.create = function create(properties) { - return new FileDescriptorSet(properties); - }; - - /** - * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {google.protobuf.IFileDescriptorSet} message FileDescriptorSet message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FileDescriptorSet.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.file != null && message.file.length) - for (var i = 0; i < message.file.length; ++i) - $root.google.protobuf.FileDescriptorProto.encode(message.file[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {google.protobuf.IFileDescriptorSet} message FileDescriptorSet message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FileDescriptorSet.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FileDescriptorSet message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FileDescriptorSet.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FileDescriptorSet(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.file && message.file.length)) - message.file = []; - message.file.push($root.google.protobuf.FileDescriptorProto.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FileDescriptorSet.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FileDescriptorSet message. - * @function verify - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FileDescriptorSet.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.file != null && message.hasOwnProperty("file")) { - if (!Array.isArray(message.file)) - return "file: array expected"; - for (var i = 0; i < message.file.length; ++i) { - var error = $root.google.protobuf.FileDescriptorProto.verify(message.file[i]); - if (error) - return "file." + error; - } - } - return null; - }; - - /** - * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet - */ - FileDescriptorSet.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FileDescriptorSet) - return object; - var message = new $root.google.protobuf.FileDescriptorSet(); - if (object.file) { - if (!Array.isArray(object.file)) - throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); - message.file = []; - for (var i = 0; i < object.file.length; ++i) { - if (typeof object.file[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); - message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FileDescriptorSet.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.file = []; - if (message.file && message.file.length) { - object.file = []; - for (var j = 0; j < message.file.length; ++j) - object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); - } - return object; - }; - - /** - * Converts this FileDescriptorSet to JSON. - * @function toJSON - * @memberof google.protobuf.FileDescriptorSet - * @instance - * @returns {Object.} JSON object - */ - FileDescriptorSet.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return FileDescriptorSet; - })(); - - protobuf.FileDescriptorProto = (function() { - - /** - * Properties of a FileDescriptorProto. - * @memberof google.protobuf - * @interface IFileDescriptorProto - * @property {string|null} [name] FileDescriptorProto name - * @property {string|null} ["package"] FileDescriptorProto package - * @property {Array.|null} [dependency] FileDescriptorProto dependency - * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency - * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency - * @property {Array.|null} [messageType] FileDescriptorProto messageType - * @property {Array.|null} [enumType] FileDescriptorProto enumType - * @property {Array.|null} [service] FileDescriptorProto service - * @property {Array.|null} [extension] FileDescriptorProto extension - * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options - * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo - * @property {string|null} [syntax] FileDescriptorProto syntax - */ - - /** - * Constructs a new FileDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a FileDescriptorProto. - * @implements IFileDescriptorProto - * @constructor - * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set - */ - function FileDescriptorProto(properties) { - this.dependency = []; - this.publicDependency = []; - this.weakDependency = []; - this.messageType = []; - this.enumType = []; - this.service = []; - this.extension = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FileDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.name = ""; - - /** - * FileDescriptorProto package. - * @member {string} package - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype["package"] = ""; - - /** - * FileDescriptorProto dependency. - * @member {Array.} dependency - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.dependency = $util.emptyArray; - - /** - * FileDescriptorProto publicDependency. - * @member {Array.} publicDependency - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.publicDependency = $util.emptyArray; - - /** - * FileDescriptorProto weakDependency. - * @member {Array.} weakDependency - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.weakDependency = $util.emptyArray; - - /** - * FileDescriptorProto messageType. - * @member {Array.} messageType - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.messageType = $util.emptyArray; - - /** - * FileDescriptorProto enumType. - * @member {Array.} enumType - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.enumType = $util.emptyArray; - - /** - * FileDescriptorProto service. - * @member {Array.} service - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.service = $util.emptyArray; - - /** - * FileDescriptorProto extension. - * @member {Array.} extension - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.extension = $util.emptyArray; - - /** - * FileDescriptorProto options. - * @member {google.protobuf.IFileOptions|null|undefined} options - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.options = null; - - /** - * FileDescriptorProto sourceCodeInfo. - * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.sourceCodeInfo = null; - - /** - * FileDescriptorProto syntax. - * @member {string} syntax - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.syntax = ""; - - /** - * Creates a new FileDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto instance - */ - FileDescriptorProto.create = function create(properties) { - return new FileDescriptorProto(properties); - }; - - /** - * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {google.protobuf.IFileDescriptorProto} message FileDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FileDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message["package"] != null && message.hasOwnProperty("package")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message["package"]); - if (message.dependency != null && message.dependency.length) - for (var i = 0; i < message.dependency.length; ++i) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.dependency[i]); - if (message.messageType != null && message.messageType.length) - for (var i = 0; i < message.messageType.length; ++i) - $root.google.protobuf.DescriptorProto.encode(message.messageType[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.enumType != null && message.enumType.length) - for (var i = 0; i < message.enumType.length; ++i) - $root.google.protobuf.EnumDescriptorProto.encode(message.enumType[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.service != null && message.service.length) - for (var i = 0; i < message.service.length; ++i) - $root.google.protobuf.ServiceDescriptorProto.encode(message.service[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - if (message.extension != null && message.extension.length) - for (var i = 0; i < message.extension.length; ++i) - $root.google.protobuf.FieldDescriptorProto.encode(message.extension[i], writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.FileOptions.encode(message.options, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) - $root.google.protobuf.SourceCodeInfo.encode(message.sourceCodeInfo, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); - if (message.publicDependency != null && message.publicDependency.length) - for (var i = 0; i < message.publicDependency.length; ++i) - writer.uint32(/* id 10, wireType 0 =*/80).int32(message.publicDependency[i]); - if (message.weakDependency != null && message.weakDependency.length) - for (var i = 0; i < message.weakDependency.length; ++i) - writer.uint32(/* id 11, wireType 0 =*/88).int32(message.weakDependency[i]); - if (message.syntax != null && message.hasOwnProperty("syntax")) - writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); - return writer; - }; - - /** - * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {google.protobuf.IFileDescriptorProto} message FileDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FileDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FileDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FileDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FileDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - message["package"] = reader.string(); - break; - case 3: - if (!(message.dependency && message.dependency.length)) - message.dependency = []; - message.dependency.push(reader.string()); - break; - case 10: - if (!(message.publicDependency && message.publicDependency.length)) - message.publicDependency = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.publicDependency.push(reader.int32()); - } else - message.publicDependency.push(reader.int32()); - break; - case 11: - if (!(message.weakDependency && message.weakDependency.length)) - message.weakDependency = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.weakDependency.push(reader.int32()); - } else - message.weakDependency.push(reader.int32()); - break; - case 4: - if (!(message.messageType && message.messageType.length)) - message.messageType = []; - message.messageType.push($root.google.protobuf.DescriptorProto.decode(reader, reader.uint32())); - break; - case 5: - if (!(message.enumType && message.enumType.length)) - message.enumType = []; - message.enumType.push($root.google.protobuf.EnumDescriptorProto.decode(reader, reader.uint32())); - break; - case 6: - if (!(message.service && message.service.length)) - message.service = []; - message.service.push($root.google.protobuf.ServiceDescriptorProto.decode(reader, reader.uint32())); - break; - case 7: - if (!(message.extension && message.extension.length)) - message.extension = []; - message.extension.push($root.google.protobuf.FieldDescriptorProto.decode(reader, reader.uint32())); - break; - case 8: - message.options = $root.google.protobuf.FileOptions.decode(reader, reader.uint32()); - break; - case 9: - message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.decode(reader, reader.uint32()); - break; - case 12: - message.syntax = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FileDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FileDescriptorProto message. - * @function verify - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FileDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message["package"] != null && message.hasOwnProperty("package")) - if (!$util.isString(message["package"])) - return "package: string expected"; - if (message.dependency != null && message.hasOwnProperty("dependency")) { - if (!Array.isArray(message.dependency)) - return "dependency: array expected"; - for (var i = 0; i < message.dependency.length; ++i) - if (!$util.isString(message.dependency[i])) - return "dependency: string[] expected"; - } - if (message.publicDependency != null && message.hasOwnProperty("publicDependency")) { - if (!Array.isArray(message.publicDependency)) - return "publicDependency: array expected"; - for (var i = 0; i < message.publicDependency.length; ++i) - if (!$util.isInteger(message.publicDependency[i])) - return "publicDependency: integer[] expected"; - } - if (message.weakDependency != null && message.hasOwnProperty("weakDependency")) { - if (!Array.isArray(message.weakDependency)) - return "weakDependency: array expected"; - for (var i = 0; i < message.weakDependency.length; ++i) - if (!$util.isInteger(message.weakDependency[i])) - return "weakDependency: integer[] expected"; - } - if (message.messageType != null && message.hasOwnProperty("messageType")) { - if (!Array.isArray(message.messageType)) - return "messageType: array expected"; - for (var i = 0; i < message.messageType.length; ++i) { - var error = $root.google.protobuf.DescriptorProto.verify(message.messageType[i]); - if (error) - return "messageType." + error; - } - } - if (message.enumType != null && message.hasOwnProperty("enumType")) { - if (!Array.isArray(message.enumType)) - return "enumType: array expected"; - for (var i = 0; i < message.enumType.length; ++i) { - var error = $root.google.protobuf.EnumDescriptorProto.verify(message.enumType[i]); - if (error) - return "enumType." + error; - } - } - if (message.service != null && message.hasOwnProperty("service")) { - if (!Array.isArray(message.service)) - return "service: array expected"; - for (var i = 0; i < message.service.length; ++i) { - var error = $root.google.protobuf.ServiceDescriptorProto.verify(message.service[i]); - if (error) - return "service." + error; - } - } - if (message.extension != null && message.hasOwnProperty("extension")) { - if (!Array.isArray(message.extension)) - return "extension: array expected"; - for (var i = 0; i < message.extension.length; ++i) { - var error = $root.google.protobuf.FieldDescriptorProto.verify(message.extension[i]); - if (error) - return "extension." + error; - } - } - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.FileOptions.verify(message.options); - if (error) - return "options." + error; - } - if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) { - var error = $root.google.protobuf.SourceCodeInfo.verify(message.sourceCodeInfo); - if (error) - return "sourceCodeInfo." + error; - } - if (message.syntax != null && message.hasOwnProperty("syntax")) - if (!$util.isString(message.syntax)) - return "syntax: string expected"; - return null; - }; - - /** - * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto - */ - FileDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FileDescriptorProto) - return object; - var message = new $root.google.protobuf.FileDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object["package"] != null) - message["package"] = String(object["package"]); - if (object.dependency) { - if (!Array.isArray(object.dependency)) - throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); - message.dependency = []; - for (var i = 0; i < object.dependency.length; ++i) - message.dependency[i] = String(object.dependency[i]); - } - if (object.publicDependency) { - if (!Array.isArray(object.publicDependency)) - throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); - message.publicDependency = []; - for (var i = 0; i < object.publicDependency.length; ++i) - message.publicDependency[i] = object.publicDependency[i] | 0; - } - if (object.weakDependency) { - if (!Array.isArray(object.weakDependency)) - throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); - message.weakDependency = []; - for (var i = 0; i < object.weakDependency.length; ++i) - message.weakDependency[i] = object.weakDependency[i] | 0; - } - if (object.messageType) { - if (!Array.isArray(object.messageType)) - throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); - message.messageType = []; - for (var i = 0; i < object.messageType.length; ++i) { - if (typeof object.messageType[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); - message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); - } - } - if (object.enumType) { - if (!Array.isArray(object.enumType)) - throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); - message.enumType = []; - for (var i = 0; i < object.enumType.length; ++i) { - if (typeof object.enumType[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); - message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); - } - } - if (object.service) { - if (!Array.isArray(object.service)) - throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); - message.service = []; - for (var i = 0; i < object.service.length; ++i) { - if (typeof object.service[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); - message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); - } - } - if (object.extension) { - if (!Array.isArray(object.extension)) - throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); - message.extension = []; - for (var i = 0; i < object.extension.length; ++i) { - if (typeof object.extension[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); - message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.FileOptions.fromObject(object.options); - } - if (object.sourceCodeInfo != null) { - if (typeof object.sourceCodeInfo !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); - message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); - } - if (object.syntax != null) - message.syntax = String(object.syntax); - return message; - }; - - /** - * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FileDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.dependency = []; - object.messageType = []; - object.enumType = []; - object.service = []; - object.extension = []; - object.publicDependency = []; - object.weakDependency = []; - } - if (options.defaults) { - object.name = ""; - object["package"] = ""; - object.options = null; - object.sourceCodeInfo = null; - object.syntax = ""; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message["package"] != null && message.hasOwnProperty("package")) - object["package"] = message["package"]; - if (message.dependency && message.dependency.length) { - object.dependency = []; - for (var j = 0; j < message.dependency.length; ++j) - object.dependency[j] = message.dependency[j]; - } - if (message.messageType && message.messageType.length) { - object.messageType = []; - for (var j = 0; j < message.messageType.length; ++j) - object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); - } - if (message.enumType && message.enumType.length) { - object.enumType = []; - for (var j = 0; j < message.enumType.length; ++j) - object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); - } - if (message.service && message.service.length) { - object.service = []; - for (var j = 0; j < message.service.length; ++j) - object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); - } - if (message.extension && message.extension.length) { - object.extension = []; - for (var j = 0; j < message.extension.length; ++j) - object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); - if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) - object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); - if (message.publicDependency && message.publicDependency.length) { - object.publicDependency = []; - for (var j = 0; j < message.publicDependency.length; ++j) - object.publicDependency[j] = message.publicDependency[j]; - } - if (message.weakDependency && message.weakDependency.length) { - object.weakDependency = []; - for (var j = 0; j < message.weakDependency.length; ++j) - object.weakDependency[j] = message.weakDependency[j]; - } - if (message.syntax != null && message.hasOwnProperty("syntax")) - object.syntax = message.syntax; - return object; - }; - - /** - * Converts this FileDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.FileDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - FileDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return FileDescriptorProto; - })(); - - protobuf.DescriptorProto = (function() { - - /** - * Properties of a DescriptorProto. - * @memberof google.protobuf - * @interface IDescriptorProto - * @property {string|null} [name] DescriptorProto name - * @property {Array.|null} [field] DescriptorProto field - * @property {Array.|null} [extension] DescriptorProto extension - * @property {Array.|null} [nestedType] DescriptorProto nestedType - * @property {Array.|null} [enumType] DescriptorProto enumType - * @property {Array.|null} [extensionRange] DescriptorProto extensionRange - * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl - * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options - * @property {Array.|null} [reservedRange] DescriptorProto reservedRange - * @property {Array.|null} [reservedName] DescriptorProto reservedName - */ - - /** - * Constructs a new DescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a DescriptorProto. - * @implements IDescriptorProto - * @constructor - * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set - */ - function DescriptorProto(properties) { - this.field = []; - this.extension = []; - this.nestedType = []; - this.enumType = []; - this.extensionRange = []; - this.oneofDecl = []; - this.reservedRange = []; - this.reservedName = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DescriptorProto name. - * @member {string} name - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.name = ""; - - /** - * DescriptorProto field. - * @member {Array.} field - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.field = $util.emptyArray; - - /** - * DescriptorProto extension. - * @member {Array.} extension - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.extension = $util.emptyArray; - - /** - * DescriptorProto nestedType. - * @member {Array.} nestedType - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.nestedType = $util.emptyArray; - - /** - * DescriptorProto enumType. - * @member {Array.} enumType - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.enumType = $util.emptyArray; - - /** - * DescriptorProto extensionRange. - * @member {Array.} extensionRange - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.extensionRange = $util.emptyArray; - - /** - * DescriptorProto oneofDecl. - * @member {Array.} oneofDecl - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.oneofDecl = $util.emptyArray; - - /** - * DescriptorProto options. - * @member {google.protobuf.IMessageOptions|null|undefined} options - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.options = null; - - /** - * DescriptorProto reservedRange. - * @member {Array.} reservedRange - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.reservedRange = $util.emptyArray; - - /** - * DescriptorProto reservedName. - * @member {Array.} reservedName - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.reservedName = $util.emptyArray; - - /** - * Creates a new DescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.DescriptorProto - * @static - * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.DescriptorProto} DescriptorProto instance - */ - DescriptorProto.create = function create(properties) { - return new DescriptorProto(properties); - }; - - /** - * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.DescriptorProto - * @static - * @param {google.protobuf.IDescriptorProto} message DescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.field != null && message.field.length) - for (var i = 0; i < message.field.length; ++i) - $root.google.protobuf.FieldDescriptorProto.encode(message.field[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.nestedType != null && message.nestedType.length) - for (var i = 0; i < message.nestedType.length; ++i) - $root.google.protobuf.DescriptorProto.encode(message.nestedType[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.enumType != null && message.enumType.length) - for (var i = 0; i < message.enumType.length; ++i) - $root.google.protobuf.EnumDescriptorProto.encode(message.enumType[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.extensionRange != null && message.extensionRange.length) - for (var i = 0; i < message.extensionRange.length; ++i) - $root.google.protobuf.DescriptorProto.ExtensionRange.encode(message.extensionRange[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.extension != null && message.extension.length) - for (var i = 0; i < message.extension.length; ++i) - $root.google.protobuf.FieldDescriptorProto.encode(message.extension[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.MessageOptions.encode(message.options, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - if (message.oneofDecl != null && message.oneofDecl.length) - for (var i = 0; i < message.oneofDecl.length; ++i) - $root.google.protobuf.OneofDescriptorProto.encode(message.oneofDecl[i], writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - if (message.reservedRange != null && message.reservedRange.length) - for (var i = 0; i < message.reservedRange.length; ++i) - $root.google.protobuf.DescriptorProto.ReservedRange.encode(message.reservedRange[i], writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); - if (message.reservedName != null && message.reservedName.length) - for (var i = 0; i < message.reservedName.length; ++i) - writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); - return writer; - }; - - /** - * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.DescriptorProto - * @static - * @param {google.protobuf.IDescriptorProto} message DescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.DescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.DescriptorProto} DescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - if (!(message.field && message.field.length)) - message.field = []; - message.field.push($root.google.protobuf.FieldDescriptorProto.decode(reader, reader.uint32())); - break; - case 6: - if (!(message.extension && message.extension.length)) - message.extension = []; - message.extension.push($root.google.protobuf.FieldDescriptorProto.decode(reader, reader.uint32())); - break; - case 3: - if (!(message.nestedType && message.nestedType.length)) - message.nestedType = []; - message.nestedType.push($root.google.protobuf.DescriptorProto.decode(reader, reader.uint32())); - break; - case 4: - if (!(message.enumType && message.enumType.length)) - message.enumType = []; - message.enumType.push($root.google.protobuf.EnumDescriptorProto.decode(reader, reader.uint32())); - break; - case 5: - if (!(message.extensionRange && message.extensionRange.length)) - message.extensionRange = []; - message.extensionRange.push($root.google.protobuf.DescriptorProto.ExtensionRange.decode(reader, reader.uint32())); - break; - case 8: - if (!(message.oneofDecl && message.oneofDecl.length)) - message.oneofDecl = []; - message.oneofDecl.push($root.google.protobuf.OneofDescriptorProto.decode(reader, reader.uint32())); - break; - case 7: - message.options = $root.google.protobuf.MessageOptions.decode(reader, reader.uint32()); - break; - case 9: - if (!(message.reservedRange && message.reservedRange.length)) - message.reservedRange = []; - message.reservedRange.push($root.google.protobuf.DescriptorProto.ReservedRange.decode(reader, reader.uint32())); - break; - case 10: - if (!(message.reservedName && message.reservedName.length)) - message.reservedName = []; - message.reservedName.push(reader.string()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.DescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.DescriptorProto} DescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DescriptorProto message. - * @function verify - * @memberof google.protobuf.DescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.field != null && message.hasOwnProperty("field")) { - if (!Array.isArray(message.field)) - return "field: array expected"; - for (var i = 0; i < message.field.length; ++i) { - var error = $root.google.protobuf.FieldDescriptorProto.verify(message.field[i]); - if (error) - return "field." + error; - } - } - if (message.extension != null && message.hasOwnProperty("extension")) { - if (!Array.isArray(message.extension)) - return "extension: array expected"; - for (var i = 0; i < message.extension.length; ++i) { - var error = $root.google.protobuf.FieldDescriptorProto.verify(message.extension[i]); - if (error) - return "extension." + error; - } - } - if (message.nestedType != null && message.hasOwnProperty("nestedType")) { - if (!Array.isArray(message.nestedType)) - return "nestedType: array expected"; - for (var i = 0; i < message.nestedType.length; ++i) { - var error = $root.google.protobuf.DescriptorProto.verify(message.nestedType[i]); - if (error) - return "nestedType." + error; - } - } - if (message.enumType != null && message.hasOwnProperty("enumType")) { - if (!Array.isArray(message.enumType)) - return "enumType: array expected"; - for (var i = 0; i < message.enumType.length; ++i) { - var error = $root.google.protobuf.EnumDescriptorProto.verify(message.enumType[i]); - if (error) - return "enumType." + error; - } - } - if (message.extensionRange != null && message.hasOwnProperty("extensionRange")) { - if (!Array.isArray(message.extensionRange)) - return "extensionRange: array expected"; - for (var i = 0; i < message.extensionRange.length; ++i) { - var error = $root.google.protobuf.DescriptorProto.ExtensionRange.verify(message.extensionRange[i]); - if (error) - return "extensionRange." + error; - } - } - if (message.oneofDecl != null && message.hasOwnProperty("oneofDecl")) { - if (!Array.isArray(message.oneofDecl)) - return "oneofDecl: array expected"; - for (var i = 0; i < message.oneofDecl.length; ++i) { - var error = $root.google.protobuf.OneofDescriptorProto.verify(message.oneofDecl[i]); - if (error) - return "oneofDecl." + error; - } - } - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.MessageOptions.verify(message.options); - if (error) - return "options." + error; - } - if (message.reservedRange != null && message.hasOwnProperty("reservedRange")) { - if (!Array.isArray(message.reservedRange)) - return "reservedRange: array expected"; - for (var i = 0; i < message.reservedRange.length; ++i) { - var error = $root.google.protobuf.DescriptorProto.ReservedRange.verify(message.reservedRange[i]); - if (error) - return "reservedRange." + error; - } - } - if (message.reservedName != null && message.hasOwnProperty("reservedName")) { - if (!Array.isArray(message.reservedName)) - return "reservedName: array expected"; - for (var i = 0; i < message.reservedName.length; ++i) - if (!$util.isString(message.reservedName[i])) - return "reservedName: string[] expected"; - } - return null; - }; - - /** - * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.DescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.DescriptorProto} DescriptorProto - */ - DescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DescriptorProto) - return object; - var message = new $root.google.protobuf.DescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.field) { - if (!Array.isArray(object.field)) - throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); - message.field = []; - for (var i = 0; i < object.field.length; ++i) { - if (typeof object.field[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); - message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); - } - } - if (object.extension) { - if (!Array.isArray(object.extension)) - throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); - message.extension = []; - for (var i = 0; i < object.extension.length; ++i) { - if (typeof object.extension[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); - message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); - } - } - if (object.nestedType) { - if (!Array.isArray(object.nestedType)) - throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); - message.nestedType = []; - for (var i = 0; i < object.nestedType.length; ++i) { - if (typeof object.nestedType[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); - message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); - } - } - if (object.enumType) { - if (!Array.isArray(object.enumType)) - throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); - message.enumType = []; - for (var i = 0; i < object.enumType.length; ++i) { - if (typeof object.enumType[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); - message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); - } - } - if (object.extensionRange) { - if (!Array.isArray(object.extensionRange)) - throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); - message.extensionRange = []; - for (var i = 0; i < object.extensionRange.length; ++i) { - if (typeof object.extensionRange[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); - message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); - } - } - if (object.oneofDecl) { - if (!Array.isArray(object.oneofDecl)) - throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); - message.oneofDecl = []; - for (var i = 0; i < object.oneofDecl.length; ++i) { - if (typeof object.oneofDecl[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); - message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); - message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); - } - if (object.reservedRange) { - if (!Array.isArray(object.reservedRange)) - throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); - message.reservedRange = []; - for (var i = 0; i < object.reservedRange.length; ++i) { - if (typeof object.reservedRange[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); - message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); - } - } - if (object.reservedName) { - if (!Array.isArray(object.reservedName)) - throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); - message.reservedName = []; - for (var i = 0; i < object.reservedName.length; ++i) - message.reservedName[i] = String(object.reservedName[i]); - } - return message; - }; - - /** - * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.DescriptorProto - * @static - * @param {google.protobuf.DescriptorProto} message DescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.field = []; - object.nestedType = []; - object.enumType = []; - object.extensionRange = []; - object.extension = []; - object.oneofDecl = []; - object.reservedRange = []; - object.reservedName = []; - } - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.field && message.field.length) { - object.field = []; - for (var j = 0; j < message.field.length; ++j) - object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); - } - if (message.nestedType && message.nestedType.length) { - object.nestedType = []; - for (var j = 0; j < message.nestedType.length; ++j) - object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); - } - if (message.enumType && message.enumType.length) { - object.enumType = []; - for (var j = 0; j < message.enumType.length; ++j) - object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); - } - if (message.extensionRange && message.extensionRange.length) { - object.extensionRange = []; - for (var j = 0; j < message.extensionRange.length; ++j) - object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); - } - if (message.extension && message.extension.length) { - object.extension = []; - for (var j = 0; j < message.extension.length; ++j) - object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); - if (message.oneofDecl && message.oneofDecl.length) { - object.oneofDecl = []; - for (var j = 0; j < message.oneofDecl.length; ++j) - object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); - } - if (message.reservedRange && message.reservedRange.length) { - object.reservedRange = []; - for (var j = 0; j < message.reservedRange.length; ++j) - object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); - } - if (message.reservedName && message.reservedName.length) { - object.reservedName = []; - for (var j = 0; j < message.reservedName.length; ++j) - object.reservedName[j] = message.reservedName[j]; - } - return object; - }; - - /** - * Converts this DescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.DescriptorProto - * @instance - * @returns {Object.} JSON object - */ - DescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - DescriptorProto.ExtensionRange = (function() { - - /** - * Properties of an ExtensionRange. - * @memberof google.protobuf.DescriptorProto - * @interface IExtensionRange - * @property {number|null} [start] ExtensionRange start - * @property {number|null} [end] ExtensionRange end - */ - - /** - * Constructs a new ExtensionRange. - * @memberof google.protobuf.DescriptorProto - * @classdesc Represents an ExtensionRange. - * @implements IExtensionRange - * @constructor - * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set - */ - function ExtensionRange(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ExtensionRange start. - * @member {number} start - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @instance - */ - ExtensionRange.prototype.start = 0; - - /** - * ExtensionRange end. - * @member {number} end - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @instance - */ - ExtensionRange.prototype.end = 0; - - /** - * Creates a new ExtensionRange instance using the specified properties. - * @function create - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set - * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange instance - */ - ExtensionRange.create = function create(properties) { - return new ExtensionRange(properties); - }; - - /** - * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. - * @function encode - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {google.protobuf.DescriptorProto.IExtensionRange} message ExtensionRange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExtensionRange.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.start != null && message.hasOwnProperty("start")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.start); - if (message.end != null && message.hasOwnProperty("end")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.end); - return writer; - }; - - /** - * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {google.protobuf.DescriptorProto.IExtensionRange} message ExtensionRange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExtensionRange.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an ExtensionRange message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExtensionRange.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.start = reader.int32(); - break; - case 2: - message.end = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExtensionRange.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an ExtensionRange message. - * @function verify - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExtensionRange.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.start != null && message.hasOwnProperty("start")) - if (!$util.isInteger(message.start)) - return "start: integer expected"; - if (message.end != null && message.hasOwnProperty("end")) - if (!$util.isInteger(message.end)) - return "end: integer expected"; - return null; - }; - - /** - * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange - */ - ExtensionRange.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) - return object; - var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); - if (object.start != null) - message.start = object.start | 0; - if (object.end != null) - message.end = object.end | 0; - return message; - }; - - /** - * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @static - * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExtensionRange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.start = 0; - object.end = 0; - } - if (message.start != null && message.hasOwnProperty("start")) - object.start = message.start; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; - return object; - }; - - /** - * Converts this ExtensionRange to JSON. - * @function toJSON - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @instance - * @returns {Object.} JSON object - */ - ExtensionRange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ExtensionRange; - })(); - - DescriptorProto.ReservedRange = (function() { - - /** - * Properties of a ReservedRange. - * @memberof google.protobuf.DescriptorProto - * @interface IReservedRange - * @property {number|null} [start] ReservedRange start - * @property {number|null} [end] ReservedRange end - */ - - /** - * Constructs a new ReservedRange. - * @memberof google.protobuf.DescriptorProto - * @classdesc Represents a ReservedRange. - * @implements IReservedRange - * @constructor - * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set - */ - function ReservedRange(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ReservedRange start. - * @member {number} start - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @instance - */ - ReservedRange.prototype.start = 0; - - /** - * ReservedRange end. - * @member {number} end - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @instance - */ - ReservedRange.prototype.end = 0; - - /** - * Creates a new ReservedRange instance using the specified properties. - * @function create - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set - * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange instance - */ - ReservedRange.create = function create(properties) { - return new ReservedRange(properties); - }; - - /** - * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. - * @function encode - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {google.protobuf.DescriptorProto.IReservedRange} message ReservedRange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ReservedRange.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.start != null && message.hasOwnProperty("start")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.start); - if (message.end != null && message.hasOwnProperty("end")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.end); - return writer; - }; - - /** - * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {google.protobuf.DescriptorProto.IReservedRange} message ReservedRange message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ReservedRange.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ReservedRange message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ReservedRange.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DescriptorProto.ReservedRange(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.start = reader.int32(); - break; - case 2: - message.end = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ReservedRange message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ReservedRange.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ReservedRange message. - * @function verify - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ReservedRange.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.start != null && message.hasOwnProperty("start")) - if (!$util.isInteger(message.start)) - return "start: integer expected"; - if (message.end != null && message.hasOwnProperty("end")) - if (!$util.isInteger(message.end)) - return "end: integer expected"; - return null; - }; - - /** - * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange - */ - ReservedRange.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) - return object; - var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); - if (object.start != null) - message.start = object.start | 0; - if (object.end != null) - message.end = object.end | 0; - return message; - }; - - /** - * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @static - * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ReservedRange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.start = 0; - object.end = 0; - } - if (message.start != null && message.hasOwnProperty("start")) - object.start = message.start; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; - return object; - }; - - /** - * Converts this ReservedRange to JSON. - * @function toJSON - * @memberof google.protobuf.DescriptorProto.ReservedRange - * @instance - * @returns {Object.} JSON object - */ - ReservedRange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ReservedRange; - })(); - - return DescriptorProto; - })(); - - protobuf.FieldDescriptorProto = (function() { - - /** - * Properties of a FieldDescriptorProto. - * @memberof google.protobuf - * @interface IFieldDescriptorProto - * @property {string|null} [name] FieldDescriptorProto name - * @property {number|null} [number] FieldDescriptorProto number - * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label - * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type - * @property {string|null} [typeName] FieldDescriptorProto typeName - * @property {string|null} [extendee] FieldDescriptorProto extendee - * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue - * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex - * @property {string|null} [jsonName] FieldDescriptorProto jsonName - * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options - */ - - /** - * Constructs a new FieldDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a FieldDescriptorProto. - * @implements IFieldDescriptorProto - * @constructor - * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set - */ - function FieldDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.name = ""; - - /** - * FieldDescriptorProto number. - * @member {number} number - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.number = 0; - - /** - * FieldDescriptorProto label. - * @member {google.protobuf.FieldDescriptorProto.Label} label - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.label = 1; - - /** - * FieldDescriptorProto type. - * @member {google.protobuf.FieldDescriptorProto.Type} type - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.type = 1; - - /** - * FieldDescriptorProto typeName. - * @member {string} typeName - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.typeName = ""; - - /** - * FieldDescriptorProto extendee. - * @member {string} extendee - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.extendee = ""; - - /** - * FieldDescriptorProto defaultValue. - * @member {string} defaultValue - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.defaultValue = ""; - - /** - * FieldDescriptorProto oneofIndex. - * @member {number} oneofIndex - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.oneofIndex = 0; - - /** - * FieldDescriptorProto jsonName. - * @member {string} jsonName - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.jsonName = ""; - - /** - * FieldDescriptorProto options. - * @member {google.protobuf.IFieldOptions|null|undefined} options - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.options = null; - - /** - * Creates a new FieldDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto instance - */ - FieldDescriptorProto.create = function create(properties) { - return new FieldDescriptorProto(properties); - }; - - /** - * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {google.protobuf.IFieldDescriptorProto} message FieldDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.extendee != null && message.hasOwnProperty("extendee")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.extendee); - if (message.number != null && message.hasOwnProperty("number")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.number); - if (message.label != null && message.hasOwnProperty("label")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.label); - if (message.type != null && message.hasOwnProperty("type")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.type); - if (message.typeName != null && message.hasOwnProperty("typeName")) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.typeName); - if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) - writer.uint32(/* id 7, wireType 2 =*/58).string(message.defaultValue); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.FieldOptions.encode(message.options, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) - writer.uint32(/* id 9, wireType 0 =*/72).int32(message.oneofIndex); - if (message.jsonName != null && message.hasOwnProperty("jsonName")) - writer.uint32(/* id 10, wireType 2 =*/82).string(message.jsonName); - return writer; - }; - - /** - * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {google.protobuf.IFieldDescriptorProto} message FieldDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FieldDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 3: - message.number = reader.int32(); - break; - case 4: - message.label = reader.int32(); - break; - case 5: - message.type = reader.int32(); - break; - case 6: - message.typeName = reader.string(); - break; - case 2: - message.extendee = reader.string(); - break; - case 7: - message.defaultValue = reader.string(); - break; - case 9: - message.oneofIndex = reader.int32(); - break; - case 10: - message.jsonName = reader.string(); - break; - case 8: - message.options = $root.google.protobuf.FieldOptions.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FieldDescriptorProto message. - * @function verify - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FieldDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.number != null && message.hasOwnProperty("number")) - if (!$util.isInteger(message.number)) - return "number: integer expected"; - if (message.label != null && message.hasOwnProperty("label")) - switch (message.label) { - default: - return "label: enum value expected"; - case 1: - case 2: - case 3: - break; - } - if (message.type != null && message.hasOwnProperty("type")) - switch (message.type) { - default: - return "type: enum value expected"; - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - break; - } - if (message.typeName != null && message.hasOwnProperty("typeName")) - if (!$util.isString(message.typeName)) - return "typeName: string expected"; - if (message.extendee != null && message.hasOwnProperty("extendee")) - if (!$util.isString(message.extendee)) - return "extendee: string expected"; - if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) - if (!$util.isString(message.defaultValue)) - return "defaultValue: string expected"; - if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) - if (!$util.isInteger(message.oneofIndex)) - return "oneofIndex: integer expected"; - if (message.jsonName != null && message.hasOwnProperty("jsonName")) - if (!$util.isString(message.jsonName)) - return "jsonName: string expected"; - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.FieldOptions.verify(message.options); - if (error) - return "options." + error; - } - return null; - }; - - /** - * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto - */ - FieldDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldDescriptorProto) - return object; - var message = new $root.google.protobuf.FieldDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.number != null) - message.number = object.number | 0; - switch (object.label) { - case "LABEL_OPTIONAL": - case 1: - message.label = 1; - break; - case "LABEL_REQUIRED": - case 2: - message.label = 2; - break; - case "LABEL_REPEATED": - case 3: - message.label = 3; - break; - } - switch (object.type) { - case "TYPE_DOUBLE": - case 1: - message.type = 1; - break; - case "TYPE_FLOAT": - case 2: - message.type = 2; - break; - case "TYPE_INT64": - case 3: - message.type = 3; - break; - case "TYPE_UINT64": - case 4: - message.type = 4; - break; - case "TYPE_INT32": - case 5: - message.type = 5; - break; - case "TYPE_FIXED64": - case 6: - message.type = 6; - break; - case "TYPE_FIXED32": - case 7: - message.type = 7; - break; - case "TYPE_BOOL": - case 8: - message.type = 8; - break; - case "TYPE_STRING": - case 9: - message.type = 9; - break; - case "TYPE_GROUP": - case 10: - message.type = 10; - break; - case "TYPE_MESSAGE": - case 11: - message.type = 11; - break; - case "TYPE_BYTES": - case 12: - message.type = 12; - break; - case "TYPE_UINT32": - case 13: - message.type = 13; - break; - case "TYPE_ENUM": - case 14: - message.type = 14; - break; - case "TYPE_SFIXED32": - case 15: - message.type = 15; - break; - case "TYPE_SFIXED64": - case 16: - message.type = 16; - break; - case "TYPE_SINT32": - case 17: - message.type = 17; - break; - case "TYPE_SINT64": - case 18: - message.type = 18; - break; - } - if (object.typeName != null) - message.typeName = String(object.typeName); - if (object.extendee != null) - message.extendee = String(object.extendee); - if (object.defaultValue != null) - message.defaultValue = String(object.defaultValue); - if (object.oneofIndex != null) - message.oneofIndex = object.oneofIndex | 0; - if (object.jsonName != null) - message.jsonName = String(object.jsonName); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); - } - return message; - }; - - /** - * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.extendee = ""; - object.number = 0; - object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; - object.type = options.enums === String ? "TYPE_DOUBLE" : 1; - object.typeName = ""; - object.defaultValue = ""; - object.options = null; - object.oneofIndex = 0; - object.jsonName = ""; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.extendee != null && message.hasOwnProperty("extendee")) - object.extendee = message.extendee; - if (message.number != null && message.hasOwnProperty("number")) - object.number = message.number; - if (message.label != null && message.hasOwnProperty("label")) - object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; - if (message.type != null && message.hasOwnProperty("type")) - object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; - if (message.typeName != null && message.hasOwnProperty("typeName")) - object.typeName = message.typeName; - if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) - object.defaultValue = message.defaultValue; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); - if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) - object.oneofIndex = message.oneofIndex; - if (message.jsonName != null && message.hasOwnProperty("jsonName")) - object.jsonName = message.jsonName; - return object; - }; - - /** - * Converts this FieldDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.FieldDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - FieldDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Type enum. - * @name google.protobuf.FieldDescriptorProto.Type - * @enum {string} - * @property {number} TYPE_DOUBLE=1 TYPE_DOUBLE value - * @property {number} TYPE_FLOAT=2 TYPE_FLOAT value - * @property {number} TYPE_INT64=3 TYPE_INT64 value - * @property {number} TYPE_UINT64=4 TYPE_UINT64 value - * @property {number} TYPE_INT32=5 TYPE_INT32 value - * @property {number} TYPE_FIXED64=6 TYPE_FIXED64 value - * @property {number} TYPE_FIXED32=7 TYPE_FIXED32 value - * @property {number} TYPE_BOOL=8 TYPE_BOOL value - * @property {number} TYPE_STRING=9 TYPE_STRING value - * @property {number} TYPE_GROUP=10 TYPE_GROUP value - * @property {number} TYPE_MESSAGE=11 TYPE_MESSAGE value - * @property {number} TYPE_BYTES=12 TYPE_BYTES value - * @property {number} TYPE_UINT32=13 TYPE_UINT32 value - * @property {number} TYPE_ENUM=14 TYPE_ENUM value - * @property {number} TYPE_SFIXED32=15 TYPE_SFIXED32 value - * @property {number} TYPE_SFIXED64=16 TYPE_SFIXED64 value - * @property {number} TYPE_SINT32=17 TYPE_SINT32 value - * @property {number} TYPE_SINT64=18 TYPE_SINT64 value - */ - FieldDescriptorProto.Type = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "TYPE_DOUBLE"] = 1; - values[valuesById[2] = "TYPE_FLOAT"] = 2; - values[valuesById[3] = "TYPE_INT64"] = 3; - values[valuesById[4] = "TYPE_UINT64"] = 4; - values[valuesById[5] = "TYPE_INT32"] = 5; - values[valuesById[6] = "TYPE_FIXED64"] = 6; - values[valuesById[7] = "TYPE_FIXED32"] = 7; - values[valuesById[8] = "TYPE_BOOL"] = 8; - values[valuesById[9] = "TYPE_STRING"] = 9; - values[valuesById[10] = "TYPE_GROUP"] = 10; - values[valuesById[11] = "TYPE_MESSAGE"] = 11; - values[valuesById[12] = "TYPE_BYTES"] = 12; - values[valuesById[13] = "TYPE_UINT32"] = 13; - values[valuesById[14] = "TYPE_ENUM"] = 14; - values[valuesById[15] = "TYPE_SFIXED32"] = 15; - values[valuesById[16] = "TYPE_SFIXED64"] = 16; - values[valuesById[17] = "TYPE_SINT32"] = 17; - values[valuesById[18] = "TYPE_SINT64"] = 18; - return values; - })(); - - /** - * Label enum. - * @name google.protobuf.FieldDescriptorProto.Label - * @enum {string} - * @property {number} LABEL_OPTIONAL=1 LABEL_OPTIONAL value - * @property {number} LABEL_REQUIRED=2 LABEL_REQUIRED value - * @property {number} LABEL_REPEATED=3 LABEL_REPEATED value - */ - FieldDescriptorProto.Label = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "LABEL_OPTIONAL"] = 1; - values[valuesById[2] = "LABEL_REQUIRED"] = 2; - values[valuesById[3] = "LABEL_REPEATED"] = 3; - return values; - })(); - - return FieldDescriptorProto; - })(); - - protobuf.OneofDescriptorProto = (function() { - - /** - * Properties of an OneofDescriptorProto. - * @memberof google.protobuf - * @interface IOneofDescriptorProto - * @property {string|null} [name] OneofDescriptorProto name - * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options - */ - - /** - * Constructs a new OneofDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents an OneofDescriptorProto. - * @implements IOneofDescriptorProto - * @constructor - * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set - */ - function OneofDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * OneofDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.OneofDescriptorProto - * @instance - */ - OneofDescriptorProto.prototype.name = ""; - - /** - * OneofDescriptorProto options. - * @member {google.protobuf.IOneofOptions|null|undefined} options - * @memberof google.protobuf.OneofDescriptorProto - * @instance - */ - OneofDescriptorProto.prototype.options = null; - - /** - * Creates a new OneofDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto instance - */ - OneofDescriptorProto.create = function create(properties) { - return new OneofDescriptorProto(properties); - }; - - /** - * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {google.protobuf.IOneofDescriptorProto} message OneofDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - OneofDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.OneofOptions.encode(message.options, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {google.protobuf.IOneofDescriptorProto} message OneofDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - OneofDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an OneofDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - OneofDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.OneofDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - message.options = $root.google.protobuf.OneofOptions.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - OneofDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an OneofDescriptorProto message. - * @function verify - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - OneofDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.OneofOptions.verify(message.options); - if (error) - return "options." + error; - } - return null; - }; - - /** - * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto - */ - OneofDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.OneofDescriptorProto) - return object; - var message = new $root.google.protobuf.OneofDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); - } - return message; - }; - - /** - * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - OneofDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); - return object; - }; - - /** - * Converts this OneofDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.OneofDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - OneofDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return OneofDescriptorProto; - })(); - - protobuf.EnumDescriptorProto = (function() { - - /** - * Properties of an EnumDescriptorProto. - * @memberof google.protobuf - * @interface IEnumDescriptorProto - * @property {string|null} [name] EnumDescriptorProto name - * @property {Array.|null} [value] EnumDescriptorProto value - * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options - */ - - /** - * Constructs a new EnumDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents an EnumDescriptorProto. - * @implements IEnumDescriptorProto - * @constructor - * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set - */ - function EnumDescriptorProto(properties) { - this.value = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * EnumDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.name = ""; - - /** - * EnumDescriptorProto value. - * @member {Array.} value - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.value = $util.emptyArray; - - /** - * EnumDescriptorProto options. - * @member {google.protobuf.IEnumOptions|null|undefined} options - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.options = null; - - /** - * Creates a new EnumDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto instance - */ - EnumDescriptorProto.create = function create(properties) { - return new EnumDescriptorProto(properties); - }; - - /** - * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {google.protobuf.IEnumDescriptorProto} message EnumDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.value != null && message.value.length) - for (var i = 0; i < message.value.length; ++i) - $root.google.protobuf.EnumValueDescriptorProto.encode(message.value[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.EnumOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {google.protobuf.IEnumDescriptorProto} message EnumDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an EnumDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - if (!(message.value && message.value.length)) - message.value = []; - message.value.push($root.google.protobuf.EnumValueDescriptorProto.decode(reader, reader.uint32())); - break; - case 3: - message.options = $root.google.protobuf.EnumOptions.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an EnumDescriptorProto message. - * @function verify - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - EnumDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.value != null && message.hasOwnProperty("value")) { - if (!Array.isArray(message.value)) - return "value: array expected"; - for (var i = 0; i < message.value.length; ++i) { - var error = $root.google.protobuf.EnumValueDescriptorProto.verify(message.value[i]); - if (error) - return "value." + error; - } - } - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.EnumOptions.verify(message.options); - if (error) - return "options." + error; - } - return null; - }; - - /** - * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto - */ - EnumDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumDescriptorProto) - return object; - var message = new $root.google.protobuf.EnumDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.value) { - if (!Array.isArray(object.value)) - throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); - message.value = []; - for (var i = 0; i < object.value.length; ++i) { - if (typeof object.value[i] !== "object") - throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); - message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); - } - return message; - }; - - /** - * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.value = []; - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.value && message.value.length) { - object.value = []; - for (var j = 0; j < message.value.length; ++j) - object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); - return object; - }; - - /** - * Converts this EnumDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.EnumDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - EnumDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return EnumDescriptorProto; - })(); - - protobuf.EnumValueDescriptorProto = (function() { - - /** - * Properties of an EnumValueDescriptorProto. - * @memberof google.protobuf - * @interface IEnumValueDescriptorProto - * @property {string|null} [name] EnumValueDescriptorProto name - * @property {number|null} [number] EnumValueDescriptorProto number - * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options - */ - - /** - * Constructs a new EnumValueDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents an EnumValueDescriptorProto. - * @implements IEnumValueDescriptorProto - * @constructor - * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set - */ - function EnumValueDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * EnumValueDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - */ - EnumValueDescriptorProto.prototype.name = ""; - - /** - * EnumValueDescriptorProto number. - * @member {number} number - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - */ - EnumValueDescriptorProto.prototype.number = 0; - - /** - * EnumValueDescriptorProto options. - * @member {google.protobuf.IEnumValueOptions|null|undefined} options - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - */ - EnumValueDescriptorProto.prototype.options = null; - - /** - * Creates a new EnumValueDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto instance - */ - EnumValueDescriptorProto.create = function create(properties) { - return new EnumValueDescriptorProto(properties); - }; - - /** - * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {google.protobuf.IEnumValueDescriptorProto} message EnumValueDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumValueDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.number != null && message.hasOwnProperty("number")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.number); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.EnumValueOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {google.protobuf.IEnumValueDescriptorProto} message EnumValueDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumValueDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumValueDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumValueDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - message.number = reader.int32(); - break; - case 3: - message.options = $root.google.protobuf.EnumValueOptions.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumValueDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an EnumValueDescriptorProto message. - * @function verify - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - EnumValueDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.number != null && message.hasOwnProperty("number")) - if (!$util.isInteger(message.number)) - return "number: integer expected"; - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.EnumValueOptions.verify(message.options); - if (error) - return "options." + error; - } - return null; - }; - - /** - * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto - */ - EnumValueDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) - return object; - var message = new $root.google.protobuf.EnumValueDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.number != null) - message.number = object.number | 0; - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); - } - return message; - }; - - /** - * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumValueDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.number = 0; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.number != null && message.hasOwnProperty("number")) - object.number = message.number; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); - return object; - }; - - /** - * Converts this EnumValueDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - EnumValueDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return EnumValueDescriptorProto; - })(); - - protobuf.ServiceDescriptorProto = (function() { - - /** - * Properties of a ServiceDescriptorProto. - * @memberof google.protobuf - * @interface IServiceDescriptorProto - * @property {string|null} [name] ServiceDescriptorProto name - * @property {Array.|null} [method] ServiceDescriptorProto method - * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options - */ - - /** - * Constructs a new ServiceDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a ServiceDescriptorProto. - * @implements IServiceDescriptorProto - * @constructor - * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set - */ - function ServiceDescriptorProto(properties) { - this.method = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ServiceDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - */ - ServiceDescriptorProto.prototype.name = ""; - - /** - * ServiceDescriptorProto method. - * @member {Array.} method - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - */ - ServiceDescriptorProto.prototype.method = $util.emptyArray; - - /** - * ServiceDescriptorProto options. - * @member {google.protobuf.IServiceOptions|null|undefined} options - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - */ - ServiceDescriptorProto.prototype.options = null; - - /** - * Creates a new ServiceDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto instance - */ - ServiceDescriptorProto.create = function create(properties) { - return new ServiceDescriptorProto(properties); - }; - - /** - * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {google.protobuf.IServiceDescriptorProto} message ServiceDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ServiceDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.method != null && message.method.length) - for (var i = 0; i < message.method.length; ++i) - $root.google.protobuf.MethodDescriptorProto.encode(message.method[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.ServiceOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {google.protobuf.IServiceDescriptorProto} message ServiceDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ServiceDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ServiceDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ServiceDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ServiceDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - if (!(message.method && message.method.length)) - message.method = []; - message.method.push($root.google.protobuf.MethodDescriptorProto.decode(reader, reader.uint32())); - break; - case 3: - message.options = $root.google.protobuf.ServiceOptions.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ServiceDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ServiceDescriptorProto message. - * @function verify - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ServiceDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.method != null && message.hasOwnProperty("method")) { - if (!Array.isArray(message.method)) - return "method: array expected"; - for (var i = 0; i < message.method.length; ++i) { - var error = $root.google.protobuf.MethodDescriptorProto.verify(message.method[i]); - if (error) - return "method." + error; - } - } - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.ServiceOptions.verify(message.options); - if (error) - return "options." + error; - } - return null; - }; - - /** - * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto - */ - ServiceDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ServiceDescriptorProto) - return object; - var message = new $root.google.protobuf.ServiceDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.method) { - if (!Array.isArray(object.method)) - throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); - message.method = []; - for (var i = 0; i < object.method.length; ++i) { - if (typeof object.method[i] !== "object") - throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); - message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); - } - return message; - }; - - /** - * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ServiceDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.method = []; - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.method && message.method.length) { - object.method = []; - for (var j = 0; j < message.method.length; ++j) - object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); - return object; - }; - - /** - * Converts this ServiceDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - ServiceDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ServiceDescriptorProto; - })(); - - protobuf.MethodDescriptorProto = (function() { - - /** - * Properties of a MethodDescriptorProto. - * @memberof google.protobuf - * @interface IMethodDescriptorProto - * @property {string|null} [name] MethodDescriptorProto name - * @property {string|null} [inputType] MethodDescriptorProto inputType - * @property {string|null} [outputType] MethodDescriptorProto outputType - * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options - * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming - * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming - */ - - /** - * Constructs a new MethodDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a MethodDescriptorProto. - * @implements IMethodDescriptorProto - * @constructor - * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set - */ - function MethodDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * MethodDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.name = ""; - - /** - * MethodDescriptorProto inputType. - * @member {string} inputType - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.inputType = ""; - - /** - * MethodDescriptorProto outputType. - * @member {string} outputType - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.outputType = ""; - - /** - * MethodDescriptorProto options. - * @member {google.protobuf.IMethodOptions|null|undefined} options - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.options = null; - - /** - * MethodDescriptorProto clientStreaming. - * @member {boolean} clientStreaming - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.clientStreaming = false; - - /** - * MethodDescriptorProto serverStreaming. - * @member {boolean} serverStreaming - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.serverStreaming = false; - - /** - * Creates a new MethodDescriptorProto instance using the specified properties. - * @function create - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set - * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto instance - */ - MethodDescriptorProto.create = function create(properties) { - return new MethodDescriptorProto(properties); - }; - - /** - * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. - * @function encode - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {google.protobuf.IMethodDescriptorProto} message MethodDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MethodDescriptorProto.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.hasOwnProperty("name")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); - if (message.inputType != null && message.hasOwnProperty("inputType")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.inputType); - if (message.outputType != null && message.hasOwnProperty("outputType")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.outputType); - if (message.options != null && message.hasOwnProperty("options")) - $root.google.protobuf.MethodOptions.encode(message.options, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) - writer.uint32(/* id 5, wireType 0 =*/40).bool(message.clientStreaming); - if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) - writer.uint32(/* id 6, wireType 0 =*/48).bool(message.serverStreaming); - return writer; - }; - - /** - * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {google.protobuf.IMethodDescriptorProto} message MethodDescriptorProto message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MethodDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a MethodDescriptorProto message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MethodDescriptorProto.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.MethodDescriptorProto(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.name = reader.string(); - break; - case 2: - message.inputType = reader.string(); - break; - case 3: - message.outputType = reader.string(); - break; - case 4: - message.options = $root.google.protobuf.MethodOptions.decode(reader, reader.uint32()); - break; - case 5: - message.clientStreaming = reader.bool(); - break; - case 6: - message.serverStreaming = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MethodDescriptorProto.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a MethodDescriptorProto message. - * @function verify - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - MethodDescriptorProto.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.inputType != null && message.hasOwnProperty("inputType")) - if (!$util.isString(message.inputType)) - return "inputType: string expected"; - if (message.outputType != null && message.hasOwnProperty("outputType")) - if (!$util.isString(message.outputType)) - return "outputType: string expected"; - if (message.options != null && message.hasOwnProperty("options")) { - var error = $root.google.protobuf.MethodOptions.verify(message.options); - if (error) - return "options." + error; - } - if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) - if (typeof message.clientStreaming !== "boolean") - return "clientStreaming: boolean expected"; - if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) - if (typeof message.serverStreaming !== "boolean") - return "serverStreaming: boolean expected"; - return null; - }; - - /** - * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto - */ - MethodDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.MethodDescriptorProto) - return object; - var message = new $root.google.protobuf.MethodDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.inputType != null) - message.inputType = String(object.inputType); - if (object.outputType != null) - message.outputType = String(object.outputType); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); - } - if (object.clientStreaming != null) - message.clientStreaming = Boolean(object.clientStreaming); - if (object.serverStreaming != null) - message.serverStreaming = Boolean(object.serverStreaming); - return message; - }; - - /** - * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MethodDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.inputType = ""; - object.outputType = ""; - object.options = null; - object.clientStreaming = false; - object.serverStreaming = false; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.inputType != null && message.hasOwnProperty("inputType")) - object.inputType = message.inputType; - if (message.outputType != null && message.hasOwnProperty("outputType")) - object.outputType = message.outputType; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); - if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) - object.clientStreaming = message.clientStreaming; - if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) - object.serverStreaming = message.serverStreaming; - return object; - }; - - /** - * Converts this MethodDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.MethodDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - MethodDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return MethodDescriptorProto; - })(); - - protobuf.FileOptions = (function() { - - /** - * Properties of a FileOptions. - * @memberof google.protobuf - * @interface IFileOptions - * @property {string|null} [javaPackage] FileOptions javaPackage - * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname - * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles - * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash - * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 - * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor - * @property {string|null} [goPackage] FileOptions goPackage - * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices - * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices - * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices - * @property {boolean|null} [deprecated] FileOptions deprecated - * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas - * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix - * @property {string|null} [csharpNamespace] FileOptions csharpNamespace - * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption - */ - - /** - * Constructs a new FileOptions. - * @memberof google.protobuf - * @classdesc Represents a FileOptions. - * @implements IFileOptions - * @constructor - * @param {google.protobuf.IFileOptions=} [properties] Properties to set - */ - function FileOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FileOptions javaPackage. - * @member {string} javaPackage - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaPackage = ""; - - /** - * FileOptions javaOuterClassname. - * @member {string} javaOuterClassname - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaOuterClassname = ""; - - /** - * FileOptions javaMultipleFiles. - * @member {boolean} javaMultipleFiles - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaMultipleFiles = false; - - /** - * FileOptions javaGenerateEqualsAndHash. - * @member {boolean} javaGenerateEqualsAndHash - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaGenerateEqualsAndHash = false; - - /** - * FileOptions javaStringCheckUtf8. - * @member {boolean} javaStringCheckUtf8 - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaStringCheckUtf8 = false; - - /** - * FileOptions optimizeFor. - * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.optimizeFor = 1; - - /** - * FileOptions goPackage. - * @member {string} goPackage - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.goPackage = ""; - - /** - * FileOptions ccGenericServices. - * @member {boolean} ccGenericServices - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.ccGenericServices = false; - - /** - * FileOptions javaGenericServices. - * @member {boolean} javaGenericServices - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaGenericServices = false; - - /** - * FileOptions pyGenericServices. - * @member {boolean} pyGenericServices - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.pyGenericServices = false; - - /** - * FileOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.deprecated = false; - - /** - * FileOptions ccEnableArenas. - * @member {boolean} ccEnableArenas - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.ccEnableArenas = false; - - /** - * FileOptions objcClassPrefix. - * @member {string} objcClassPrefix - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.objcClassPrefix = ""; - - /** - * FileOptions csharpNamespace. - * @member {string} csharpNamespace - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.csharpNamespace = ""; - - /** - * FileOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new FileOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.FileOptions - * @static - * @param {google.protobuf.IFileOptions=} [properties] Properties to set - * @returns {google.protobuf.FileOptions} FileOptions instance - */ - FileOptions.create = function create(properties) { - return new FileOptions(properties); - }; - - /** - * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FileOptions - * @static - * @param {google.protobuf.IFileOptions} message FileOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FileOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.javaPackage); - if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) - writer.uint32(/* id 8, wireType 2 =*/66).string(message.javaOuterClassname); - if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) - writer.uint32(/* id 9, wireType 0 =*/72).int32(message.optimizeFor); - if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) - writer.uint32(/* id 10, wireType 0 =*/80).bool(message.javaMultipleFiles); - if (message.goPackage != null && message.hasOwnProperty("goPackage")) - writer.uint32(/* id 11, wireType 2 =*/90).string(message.goPackage); - if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) - writer.uint32(/* id 16, wireType 0 =*/128).bool(message.ccGenericServices); - if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) - writer.uint32(/* id 17, wireType 0 =*/136).bool(message.javaGenericServices); - if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) - writer.uint32(/* id 18, wireType 0 =*/144).bool(message.pyGenericServices); - if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) - writer.uint32(/* id 20, wireType 0 =*/160).bool(message.javaGenerateEqualsAndHash); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 23, wireType 0 =*/184).bool(message.deprecated); - if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) - writer.uint32(/* id 27, wireType 0 =*/216).bool(message.javaStringCheckUtf8); - if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) - writer.uint32(/* id 31, wireType 0 =*/248).bool(message.ccEnableArenas); - if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) - writer.uint32(/* id 36, wireType 2 =*/290).string(message.objcClassPrefix); - if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) - writer.uint32(/* id 37, wireType 2 =*/298).string(message.csharpNamespace); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FileOptions - * @static - * @param {google.protobuf.IFileOptions} message FileOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FileOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FileOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FileOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FileOptions} FileOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FileOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FileOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.javaPackage = reader.string(); - break; - case 8: - message.javaOuterClassname = reader.string(); - break; - case 10: - message.javaMultipleFiles = reader.bool(); - break; - case 20: - message.javaGenerateEqualsAndHash = reader.bool(); - break; - case 27: - message.javaStringCheckUtf8 = reader.bool(); - break; - case 9: - message.optimizeFor = reader.int32(); - break; - case 11: - message.goPackage = reader.string(); - break; - case 16: - message.ccGenericServices = reader.bool(); - break; - case 17: - message.javaGenericServices = reader.bool(); - break; - case 18: - message.pyGenericServices = reader.bool(); - break; - case 23: - message.deprecated = reader.bool(); - break; - case 31: - message.ccEnableArenas = reader.bool(); - break; - case 36: - message.objcClassPrefix = reader.string(); - break; - case 37: - message.csharpNamespace = reader.string(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FileOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FileOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FileOptions} FileOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FileOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FileOptions message. - * @function verify - * @memberof google.protobuf.FileOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FileOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) - if (!$util.isString(message.javaPackage)) - return "javaPackage: string expected"; - if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) - if (!$util.isString(message.javaOuterClassname)) - return "javaOuterClassname: string expected"; - if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) - if (typeof message.javaMultipleFiles !== "boolean") - return "javaMultipleFiles: boolean expected"; - if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) - if (typeof message.javaGenerateEqualsAndHash !== "boolean") - return "javaGenerateEqualsAndHash: boolean expected"; - if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) - if (typeof message.javaStringCheckUtf8 !== "boolean") - return "javaStringCheckUtf8: boolean expected"; - if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) - switch (message.optimizeFor) { - default: - return "optimizeFor: enum value expected"; - case 1: - case 2: - case 3: - break; - } - if (message.goPackage != null && message.hasOwnProperty("goPackage")) - if (!$util.isString(message.goPackage)) - return "goPackage: string expected"; - if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) - if (typeof message.ccGenericServices !== "boolean") - return "ccGenericServices: boolean expected"; - if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) - if (typeof message.javaGenericServices !== "boolean") - return "javaGenericServices: boolean expected"; - if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) - if (typeof message.pyGenericServices !== "boolean") - return "pyGenericServices: boolean expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) - if (typeof message.ccEnableArenas !== "boolean") - return "ccEnableArenas: boolean expected"; - if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) - if (!$util.isString(message.objcClassPrefix)) - return "objcClassPrefix: string expected"; - if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) - if (!$util.isString(message.csharpNamespace)) - return "csharpNamespace: string expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FileOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FileOptions} FileOptions - */ - FileOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FileOptions) - return object; - var message = new $root.google.protobuf.FileOptions(); - if (object.javaPackage != null) - message.javaPackage = String(object.javaPackage); - if (object.javaOuterClassname != null) - message.javaOuterClassname = String(object.javaOuterClassname); - if (object.javaMultipleFiles != null) - message.javaMultipleFiles = Boolean(object.javaMultipleFiles); - if (object.javaGenerateEqualsAndHash != null) - message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); - if (object.javaStringCheckUtf8 != null) - message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); - switch (object.optimizeFor) { - case "SPEED": - case 1: - message.optimizeFor = 1; - break; - case "CODE_SIZE": - case 2: - message.optimizeFor = 2; - break; - case "LITE_RUNTIME": - case 3: - message.optimizeFor = 3; - break; - } - if (object.goPackage != null) - message.goPackage = String(object.goPackage); - if (object.ccGenericServices != null) - message.ccGenericServices = Boolean(object.ccGenericServices); - if (object.javaGenericServices != null) - message.javaGenericServices = Boolean(object.javaGenericServices); - if (object.pyGenericServices != null) - message.pyGenericServices = Boolean(object.pyGenericServices); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.ccEnableArenas != null) - message.ccEnableArenas = Boolean(object.ccEnableArenas); - if (object.objcClassPrefix != null) - message.objcClassPrefix = String(object.objcClassPrefix); - if (object.csharpNamespace != null) - message.csharpNamespace = String(object.csharpNamespace); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a FileOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FileOptions - * @static - * @param {google.protobuf.FileOptions} message FileOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FileOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.javaPackage = ""; - object.javaOuterClassname = ""; - object.optimizeFor = options.enums === String ? "SPEED" : 1; - object.javaMultipleFiles = false; - object.goPackage = ""; - object.ccGenericServices = false; - object.javaGenericServices = false; - object.pyGenericServices = false; - object.javaGenerateEqualsAndHash = false; - object.deprecated = false; - object.javaStringCheckUtf8 = false; - object.ccEnableArenas = false; - object.objcClassPrefix = ""; - object.csharpNamespace = ""; - } - if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) - object.javaPackage = message.javaPackage; - if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) - object.javaOuterClassname = message.javaOuterClassname; - if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) - object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; - if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) - object.javaMultipleFiles = message.javaMultipleFiles; - if (message.goPackage != null && message.hasOwnProperty("goPackage")) - object.goPackage = message.goPackage; - if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) - object.ccGenericServices = message.ccGenericServices; - if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) - object.javaGenericServices = message.javaGenericServices; - if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) - object.pyGenericServices = message.pyGenericServices; - if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) - object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) - object.javaStringCheckUtf8 = message.javaStringCheckUtf8; - if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) - object.ccEnableArenas = message.ccEnableArenas; - if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) - object.objcClassPrefix = message.objcClassPrefix; - if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) - object.csharpNamespace = message.csharpNamespace; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this FileOptions to JSON. - * @function toJSON - * @memberof google.protobuf.FileOptions - * @instance - * @returns {Object.} JSON object - */ - FileOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * OptimizeMode enum. - * @name google.protobuf.FileOptions.OptimizeMode - * @enum {string} - * @property {number} SPEED=1 SPEED value - * @property {number} CODE_SIZE=2 CODE_SIZE value - * @property {number} LITE_RUNTIME=3 LITE_RUNTIME value - */ - FileOptions.OptimizeMode = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "SPEED"] = 1; - values[valuesById[2] = "CODE_SIZE"] = 2; - values[valuesById[3] = "LITE_RUNTIME"] = 3; - return values; - })(); - - return FileOptions; - })(); - - protobuf.MessageOptions = (function() { - - /** - * Properties of a MessageOptions. - * @memberof google.protobuf - * @interface IMessageOptions - * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat - * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor - * @property {boolean|null} [deprecated] MessageOptions deprecated - * @property {boolean|null} [mapEntry] MessageOptions mapEntry - * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption - */ - - /** - * Constructs a new MessageOptions. - * @memberof google.protobuf - * @classdesc Represents a MessageOptions. - * @implements IMessageOptions - * @constructor - * @param {google.protobuf.IMessageOptions=} [properties] Properties to set - */ - function MessageOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * MessageOptions messageSetWireFormat. - * @member {boolean} messageSetWireFormat - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.messageSetWireFormat = false; - - /** - * MessageOptions noStandardDescriptorAccessor. - * @member {boolean} noStandardDescriptorAccessor - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.noStandardDescriptorAccessor = false; - - /** - * MessageOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.deprecated = false; - - /** - * MessageOptions mapEntry. - * @member {boolean} mapEntry - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.mapEntry = false; - - /** - * MessageOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new MessageOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.MessageOptions - * @static - * @param {google.protobuf.IMessageOptions=} [properties] Properties to set - * @returns {google.protobuf.MessageOptions} MessageOptions instance - */ - MessageOptions.create = function create(properties) { - return new MessageOptions(properties); - }; - - /** - * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.MessageOptions - * @static - * @param {google.protobuf.IMessageOptions} message MessageOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MessageOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) - writer.uint32(/* id 1, wireType 0 =*/8).bool(message.messageSetWireFormat); - if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) - writer.uint32(/* id 2, wireType 0 =*/16).bool(message.noStandardDescriptorAccessor); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 3, wireType 0 =*/24).bool(message.deprecated); - if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) - writer.uint32(/* id 7, wireType 0 =*/56).bool(message.mapEntry); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.MessageOptions - * @static - * @param {google.protobuf.IMessageOptions} message MessageOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MessageOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a MessageOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.MessageOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.MessageOptions} MessageOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MessageOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.MessageOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.messageSetWireFormat = reader.bool(); - break; - case 2: - message.noStandardDescriptorAccessor = reader.bool(); - break; - case 3: - message.deprecated = reader.bool(); - break; - case 7: - message.mapEntry = reader.bool(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a MessageOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.MessageOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.MessageOptions} MessageOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MessageOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a MessageOptions message. - * @function verify - * @memberof google.protobuf.MessageOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - MessageOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) - if (typeof message.messageSetWireFormat !== "boolean") - return "messageSetWireFormat: boolean expected"; - if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) - if (typeof message.noStandardDescriptorAccessor !== "boolean") - return "noStandardDescriptorAccessor: boolean expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) - if (typeof message.mapEntry !== "boolean") - return "mapEntry: boolean expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.MessageOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.MessageOptions} MessageOptions - */ - MessageOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.MessageOptions) - return object; - var message = new $root.google.protobuf.MessageOptions(); - if (object.messageSetWireFormat != null) - message.messageSetWireFormat = Boolean(object.messageSetWireFormat); - if (object.noStandardDescriptorAccessor != null) - message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.mapEntry != null) - message.mapEntry = Boolean(object.mapEntry); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.MessageOptions - * @static - * @param {google.protobuf.MessageOptions} message MessageOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MessageOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.messageSetWireFormat = false; - object.noStandardDescriptorAccessor = false; - object.deprecated = false; - object.mapEntry = false; - } - if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) - object.messageSetWireFormat = message.messageSetWireFormat; - if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) - object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) - object.mapEntry = message.mapEntry; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this MessageOptions to JSON. - * @function toJSON - * @memberof google.protobuf.MessageOptions - * @instance - * @returns {Object.} JSON object - */ - MessageOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return MessageOptions; - })(); - - protobuf.FieldOptions = (function() { - - /** - * Properties of a FieldOptions. - * @memberof google.protobuf - * @interface IFieldOptions - * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype - * @property {boolean|null} [packed] FieldOptions packed - * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype - * @property {boolean|null} [lazy] FieldOptions lazy - * @property {boolean|null} [deprecated] FieldOptions deprecated - * @property {boolean|null} [weak] FieldOptions weak - * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption - */ - - /** - * Constructs a new FieldOptions. - * @memberof google.protobuf - * @classdesc Represents a FieldOptions. - * @implements IFieldOptions - * @constructor - * @param {google.protobuf.IFieldOptions=} [properties] Properties to set - */ - function FieldOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldOptions ctype. - * @member {google.protobuf.FieldOptions.CType} ctype - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.ctype = 0; - - /** - * FieldOptions packed. - * @member {boolean} packed - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.packed = false; - - /** - * FieldOptions jstype. - * @member {google.protobuf.FieldOptions.JSType} jstype - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.jstype = 0; - - /** - * FieldOptions lazy. - * @member {boolean} lazy - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.lazy = false; - - /** - * FieldOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.deprecated = false; - - /** - * FieldOptions weak. - * @member {boolean} weak - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.weak = false; - - /** - * FieldOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new FieldOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.FieldOptions - * @static - * @param {google.protobuf.IFieldOptions=} [properties] Properties to set - * @returns {google.protobuf.FieldOptions} FieldOptions instance - */ - FieldOptions.create = function create(properties) { - return new FieldOptions(properties); - }; - - /** - * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FieldOptions - * @static - * @param {google.protobuf.IFieldOptions} message FieldOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.ctype != null && message.hasOwnProperty("ctype")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.ctype); - if (message.packed != null && message.hasOwnProperty("packed")) - writer.uint32(/* id 2, wireType 0 =*/16).bool(message.packed); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 3, wireType 0 =*/24).bool(message.deprecated); - if (message.lazy != null && message.hasOwnProperty("lazy")) - writer.uint32(/* id 5, wireType 0 =*/40).bool(message.lazy); - if (message.jstype != null && message.hasOwnProperty("jstype")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jstype); - if (message.weak != null && message.hasOwnProperty("weak")) - writer.uint32(/* id 10, wireType 0 =*/80).bool(message.weak); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FieldOptions - * @static - * @param {google.protobuf.IFieldOptions} message FieldOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FieldOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FieldOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FieldOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FieldOptions} FieldOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.ctype = reader.int32(); - break; - case 2: - message.packed = reader.bool(); - break; - case 6: - message.jstype = reader.int32(); - break; - case 5: - message.lazy = reader.bool(); - break; - case 3: - message.deprecated = reader.bool(); - break; - case 10: - message.weak = reader.bool(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FieldOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FieldOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FieldOptions} FieldOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FieldOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FieldOptions message. - * @function verify - * @memberof google.protobuf.FieldOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FieldOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.ctype != null && message.hasOwnProperty("ctype")) - switch (message.ctype) { - default: - return "ctype: enum value expected"; - case 0: - case 1: - case 2: - break; - } - if (message.packed != null && message.hasOwnProperty("packed")) - if (typeof message.packed !== "boolean") - return "packed: boolean expected"; - if (message.jstype != null && message.hasOwnProperty("jstype")) - switch (message.jstype) { - default: - return "jstype: enum value expected"; - case 0: - case 1: - case 2: - break; - } - if (message.lazy != null && message.hasOwnProperty("lazy")) - if (typeof message.lazy !== "boolean") - return "lazy: boolean expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.weak != null && message.hasOwnProperty("weak")) - if (typeof message.weak !== "boolean") - return "weak: boolean expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldOptions} FieldOptions - */ - FieldOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldOptions) - return object; - var message = new $root.google.protobuf.FieldOptions(); - switch (object.ctype) { - case "STRING": - case 0: - message.ctype = 0; - break; - case "CORD": - case 1: - message.ctype = 1; - break; - case "STRING_PIECE": - case 2: - message.ctype = 2; - break; - } - if (object.packed != null) - message.packed = Boolean(object.packed); - switch (object.jstype) { - case "JS_NORMAL": - case 0: - message.jstype = 0; - break; - case "JS_STRING": - case 1: - message.jstype = 1; - break; - case "JS_NUMBER": - case 2: - message.jstype = 2; - break; - } - if (object.lazy != null) - message.lazy = Boolean(object.lazy); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.weak != null) - message.weak = Boolean(object.weak); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldOptions - * @static - * @param {google.protobuf.FieldOptions} message FieldOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.ctype = options.enums === String ? "STRING" : 0; - object.packed = false; - object.deprecated = false; - object.lazy = false; - object.jstype = options.enums === String ? "JS_NORMAL" : 0; - object.weak = false; - } - if (message.ctype != null && message.hasOwnProperty("ctype")) - object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; - if (message.packed != null && message.hasOwnProperty("packed")) - object.packed = message.packed; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.lazy != null && message.hasOwnProperty("lazy")) - object.lazy = message.lazy; - if (message.jstype != null && message.hasOwnProperty("jstype")) - object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; - if (message.weak != null && message.hasOwnProperty("weak")) - object.weak = message.weak; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this FieldOptions to JSON. - * @function toJSON - * @memberof google.protobuf.FieldOptions - * @instance - * @returns {Object.} JSON object - */ - FieldOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * CType enum. - * @name google.protobuf.FieldOptions.CType - * @enum {string} - * @property {number} STRING=0 STRING value - * @property {number} CORD=1 CORD value - * @property {number} STRING_PIECE=2 STRING_PIECE value - */ - FieldOptions.CType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "STRING"] = 0; - values[valuesById[1] = "CORD"] = 1; - values[valuesById[2] = "STRING_PIECE"] = 2; - return values; - })(); - - /** - * JSType enum. - * @name google.protobuf.FieldOptions.JSType - * @enum {string} - * @property {number} JS_NORMAL=0 JS_NORMAL value - * @property {number} JS_STRING=1 JS_STRING value - * @property {number} JS_NUMBER=2 JS_NUMBER value - */ - FieldOptions.JSType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "JS_NORMAL"] = 0; - values[valuesById[1] = "JS_STRING"] = 1; - values[valuesById[2] = "JS_NUMBER"] = 2; - return values; - })(); - - return FieldOptions; - })(); - - protobuf.OneofOptions = (function() { - - /** - * Properties of an OneofOptions. - * @memberof google.protobuf - * @interface IOneofOptions - * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption - */ - - /** - * Constructs a new OneofOptions. - * @memberof google.protobuf - * @classdesc Represents an OneofOptions. - * @implements IOneofOptions - * @constructor - * @param {google.protobuf.IOneofOptions=} [properties] Properties to set - */ - function OneofOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * OneofOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.OneofOptions - * @instance - */ - OneofOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new OneofOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.IOneofOptions=} [properties] Properties to set - * @returns {google.protobuf.OneofOptions} OneofOptions instance - */ - OneofOptions.create = function create(properties) { - return new OneofOptions(properties); - }; - - /** - * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - OneofOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - OneofOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an OneofOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.OneofOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.OneofOptions} OneofOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - OneofOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.OneofOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an OneofOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.OneofOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.OneofOptions} OneofOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - OneofOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an OneofOptions message. - * @function verify - * @memberof google.protobuf.OneofOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - OneofOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.OneofOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.OneofOptions} OneofOptions - */ - OneofOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.OneofOptions) - return object; - var message = new $root.google.protobuf.OneofOptions(); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.OneofOptions} message OneofOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - OneofOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this OneofOptions to JSON. - * @function toJSON - * @memberof google.protobuf.OneofOptions - * @instance - * @returns {Object.} JSON object - */ - OneofOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return OneofOptions; - })(); - - protobuf.EnumOptions = (function() { - - /** - * Properties of an EnumOptions. - * @memberof google.protobuf - * @interface IEnumOptions - * @property {boolean|null} [allowAlias] EnumOptions allowAlias - * @property {boolean|null} [deprecated] EnumOptions deprecated - * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption - */ - - /** - * Constructs a new EnumOptions. - * @memberof google.protobuf - * @classdesc Represents an EnumOptions. - * @implements IEnumOptions - * @constructor - * @param {google.protobuf.IEnumOptions=} [properties] Properties to set - */ - function EnumOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * EnumOptions allowAlias. - * @member {boolean} allowAlias - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.allowAlias = false; - - /** - * EnumOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.deprecated = false; - - /** - * EnumOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new EnumOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.EnumOptions - * @static - * @param {google.protobuf.IEnumOptions=} [properties] Properties to set - * @returns {google.protobuf.EnumOptions} EnumOptions instance - */ - EnumOptions.create = function create(properties) { - return new EnumOptions(properties); - }; - - /** - * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.EnumOptions - * @static - * @param {google.protobuf.IEnumOptions} message EnumOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) - writer.uint32(/* id 2, wireType 0 =*/16).bool(message.allowAlias); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 3, wireType 0 =*/24).bool(message.deprecated); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.EnumOptions - * @static - * @param {google.protobuf.IEnumOptions} message EnumOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an EnumOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.EnumOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.EnumOptions} EnumOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - message.allowAlias = reader.bool(); - break; - case 3: - message.deprecated = reader.bool(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an EnumOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.EnumOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.EnumOptions} EnumOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an EnumOptions message. - * @function verify - * @memberof google.protobuf.EnumOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - EnumOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) - if (typeof message.allowAlias !== "boolean") - return "allowAlias: boolean expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumOptions} EnumOptions - */ - EnumOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumOptions) - return object; - var message = new $root.google.protobuf.EnumOptions(); - if (object.allowAlias != null) - message.allowAlias = Boolean(object.allowAlias); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumOptions - * @static - * @param {google.protobuf.EnumOptions} message EnumOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.allowAlias = false; - object.deprecated = false; - } - if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) - object.allowAlias = message.allowAlias; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this EnumOptions to JSON. - * @function toJSON - * @memberof google.protobuf.EnumOptions - * @instance - * @returns {Object.} JSON object - */ - EnumOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return EnumOptions; - })(); - - protobuf.EnumValueOptions = (function() { - - /** - * Properties of an EnumValueOptions. - * @memberof google.protobuf - * @interface IEnumValueOptions - * @property {boolean|null} [deprecated] EnumValueOptions deprecated - * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption - */ - - /** - * Constructs a new EnumValueOptions. - * @memberof google.protobuf - * @classdesc Represents an EnumValueOptions. - * @implements IEnumValueOptions - * @constructor - * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set - */ - function EnumValueOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * EnumValueOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.EnumValueOptions - * @instance - */ - EnumValueOptions.prototype.deprecated = false; - - /** - * EnumValueOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.EnumValueOptions - * @instance - */ - EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new EnumValueOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set - * @returns {google.protobuf.EnumValueOptions} EnumValueOptions instance - */ - EnumValueOptions.create = function create(properties) { - return new EnumValueOptions(properties); - }; - - /** - * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {google.protobuf.IEnumValueOptions} message EnumValueOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumValueOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 1, wireType 0 =*/8).bool(message.deprecated); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {google.protobuf.IEnumValueOptions} message EnumValueOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EnumValueOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an EnumValueOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.EnumValueOptions} EnumValueOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumValueOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.EnumValueOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.deprecated = reader.bool(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.EnumValueOptions} EnumValueOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EnumValueOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an EnumValueOptions message. - * @function verify - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - EnumValueOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumValueOptions} EnumValueOptions - */ - EnumValueOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumValueOptions) - return object; - var message = new $root.google.protobuf.EnumValueOptions(); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {google.protobuf.EnumValueOptions} message EnumValueOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumValueOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) - object.deprecated = false; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this EnumValueOptions to JSON. - * @function toJSON - * @memberof google.protobuf.EnumValueOptions - * @instance - * @returns {Object.} JSON object - */ - EnumValueOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return EnumValueOptions; - })(); - - protobuf.ServiceOptions = (function() { - - /** - * Properties of a ServiceOptions. - * @memberof google.protobuf - * @interface IServiceOptions - * @property {boolean|null} [deprecated] ServiceOptions deprecated - * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption - */ - - /** - * Constructs a new ServiceOptions. - * @memberof google.protobuf - * @classdesc Represents a ServiceOptions. - * @implements IServiceOptions - * @constructor - * @param {google.protobuf.IServiceOptions=} [properties] Properties to set - */ - function ServiceOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ServiceOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype.deprecated = false; - - /** - * ServiceOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates a new ServiceOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.ServiceOptions - * @static - * @param {google.protobuf.IServiceOptions=} [properties] Properties to set - * @returns {google.protobuf.ServiceOptions} ServiceOptions instance - */ - ServiceOptions.create = function create(properties) { - return new ServiceOptions(properties); - }; - - /** - * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.ServiceOptions - * @static - * @param {google.protobuf.IServiceOptions} message ServiceOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ServiceOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 33, wireType 0 =*/264).bool(message.deprecated); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.ServiceOptions - * @static - * @param {google.protobuf.IServiceOptions} message ServiceOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ServiceOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ServiceOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.ServiceOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.ServiceOptions} ServiceOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ServiceOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ServiceOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 33: - message.deprecated = reader.bool(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.ServiceOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.ServiceOptions} ServiceOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ServiceOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ServiceOptions message. - * @function verify - * @memberof google.protobuf.ServiceOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ServiceOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - return null; - }; - - /** - * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ServiceOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ServiceOptions} ServiceOptions - */ - ServiceOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ServiceOptions) - return object; - var message = new $root.google.protobuf.ServiceOptions(); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ServiceOptions - * @static - * @param {google.protobuf.ServiceOptions} message ServiceOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ServiceOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) - object.deprecated = false; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this ServiceOptions to JSON. - * @function toJSON - * @memberof google.protobuf.ServiceOptions - * @instance - * @returns {Object.} JSON object - */ - ServiceOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ServiceOptions; - })(); - - protobuf.MethodOptions = (function() { - - /** - * Properties of a MethodOptions. - * @memberof google.protobuf - * @interface IMethodOptions - * @property {boolean|null} [deprecated] MethodOptions deprecated - * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption - * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http - */ - - /** - * Constructs a new MethodOptions. - * @memberof google.protobuf - * @classdesc Represents a MethodOptions. - * @implements IMethodOptions - * @constructor - * @param {google.protobuf.IMethodOptions=} [properties] Properties to set - */ - function MethodOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * MethodOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype.deprecated = false; - - /** - * MethodOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * MethodOptions .google.api.http. - * @member {google.api.IHttpRule|null|undefined} .google.api.http - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype[".google.api.http"] = null; - - /** - * Creates a new MethodOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.MethodOptions - * @static - * @param {google.protobuf.IMethodOptions=} [properties] Properties to set - * @returns {google.protobuf.MethodOptions} MethodOptions instance - */ - MethodOptions.create = function create(properties) { - return new MethodOptions(properties); - }; - - /** - * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.MethodOptions - * @static - * @param {google.protobuf.IMethodOptions} message MethodOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MethodOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - writer.uint32(/* id 33, wireType 0 =*/264).bool(message.deprecated); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) - $root.google.api.HttpRule.encode(message[".google.api.http"], writer.uint32(/* id 72295728, wireType 2 =*/578365826).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.MethodOptions - * @static - * @param {google.protobuf.IMethodOptions} message MethodOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MethodOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a MethodOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.MethodOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.MethodOptions} MethodOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MethodOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.MethodOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 33: - message.deprecated = reader.bool(); - break; - case 999: - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) - message.uninterpretedOption = []; - message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); - break; - case 72295728: - message[".google.api.http"] = $root.google.api.HttpRule.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a MethodOptions message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.MethodOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.MethodOptions} MethodOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MethodOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a MethodOptions message. - * @function verify - * @memberof google.protobuf.MethodOptions - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - MethodOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - if (typeof message.deprecated !== "boolean") - return "deprecated: boolean expected"; - if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { - if (!Array.isArray(message.uninterpretedOption)) - return "uninterpretedOption: array expected"; - for (var i = 0; i < message.uninterpretedOption.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); - if (error) - return "uninterpretedOption." + error; - } - } - if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) { - var error = $root.google.api.HttpRule.verify(message[".google.api.http"]); - if (error) - return ".google.api.http." + error; - } - return null; - }; - - /** - * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.MethodOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.MethodOptions} MethodOptions - */ - MethodOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.MethodOptions) - return object; - var message = new $root.google.protobuf.MethodOptions(); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - if (object[".google.api.http"] != null) { - if (typeof object[".google.api.http"] !== "object") - throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); - message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); - } - return message; - }; - - /** - * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.MethodOptions - * @static - * @param {google.protobuf.MethodOptions} message MethodOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MethodOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.deprecated = false; - object[".google.api.http"] = null; - } - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) - object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); - return object; - }; - - /** - * Converts this MethodOptions to JSON. - * @function toJSON - * @memberof google.protobuf.MethodOptions - * @instance - * @returns {Object.} JSON object - */ - MethodOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return MethodOptions; - })(); - - protobuf.UninterpretedOption = (function() { - - /** - * Properties of an UninterpretedOption. - * @memberof google.protobuf - * @interface IUninterpretedOption - * @property {Array.|null} [name] UninterpretedOption name - * @property {string|null} [identifierValue] UninterpretedOption identifierValue - * @property {number|string|null} [positiveIntValue] UninterpretedOption positiveIntValue - * @property {number|string|null} [negativeIntValue] UninterpretedOption negativeIntValue - * @property {number|null} [doubleValue] UninterpretedOption doubleValue - * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue - * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue - */ - - /** - * Constructs a new UninterpretedOption. - * @memberof google.protobuf - * @classdesc Represents an UninterpretedOption. - * @implements IUninterpretedOption - * @constructor - * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set - */ - function UninterpretedOption(properties) { - this.name = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * UninterpretedOption name. - * @member {Array.} name - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.name = $util.emptyArray; - - /** - * UninterpretedOption identifierValue. - * @member {string} identifierValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.identifierValue = ""; - - /** - * UninterpretedOption positiveIntValue. - * @member {number|string} positiveIntValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; - - /** - * UninterpretedOption negativeIntValue. - * @member {number|string} negativeIntValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - - /** - * UninterpretedOption doubleValue. - * @member {number} doubleValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.doubleValue = 0; - - /** - * UninterpretedOption stringValue. - * @member {Uint8Array} stringValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.stringValue = $util.newBuffer([]); - - /** - * UninterpretedOption aggregateValue. - * @member {string} aggregateValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.aggregateValue = ""; - - /** - * Creates a new UninterpretedOption instance using the specified properties. - * @function create - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set - * @returns {google.protobuf.UninterpretedOption} UninterpretedOption instance - */ - UninterpretedOption.create = function create(properties) { - return new UninterpretedOption(properties); - }; - - /** - * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. - * @function encode - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {google.protobuf.IUninterpretedOption} message UninterpretedOption message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UninterpretedOption.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && message.name.length) - for (var i = 0; i < message.name.length; ++i) - $root.google.protobuf.UninterpretedOption.NamePart.encode(message.name[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.identifierValue); - if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) - writer.uint32(/* id 4, wireType 0 =*/32).uint64(message.positiveIntValue); - if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.negativeIntValue); - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) - writer.uint32(/* id 6, wireType 1 =*/49).double(message.doubleValue); - if (message.stringValue != null && message.hasOwnProperty("stringValue")) - writer.uint32(/* id 7, wireType 2 =*/58).bytes(message.stringValue); - if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) - writer.uint32(/* id 8, wireType 2 =*/66).string(message.aggregateValue); - return writer; - }; - - /** - * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {google.protobuf.IUninterpretedOption} message UninterpretedOption message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UninterpretedOption.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an UninterpretedOption message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.UninterpretedOption} UninterpretedOption - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UninterpretedOption.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.UninterpretedOption(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 2: - if (!(message.name && message.name.length)) - message.name = []; - message.name.push($root.google.protobuf.UninterpretedOption.NamePart.decode(reader, reader.uint32())); - break; - case 3: - message.identifierValue = reader.string(); - break; - case 4: - message.positiveIntValue = reader.uint64(); - break; - case 5: - message.negativeIntValue = reader.int64(); - break; - case 6: - message.doubleValue = reader.double(); - break; - case 7: - message.stringValue = reader.bytes(); - break; - case 8: - message.aggregateValue = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.UninterpretedOption} UninterpretedOption - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UninterpretedOption.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an UninterpretedOption message. - * @function verify - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - UninterpretedOption.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) { - if (!Array.isArray(message.name)) - return "name: array expected"; - for (var i = 0; i < message.name.length; ++i) { - var error = $root.google.protobuf.UninterpretedOption.NamePart.verify(message.name[i]); - if (error) - return "name." + error; - } - } - if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) - if (!$util.isString(message.identifierValue)) - return "identifierValue: string expected"; - if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) - if (!$util.isInteger(message.positiveIntValue) && !(message.positiveIntValue && $util.isInteger(message.positiveIntValue.low) && $util.isInteger(message.positiveIntValue.high))) - return "positiveIntValue: integer|Long expected"; - if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) - if (!$util.isInteger(message.negativeIntValue) && !(message.negativeIntValue && $util.isInteger(message.negativeIntValue.low) && $util.isInteger(message.negativeIntValue.high))) - return "negativeIntValue: integer|Long expected"; - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) - if (typeof message.doubleValue !== "number") - return "doubleValue: number expected"; - if (message.stringValue != null && message.hasOwnProperty("stringValue")) - if (!(message.stringValue && typeof message.stringValue.length === "number" || $util.isString(message.stringValue))) - return "stringValue: buffer expected"; - if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) - if (!$util.isString(message.aggregateValue)) - return "aggregateValue: string expected"; - return null; - }; - - /** - * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UninterpretedOption} UninterpretedOption - */ - UninterpretedOption.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UninterpretedOption) - return object; - var message = new $root.google.protobuf.UninterpretedOption(); - if (object.name) { - if (!Array.isArray(object.name)) - throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); - message.name = []; - for (var i = 0; i < object.name.length; ++i) { - if (typeof object.name[i] !== "object") - throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); - message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); - } - } - if (object.identifierValue != null) - message.identifierValue = String(object.identifierValue); - if (object.positiveIntValue != null) - if ($util.Long) - (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; - else if (typeof object.positiveIntValue === "string") - message.positiveIntValue = parseInt(object.positiveIntValue, 10); - else if (typeof object.positiveIntValue === "number") - message.positiveIntValue = object.positiveIntValue; - else if (typeof object.positiveIntValue === "object") - message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); - if (object.negativeIntValue != null) - if ($util.Long) - (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; - else if (typeof object.negativeIntValue === "string") - message.negativeIntValue = parseInt(object.negativeIntValue, 10); - else if (typeof object.negativeIntValue === "number") - message.negativeIntValue = object.negativeIntValue; - else if (typeof object.negativeIntValue === "object") - message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); - if (object.doubleValue != null) - message.doubleValue = Number(object.doubleValue); - if (object.stringValue != null) - if (typeof object.stringValue === "string") - $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); - else if (object.stringValue.length) - message.stringValue = object.stringValue; - if (object.aggregateValue != null) - message.aggregateValue = String(object.aggregateValue); - return message; - }; - - /** - * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {google.protobuf.UninterpretedOption} message UninterpretedOption - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UninterpretedOption.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.name = []; - if (options.defaults) { - object.identifierValue = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.positiveIntValue = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.negativeIntValue = options.longs === String ? "0" : 0; - object.doubleValue = 0; - object.stringValue = options.bytes === String ? "" : []; - object.aggregateValue = ""; - } - if (message.name && message.name.length) { - object.name = []; - for (var j = 0; j < message.name.length; ++j) - object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); - } - if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) - object.identifierValue = message.identifierValue; - if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) - if (typeof message.positiveIntValue === "number") - object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; - else - object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; - if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) - if (typeof message.negativeIntValue === "number") - object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; - else - object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) - object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; - if (message.stringValue != null && message.hasOwnProperty("stringValue")) - object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; - if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) - object.aggregateValue = message.aggregateValue; - return object; - }; - - /** - * Converts this UninterpretedOption to JSON. - * @function toJSON - * @memberof google.protobuf.UninterpretedOption - * @instance - * @returns {Object.} JSON object - */ - UninterpretedOption.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - UninterpretedOption.NamePart = (function() { - - /** - * Properties of a NamePart. - * @memberof google.protobuf.UninterpretedOption - * @interface INamePart - * @property {string} namePart NamePart namePart - * @property {boolean} isExtension NamePart isExtension - */ - - /** - * Constructs a new NamePart. - * @memberof google.protobuf.UninterpretedOption - * @classdesc Represents a NamePart. - * @implements INamePart - * @constructor - * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set - */ - function NamePart(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * NamePart namePart. - * @member {string} namePart - * @memberof google.protobuf.UninterpretedOption.NamePart - * @instance - */ - NamePart.prototype.namePart = ""; - - /** - * NamePart isExtension. - * @member {boolean} isExtension - * @memberof google.protobuf.UninterpretedOption.NamePart - * @instance - */ - NamePart.prototype.isExtension = false; - - /** - * Creates a new NamePart instance using the specified properties. - * @function create - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set - * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart instance - */ - NamePart.create = function create(properties) { - return new NamePart(properties); - }; - - /** - * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. - * @function encode - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {google.protobuf.UninterpretedOption.INamePart} message NamePart message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - NamePart.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - writer.uint32(/* id 1, wireType 2 =*/10).string(message.namePart); - writer.uint32(/* id 2, wireType 0 =*/16).bool(message.isExtension); - return writer; - }; - - /** - * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {google.protobuf.UninterpretedOption.INamePart} message NamePart message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - NamePart.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a NamePart message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - NamePart.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.UninterpretedOption.NamePart(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.namePart = reader.string(); - break; - case 2: - message.isExtension = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - if (!message.hasOwnProperty("namePart")) - throw $util.ProtocolError("missing required 'namePart'", { instance: message }); - if (!message.hasOwnProperty("isExtension")) - throw $util.ProtocolError("missing required 'isExtension'", { instance: message }); - return message; - }; - - /** - * Decodes a NamePart message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - NamePart.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a NamePart message. - * @function verify - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - NamePart.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (!$util.isString(message.namePart)) - return "namePart: string expected"; - if (typeof message.isExtension !== "boolean") - return "isExtension: boolean expected"; - return null; - }; - - /** - * Creates a NamePart message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart - */ - NamePart.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) - return object; - var message = new $root.google.protobuf.UninterpretedOption.NamePart(); - if (object.namePart != null) - message.namePart = String(object.namePart); - if (object.isExtension != null) - message.isExtension = Boolean(object.isExtension); - return message; - }; - - /** - * Creates a plain object from a NamePart message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - NamePart.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.namePart = ""; - object.isExtension = false; - } - if (message.namePart != null && message.hasOwnProperty("namePart")) - object.namePart = message.namePart; - if (message.isExtension != null && message.hasOwnProperty("isExtension")) - object.isExtension = message.isExtension; - return object; - }; - - /** - * Converts this NamePart to JSON. - * @function toJSON - * @memberof google.protobuf.UninterpretedOption.NamePart - * @instance - * @returns {Object.} JSON object - */ - NamePart.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return NamePart; - })(); - - return UninterpretedOption; - })(); - - protobuf.SourceCodeInfo = (function() { - - /** - * Properties of a SourceCodeInfo. - * @memberof google.protobuf - * @interface ISourceCodeInfo - * @property {Array.|null} [location] SourceCodeInfo location - */ - - /** - * Constructs a new SourceCodeInfo. - * @memberof google.protobuf - * @classdesc Represents a SourceCodeInfo. - * @implements ISourceCodeInfo - * @constructor - * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set - */ - function SourceCodeInfo(properties) { - this.location = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SourceCodeInfo location. - * @member {Array.} location - * @memberof google.protobuf.SourceCodeInfo - * @instance - */ - SourceCodeInfo.prototype.location = $util.emptyArray; - - /** - * Creates a new SourceCodeInfo instance using the specified properties. - * @function create - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set - * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo instance - */ - SourceCodeInfo.create = function create(properties) { - return new SourceCodeInfo(properties); - }; - - /** - * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. - * @function encode - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {google.protobuf.ISourceCodeInfo} message SourceCodeInfo message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SourceCodeInfo.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.location != null && message.location.length) - for (var i = 0; i < message.location.length; ++i) - $root.google.protobuf.SourceCodeInfo.Location.encode(message.location[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {google.protobuf.ISourceCodeInfo} message SourceCodeInfo message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SourceCodeInfo.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SourceCodeInfo message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SourceCodeInfo.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.SourceCodeInfo(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.location && message.location.length)) - message.location = []; - message.location.push($root.google.protobuf.SourceCodeInfo.Location.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SourceCodeInfo.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SourceCodeInfo message. - * @function verify - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SourceCodeInfo.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.location != null && message.hasOwnProperty("location")) { - if (!Array.isArray(message.location)) - return "location: array expected"; - for (var i = 0; i < message.location.length; ++i) { - var error = $root.google.protobuf.SourceCodeInfo.Location.verify(message.location[i]); - if (error) - return "location." + error; - } - } - return null; - }; - - /** - * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo - */ - SourceCodeInfo.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.SourceCodeInfo) - return object; - var message = new $root.google.protobuf.SourceCodeInfo(); - if (object.location) { - if (!Array.isArray(object.location)) - throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); - message.location = []; - for (var i = 0; i < object.location.length; ++i) { - if (typeof object.location[i] !== "object") - throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); - message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SourceCodeInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.location = []; - if (message.location && message.location.length) { - object.location = []; - for (var j = 0; j < message.location.length; ++j) - object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); - } - return object; - }; - - /** - * Converts this SourceCodeInfo to JSON. - * @function toJSON - * @memberof google.protobuf.SourceCodeInfo - * @instance - * @returns {Object.} JSON object - */ - SourceCodeInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - SourceCodeInfo.Location = (function() { - - /** - * Properties of a Location. - * @memberof google.protobuf.SourceCodeInfo - * @interface ILocation - * @property {Array.|null} [path] Location path - * @property {Array.|null} [span] Location span - * @property {string|null} [leadingComments] Location leadingComments - * @property {string|null} [trailingComments] Location trailingComments - * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments - */ - - /** - * Constructs a new Location. - * @memberof google.protobuf.SourceCodeInfo - * @classdesc Represents a Location. - * @implements ILocation - * @constructor - * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set - */ - function Location(properties) { - this.path = []; - this.span = []; - this.leadingDetachedComments = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Location path. - * @member {Array.} path - * @memberof google.protobuf.SourceCodeInfo.Location - * @instance - */ - Location.prototype.path = $util.emptyArray; - - /** - * Location span. - * @member {Array.} span - * @memberof google.protobuf.SourceCodeInfo.Location - * @instance - */ - Location.prototype.span = $util.emptyArray; - - /** - * Location leadingComments. - * @member {string} leadingComments - * @memberof google.protobuf.SourceCodeInfo.Location - * @instance - */ - Location.prototype.leadingComments = ""; - - /** - * Location trailingComments. - * @member {string} trailingComments - * @memberof google.protobuf.SourceCodeInfo.Location - * @instance - */ - Location.prototype.trailingComments = ""; - - /** - * Location leadingDetachedComments. - * @member {Array.} leadingDetachedComments - * @memberof google.protobuf.SourceCodeInfo.Location - * @instance - */ - Location.prototype.leadingDetachedComments = $util.emptyArray; - - /** - * Creates a new Location instance using the specified properties. - * @function create - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set - * @returns {google.protobuf.SourceCodeInfo.Location} Location instance - */ - Location.create = function create(properties) { - return new Location(properties); - }; - - /** - * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. - * @function encode - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {google.protobuf.SourceCodeInfo.ILocation} message Location message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Location.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.path != null && message.path.length) { - writer.uint32(/* id 1, wireType 2 =*/10).fork(); - for (var i = 0; i < message.path.length; ++i) - writer.int32(message.path[i]); - writer.ldelim(); - } - if (message.span != null && message.span.length) { - writer.uint32(/* id 2, wireType 2 =*/18).fork(); - for (var i = 0; i < message.span.length; ++i) - writer.int32(message.span[i]); - writer.ldelim(); - } - if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.leadingComments); - if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.trailingComments); - if (message.leadingDetachedComments != null && message.leadingDetachedComments.length) - for (var i = 0; i < message.leadingDetachedComments.length; ++i) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.leadingDetachedComments[i]); - return writer; - }; - - /** - * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {google.protobuf.SourceCodeInfo.ILocation} message Location message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Location.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Location message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.SourceCodeInfo.Location} Location - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Location.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.SourceCodeInfo.Location(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.path && message.path.length)) - message.path = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.path.push(reader.int32()); - } else - message.path.push(reader.int32()); - break; - case 2: - if (!(message.span && message.span.length)) - message.span = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.span.push(reader.int32()); - } else - message.span.push(reader.int32()); - break; - case 3: - message.leadingComments = reader.string(); - break; - case 4: - message.trailingComments = reader.string(); - break; - case 6: - if (!(message.leadingDetachedComments && message.leadingDetachedComments.length)) - message.leadingDetachedComments = []; - message.leadingDetachedComments.push(reader.string()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Location message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.SourceCodeInfo.Location} Location - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Location.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Location message. - * @function verify - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Location.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.path != null && message.hasOwnProperty("path")) { - if (!Array.isArray(message.path)) - return "path: array expected"; - for (var i = 0; i < message.path.length; ++i) - if (!$util.isInteger(message.path[i])) - return "path: integer[] expected"; - } - if (message.span != null && message.hasOwnProperty("span")) { - if (!Array.isArray(message.span)) - return "span: array expected"; - for (var i = 0; i < message.span.length; ++i) - if (!$util.isInteger(message.span[i])) - return "span: integer[] expected"; - } - if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) - if (!$util.isString(message.leadingComments)) - return "leadingComments: string expected"; - if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) - if (!$util.isString(message.trailingComments)) - return "trailingComments: string expected"; - if (message.leadingDetachedComments != null && message.hasOwnProperty("leadingDetachedComments")) { - if (!Array.isArray(message.leadingDetachedComments)) - return "leadingDetachedComments: array expected"; - for (var i = 0; i < message.leadingDetachedComments.length; ++i) - if (!$util.isString(message.leadingDetachedComments[i])) - return "leadingDetachedComments: string[] expected"; - } - return null; - }; - - /** - * Creates a Location message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.SourceCodeInfo.Location} Location - */ - Location.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) - return object; - var message = new $root.google.protobuf.SourceCodeInfo.Location(); - if (object.path) { - if (!Array.isArray(object.path)) - throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); - message.path = []; - for (var i = 0; i < object.path.length; ++i) - message.path[i] = object.path[i] | 0; - } - if (object.span) { - if (!Array.isArray(object.span)) - throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); - message.span = []; - for (var i = 0; i < object.span.length; ++i) - message.span[i] = object.span[i] | 0; - } - if (object.leadingComments != null) - message.leadingComments = String(object.leadingComments); - if (object.trailingComments != null) - message.trailingComments = String(object.trailingComments); - if (object.leadingDetachedComments) { - if (!Array.isArray(object.leadingDetachedComments)) - throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); - message.leadingDetachedComments = []; - for (var i = 0; i < object.leadingDetachedComments.length; ++i) - message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); - } - return message; - }; - - /** - * Creates a plain object from a Location message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.SourceCodeInfo.Location - * @static - * @param {google.protobuf.SourceCodeInfo.Location} message Location - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Location.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.path = []; - object.span = []; - object.leadingDetachedComments = []; - } - if (options.defaults) { - object.leadingComments = ""; - object.trailingComments = ""; - } - if (message.path && message.path.length) { - object.path = []; - for (var j = 0; j < message.path.length; ++j) - object.path[j] = message.path[j]; - } - if (message.span && message.span.length) { - object.span = []; - for (var j = 0; j < message.span.length; ++j) - object.span[j] = message.span[j]; - } - if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) - object.leadingComments = message.leadingComments; - if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) - object.trailingComments = message.trailingComments; - if (message.leadingDetachedComments && message.leadingDetachedComments.length) { - object.leadingDetachedComments = []; - for (var j = 0; j < message.leadingDetachedComments.length; ++j) - object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; - } - return object; - }; - - /** - * Converts this Location to JSON. - * @function toJSON - * @memberof google.protobuf.SourceCodeInfo.Location - * @instance - * @returns {Object.} JSON object - */ - Location.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Location; - })(); - - return SourceCodeInfo; - })(); - - protobuf.GeneratedCodeInfo = (function() { - - /** - * Properties of a GeneratedCodeInfo. - * @memberof google.protobuf - * @interface IGeneratedCodeInfo - * @property {Array.|null} [annotation] GeneratedCodeInfo annotation - */ - - /** - * Constructs a new GeneratedCodeInfo. - * @memberof google.protobuf - * @classdesc Represents a GeneratedCodeInfo. - * @implements IGeneratedCodeInfo - * @constructor - * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set - */ - function GeneratedCodeInfo(properties) { - this.annotation = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * GeneratedCodeInfo annotation. - * @member {Array.} annotation - * @memberof google.protobuf.GeneratedCodeInfo - * @instance - */ - GeneratedCodeInfo.prototype.annotation = $util.emptyArray; - - /** - * Creates a new GeneratedCodeInfo instance using the specified properties. - * @function create - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set - * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo instance - */ - GeneratedCodeInfo.create = function create(properties) { - return new GeneratedCodeInfo(properties); - }; - - /** - * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. - * @function encode - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {google.protobuf.IGeneratedCodeInfo} message GeneratedCodeInfo message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - GeneratedCodeInfo.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.annotation != null && message.annotation.length) - for (var i = 0; i < message.annotation.length; ++i) - $root.google.protobuf.GeneratedCodeInfo.Annotation.encode(message.annotation[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {google.protobuf.IGeneratedCodeInfo} message GeneratedCodeInfo message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - GeneratedCodeInfo.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a GeneratedCodeInfo message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - GeneratedCodeInfo.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.GeneratedCodeInfo(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.annotation && message.annotation.length)) - message.annotation = []; - message.annotation.push($root.google.protobuf.GeneratedCodeInfo.Annotation.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - GeneratedCodeInfo.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a GeneratedCodeInfo message. - * @function verify - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - GeneratedCodeInfo.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.annotation != null && message.hasOwnProperty("annotation")) { - if (!Array.isArray(message.annotation)) - return "annotation: array expected"; - for (var i = 0; i < message.annotation.length; ++i) { - var error = $root.google.protobuf.GeneratedCodeInfo.Annotation.verify(message.annotation[i]); - if (error) - return "annotation." + error; - } - } - return null; - }; - - /** - * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo - */ - GeneratedCodeInfo.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.GeneratedCodeInfo) - return object; - var message = new $root.google.protobuf.GeneratedCodeInfo(); - if (object.annotation) { - if (!Array.isArray(object.annotation)) - throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); - message.annotation = []; - for (var i = 0; i < object.annotation.length; ++i) { - if (typeof object.annotation[i] !== "object") - throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); - message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - GeneratedCodeInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.annotation = []; - if (message.annotation && message.annotation.length) { - object.annotation = []; - for (var j = 0; j < message.annotation.length; ++j) - object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); - } - return object; - }; - - /** - * Converts this GeneratedCodeInfo to JSON. - * @function toJSON - * @memberof google.protobuf.GeneratedCodeInfo - * @instance - * @returns {Object.} JSON object - */ - GeneratedCodeInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - GeneratedCodeInfo.Annotation = (function() { - - /** - * Properties of an Annotation. - * @memberof google.protobuf.GeneratedCodeInfo - * @interface IAnnotation - * @property {Array.|null} [path] Annotation path - * @property {string|null} [sourceFile] Annotation sourceFile - * @property {number|null} [begin] Annotation begin - * @property {number|null} [end] Annotation end - */ - - /** - * Constructs a new Annotation. - * @memberof google.protobuf.GeneratedCodeInfo - * @classdesc Represents an Annotation. - * @implements IAnnotation - * @constructor - * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set - */ - function Annotation(properties) { - this.path = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Annotation path. - * @member {Array.} path - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @instance - */ - Annotation.prototype.path = $util.emptyArray; - - /** - * Annotation sourceFile. - * @member {string} sourceFile - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @instance - */ - Annotation.prototype.sourceFile = ""; - - /** - * Annotation begin. - * @member {number} begin - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @instance - */ - Annotation.prototype.begin = 0; - - /** - * Annotation end. - * @member {number} end - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @instance - */ - Annotation.prototype.end = 0; - - /** - * Creates a new Annotation instance using the specified properties. - * @function create - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set - * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation instance - */ - Annotation.create = function create(properties) { - return new Annotation(properties); - }; - - /** - * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. - * @function encode - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {google.protobuf.GeneratedCodeInfo.IAnnotation} message Annotation message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Annotation.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.path != null && message.path.length) { - writer.uint32(/* id 1, wireType 2 =*/10).fork(); - for (var i = 0; i < message.path.length; ++i) - writer.int32(message.path[i]); - writer.ldelim(); - } - if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.sourceFile); - if (message.begin != null && message.hasOwnProperty("begin")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.begin); - if (message.end != null && message.hasOwnProperty("end")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.end); - return writer; - }; - - /** - * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {google.protobuf.GeneratedCodeInfo.IAnnotation} message Annotation message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Annotation.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an Annotation message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Annotation.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.path && message.path.length)) - message.path = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.path.push(reader.int32()); - } else - message.path.push(reader.int32()); - break; - case 2: - message.sourceFile = reader.string(); - break; - case 3: - message.begin = reader.int32(); - break; - case 4: - message.end = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an Annotation message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Annotation.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an Annotation message. - * @function verify - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Annotation.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.path != null && message.hasOwnProperty("path")) { - if (!Array.isArray(message.path)) - return "path: array expected"; - for (var i = 0; i < message.path.length; ++i) - if (!$util.isInteger(message.path[i])) - return "path: integer[] expected"; - } - if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) - if (!$util.isString(message.sourceFile)) - return "sourceFile: string expected"; - if (message.begin != null && message.hasOwnProperty("begin")) - if (!$util.isInteger(message.begin)) - return "begin: integer expected"; - if (message.end != null && message.hasOwnProperty("end")) - if (!$util.isInteger(message.end)) - return "end: integer expected"; - return null; - }; - - /** - * Creates an Annotation message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation - */ - Annotation.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) - return object; - var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); - if (object.path) { - if (!Array.isArray(object.path)) - throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); - message.path = []; - for (var i = 0; i < object.path.length; ++i) - message.path[i] = object.path[i] | 0; - } - if (object.sourceFile != null) - message.sourceFile = String(object.sourceFile); - if (object.begin != null) - message.begin = object.begin | 0; - if (object.end != null) - message.end = object.end | 0; - return message; - }; - - /** - * Creates a plain object from an Annotation message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @static - * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Annotation.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.path = []; - if (options.defaults) { - object.sourceFile = ""; - object.begin = 0; - object.end = 0; - } - if (message.path && message.path.length) { - object.path = []; - for (var j = 0; j < message.path.length; ++j) - object.path[j] = message.path[j]; - } - if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) - object.sourceFile = message.sourceFile; - if (message.begin != null && message.hasOwnProperty("begin")) - object.begin = message.begin; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; - return object; - }; - - /** - * Converts this Annotation to JSON. - * @function toJSON - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @instance - * @returns {Object.} JSON object - */ - Annotation.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Annotation; - })(); - - return GeneratedCodeInfo; - })(); - - protobuf.Timestamp = (function() { - - /** - * Properties of a Timestamp. - * @memberof google.protobuf - * @interface ITimestamp - * @property {number|string|null} [seconds] Timestamp seconds - * @property {number|null} [nanos] Timestamp nanos - */ - - /** - * Constructs a new Timestamp. - * @memberof google.protobuf - * @classdesc Represents a Timestamp. - * @implements ITimestamp - * @constructor - * @param {google.protobuf.ITimestamp=} [properties] Properties to set - */ - function Timestamp(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Timestamp seconds. - * @member {number|string} seconds - * @memberof google.protobuf.Timestamp - * @instance - */ - Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - - /** - * Timestamp nanos. - * @member {number} nanos - * @memberof google.protobuf.Timestamp - * @instance - */ - Timestamp.prototype.nanos = 0; - - /** - * Creates a new Timestamp instance using the specified properties. - * @function create - * @memberof google.protobuf.Timestamp - * @static - * @param {google.protobuf.ITimestamp=} [properties] Properties to set - * @returns {google.protobuf.Timestamp} Timestamp instance - */ - Timestamp.create = function create(properties) { - return new Timestamp(properties); - }; - - /** - * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Timestamp - * @static - * @param {google.protobuf.ITimestamp} message Timestamp message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Timestamp.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.seconds != null && message.hasOwnProperty("seconds")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.seconds); - if (message.nanos != null && message.hasOwnProperty("nanos")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.nanos); - return writer; - }; - - /** - * Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Timestamp - * @static - * @param {google.protobuf.ITimestamp} message Timestamp message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Timestamp.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Timestamp message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Timestamp - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Timestamp} Timestamp - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Timestamp.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Timestamp(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.seconds = reader.int64(); - break; - case 2: - message.nanos = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Timestamp message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Timestamp - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Timestamp} Timestamp - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Timestamp.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Timestamp message. - * @function verify - * @memberof google.protobuf.Timestamp - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Timestamp.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.seconds != null && message.hasOwnProperty("seconds")) - if (!$util.isInteger(message.seconds) && !(message.seconds && $util.isInteger(message.seconds.low) && $util.isInteger(message.seconds.high))) - return "seconds: integer|Long expected"; - if (message.nanos != null && message.hasOwnProperty("nanos")) - if (!$util.isInteger(message.nanos)) - return "nanos: integer expected"; - return null; - }; - - /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Timestamp - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Timestamp} Timestamp - */ - Timestamp.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Timestamp) - return object; - var message = new $root.google.protobuf.Timestamp(); - if (object.seconds != null) - if ($util.Long) - (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; - else if (typeof object.seconds === "string") - message.seconds = parseInt(object.seconds, 10); - else if (typeof object.seconds === "number") - message.seconds = object.seconds; - else if (typeof object.seconds === "object") - message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); - if (object.nanos != null) - message.nanos = object.nanos | 0; - return message; - }; - - /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Timestamp - * @static - * @param {google.protobuf.Timestamp} message Timestamp - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Timestamp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.seconds = options.longs === String ? "0" : 0; - object.nanos = 0; - } - if (message.seconds != null && message.hasOwnProperty("seconds")) - if (typeof message.seconds === "number") - object.seconds = options.longs === String ? String(message.seconds) : message.seconds; - else - object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; - if (message.nanos != null && message.hasOwnProperty("nanos")) - object.nanos = message.nanos; - return object; - }; - - /** - * Converts this Timestamp to JSON. - * @function toJSON - * @memberof google.protobuf.Timestamp - * @instance - * @returns {Object.} JSON object - */ - Timestamp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Timestamp; - })(); - - protobuf.Struct = (function() { - - /** - * Properties of a Struct. - * @memberof google.protobuf - * @interface IStruct - * @property {Object.|null} [fields] Struct fields - */ - - /** - * Constructs a new Struct. - * @memberof google.protobuf - * @classdesc Represents a Struct. - * @implements IStruct - * @constructor - * @param {google.protobuf.IStruct=} [properties] Properties to set - */ - function Struct(properties) { - this.fields = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Struct fields. - * @member {Object.} fields - * @memberof google.protobuf.Struct - * @instance - */ - Struct.prototype.fields = $util.emptyObject; - - /** - * Creates a new Struct instance using the specified properties. - * @function create - * @memberof google.protobuf.Struct - * @static - * @param {google.protobuf.IStruct=} [properties] Properties to set - * @returns {google.protobuf.Struct} Struct instance - */ - Struct.create = function create(properties) { - return new Struct(properties); - }; - - /** - * Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Struct - * @static - * @param {google.protobuf.IStruct} message Struct message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Struct.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.fields != null && message.hasOwnProperty("fields")) - for (var keys = Object.keys(message.fields), i = 0; i < keys.length; ++i) { - writer.uint32(/* id 1, wireType 2 =*/10).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); - $root.google.protobuf.Value.encode(message.fields[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); - } - return writer; - }; - - /** - * Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Struct - * @static - * @param {google.protobuf.IStruct} message Struct message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Struct.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Struct message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Struct - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Struct} Struct - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Struct.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Struct(), key; - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - reader.skip().pos++; - if (message.fields === $util.emptyObject) - message.fields = {}; - key = reader.string(); - reader.pos++; - message.fields[key] = $root.google.protobuf.Value.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Struct message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Struct - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Struct} Struct - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Struct.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Struct message. - * @function verify - * @memberof google.protobuf.Struct - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Struct.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.fields != null && message.hasOwnProperty("fields")) { - if (!$util.isObject(message.fields)) - return "fields: object expected"; - var key = Object.keys(message.fields); - for (var i = 0; i < key.length; ++i) { - var error = $root.google.protobuf.Value.verify(message.fields[key[i]]); - if (error) - return "fields." + error; - } - } - return null; - }; - - /** - * Creates a Struct message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Struct - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Struct} Struct - */ - Struct.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Struct) - return object; - var message = new $root.google.protobuf.Struct(); - if (object.fields) { - if (typeof object.fields !== "object") - throw TypeError(".google.protobuf.Struct.fields: object expected"); - message.fields = {}; - for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { - if (typeof object.fields[keys[i]] !== "object") - throw TypeError(".google.protobuf.Struct.fields: object expected"); - message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); - } - } - return message; - }; - - /** - * Creates a plain object from a Struct message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Struct - * @static - * @param {google.protobuf.Struct} message Struct - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Struct.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.fields = {}; - var keys2; - if (message.fields && (keys2 = Object.keys(message.fields)).length) { - object.fields = {}; - for (var j = 0; j < keys2.length; ++j) - object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); - } - return object; - }; - - /** - * Converts this Struct to JSON. - * @function toJSON - * @memberof google.protobuf.Struct - * @instance - * @returns {Object.} JSON object - */ - Struct.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Struct; - })(); - - protobuf.Value = (function() { - - /** - * Properties of a Value. - * @memberof google.protobuf - * @interface IValue - * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue - * @property {number|null} [numberValue] Value numberValue - * @property {string|null} [stringValue] Value stringValue - * @property {boolean|null} [boolValue] Value boolValue - * @property {google.protobuf.IStruct|null} [structValue] Value structValue - * @property {google.protobuf.IListValue|null} [listValue] Value listValue - */ - - /** - * Constructs a new Value. - * @memberof google.protobuf - * @classdesc Represents a Value. - * @implements IValue - * @constructor - * @param {google.protobuf.IValue=} [properties] Properties to set - */ - function Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Value nullValue. - * @member {google.protobuf.NullValue} nullValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.nullValue = 0; - - /** - * Value numberValue. - * @member {number} numberValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.numberValue = 0; - - /** - * Value stringValue. - * @member {string} stringValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.stringValue = ""; - - /** - * Value boolValue. - * @member {boolean} boolValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.boolValue = false; - - /** - * Value structValue. - * @member {google.protobuf.IStruct|null|undefined} structValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.structValue = null; - - /** - * Value listValue. - * @member {google.protobuf.IListValue|null|undefined} listValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.listValue = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Value kind. - * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind - * @memberof google.protobuf.Value - * @instance - */ - Object.defineProperty(Value.prototype, "kind", { - get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new Value instance using the specified properties. - * @function create - * @memberof google.protobuf.Value - * @static - * @param {google.protobuf.IValue=} [properties] Properties to set - * @returns {google.protobuf.Value} Value instance - */ - Value.create = function create(properties) { - return new Value(properties); - }; - - /** - * Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Value - * @static - * @param {google.protobuf.IValue} message Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Value.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.nullValue != null && message.hasOwnProperty("nullValue")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.nullValue); - if (message.numberValue != null && message.hasOwnProperty("numberValue")) - writer.uint32(/* id 2, wireType 1 =*/17).double(message.numberValue); - if (message.stringValue != null && message.hasOwnProperty("stringValue")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.stringValue); - if (message.boolValue != null && message.hasOwnProperty("boolValue")) - writer.uint32(/* id 4, wireType 0 =*/32).bool(message.boolValue); - if (message.structValue != null && message.hasOwnProperty("structValue")) - $root.google.protobuf.Struct.encode(message.structValue, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.listValue != null && message.hasOwnProperty("listValue")) - $root.google.protobuf.ListValue.encode(message.listValue, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Value - * @static - * @param {google.protobuf.IValue} message Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Value.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Value message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Value} Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Value.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Value(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.nullValue = reader.int32(); - break; - case 2: - message.numberValue = reader.double(); - break; - case 3: - message.stringValue = reader.string(); - break; - case 4: - message.boolValue = reader.bool(); - break; - case 5: - message.structValue = $root.google.protobuf.Struct.decode(reader, reader.uint32()); - break; - case 6: - message.listValue = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Value message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Value} Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Value.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Value message. - * @function verify - * @memberof google.protobuf.Value - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Value.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.nullValue != null && message.hasOwnProperty("nullValue")) { - properties.kind = 1; - switch (message.nullValue) { - default: - return "nullValue: enum value expected"; - case 0: - break; - } - } - if (message.numberValue != null && message.hasOwnProperty("numberValue")) { - if (properties.kind === 1) - return "kind: multiple values"; - properties.kind = 1; - if (typeof message.numberValue !== "number") - return "numberValue: number expected"; - } - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - if (properties.kind === 1) - return "kind: multiple values"; - properties.kind = 1; - if (!$util.isString(message.stringValue)) - return "stringValue: string expected"; - } - if (message.boolValue != null && message.hasOwnProperty("boolValue")) { - if (properties.kind === 1) - return "kind: multiple values"; - properties.kind = 1; - if (typeof message.boolValue !== "boolean") - return "boolValue: boolean expected"; - } - if (message.structValue != null && message.hasOwnProperty("structValue")) { - if (properties.kind === 1) - return "kind: multiple values"; - properties.kind = 1; - { - var error = $root.google.protobuf.Struct.verify(message.structValue); - if (error) - return "structValue." + error; - } - } - if (message.listValue != null && message.hasOwnProperty("listValue")) { - if (properties.kind === 1) - return "kind: multiple values"; - properties.kind = 1; - { - var error = $root.google.protobuf.ListValue.verify(message.listValue); - if (error) - return "listValue." + error; - } - } - return null; - }; - - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Value} Value - */ - Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Value) - return object; - var message = new $root.google.protobuf.Value(); - switch (object.nullValue) { - case "NULL_VALUE": - case 0: - message.nullValue = 0; - break; - } - if (object.numberValue != null) - message.numberValue = Number(object.numberValue); - if (object.stringValue != null) - message.stringValue = String(object.stringValue); - if (object.boolValue != null) - message.boolValue = Boolean(object.boolValue); - if (object.structValue != null) { - if (typeof object.structValue !== "object") - throw TypeError(".google.protobuf.Value.structValue: object expected"); - message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); - } - if (object.listValue != null) { - if (typeof object.listValue !== "object") - throw TypeError(".google.protobuf.Value.listValue: object expected"); - message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); - } - return message; - }; - - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Value - * @static - * @param {google.protobuf.Value} message Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.nullValue != null && message.hasOwnProperty("nullValue")) { - object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; - if (options.oneofs) - object.kind = "nullValue"; - } - if (message.numberValue != null && message.hasOwnProperty("numberValue")) { - object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; - if (options.oneofs) - object.kind = "numberValue"; - } - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - object.stringValue = message.stringValue; - if (options.oneofs) - object.kind = "stringValue"; - } - if (message.boolValue != null && message.hasOwnProperty("boolValue")) { - object.boolValue = message.boolValue; - if (options.oneofs) - object.kind = "boolValue"; - } - if (message.structValue != null && message.hasOwnProperty("structValue")) { - object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); - if (options.oneofs) - object.kind = "structValue"; - } - if (message.listValue != null && message.hasOwnProperty("listValue")) { - object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); - if (options.oneofs) - object.kind = "listValue"; - } - return object; - }; - - /** - * Converts this Value to JSON. - * @function toJSON - * @memberof google.protobuf.Value - * @instance - * @returns {Object.} JSON object - */ - Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Value; - })(); - - /** - * NullValue enum. - * @name google.protobuf.NullValue - * @enum {string} - * @property {number} NULL_VALUE=0 NULL_VALUE value - */ - protobuf.NullValue = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "NULL_VALUE"] = 0; - return values; - })(); - - protobuf.ListValue = (function() { - - /** - * Properties of a ListValue. - * @memberof google.protobuf - * @interface IListValue - * @property {Array.|null} [values] ListValue values - */ - - /** - * Constructs a new ListValue. - * @memberof google.protobuf - * @classdesc Represents a ListValue. - * @implements IListValue - * @constructor - * @param {google.protobuf.IListValue=} [properties] Properties to set - */ - function ListValue(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ListValue values. - * @member {Array.} values - * @memberof google.protobuf.ListValue - * @instance - */ - ListValue.prototype.values = $util.emptyArray; - - /** - * Creates a new ListValue instance using the specified properties. - * @function create - * @memberof google.protobuf.ListValue - * @static - * @param {google.protobuf.IListValue=} [properties] Properties to set - * @returns {google.protobuf.ListValue} ListValue instance - */ - ListValue.create = function create(properties) { - return new ListValue(properties); - }; - - /** - * Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. - * @function encode - * @memberof google.protobuf.ListValue - * @static - * @param {google.protobuf.IListValue} message ListValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.values != null && message.values.length) - for (var i = 0; i < message.values.length; ++i) - $root.google.protobuf.Value.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.ListValue - * @static - * @param {google.protobuf.IListValue} message ListValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ListValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a ListValue message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.ListValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.ListValue} ListValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.ListValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.values && message.values.length)) - message.values = []; - message.values.push($root.google.protobuf.Value.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a ListValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.ListValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.ListValue} ListValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ListValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a ListValue message. - * @function verify - * @memberof google.protobuf.ListValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ListValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.values != null && message.hasOwnProperty("values")) { - if (!Array.isArray(message.values)) - return "values: array expected"; - for (var i = 0; i < message.values.length; ++i) { - var error = $root.google.protobuf.Value.verify(message.values[i]); - if (error) - return "values." + error; - } - } - return null; - }; - - /** - * Creates a ListValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ListValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ListValue} ListValue - */ - ListValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ListValue) - return object; - var message = new $root.google.protobuf.ListValue(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".google.protobuf.ListValue.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".google.protobuf.ListValue.values: object expected"); - message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a ListValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ListValue - * @static - * @param {google.protobuf.ListValue} message ListValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); - } - return object; - }; - - /** - * Converts this ListValue to JSON. - * @function toJSON - * @memberof google.protobuf.ListValue - * @instance - * @returns {Object.} JSON object - */ - ListValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ListValue; - })(); - - protobuf.DoubleValue = (function() { - - /** - * Properties of a DoubleValue. - * @memberof google.protobuf - * @interface IDoubleValue - * @property {number|null} [value] DoubleValue value - */ - - /** - * Constructs a new DoubleValue. - * @memberof google.protobuf - * @classdesc Represents a DoubleValue. - * @implements IDoubleValue - * @constructor - * @param {google.protobuf.IDoubleValue=} [properties] Properties to set - */ - function DoubleValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * DoubleValue value. - * @member {number} value - * @memberof google.protobuf.DoubleValue - * @instance - */ - DoubleValue.prototype.value = 0; - - /** - * Creates a new DoubleValue instance using the specified properties. - * @function create - * @memberof google.protobuf.DoubleValue - * @static - * @param {google.protobuf.IDoubleValue=} [properties] Properties to set - * @returns {google.protobuf.DoubleValue} DoubleValue instance - */ - DoubleValue.create = function create(properties) { - return new DoubleValue(properties); - }; - - /** - * Encodes the specified DoubleValue message. Does not implicitly {@link google.protobuf.DoubleValue.verify|verify} messages. - * @function encode - * @memberof google.protobuf.DoubleValue - * @static - * @param {google.protobuf.IDoubleValue} message DoubleValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DoubleValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 1 =*/9).double(message.value); - return writer; - }; - - /** - * Encodes the specified DoubleValue message, length delimited. Does not implicitly {@link google.protobuf.DoubleValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.DoubleValue - * @static - * @param {google.protobuf.IDoubleValue} message DoubleValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - DoubleValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a DoubleValue message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.DoubleValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.DoubleValue} DoubleValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DoubleValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.DoubleValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.double(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a DoubleValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.DoubleValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.DoubleValue} DoubleValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - DoubleValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a DoubleValue message. - * @function verify - * @memberof google.protobuf.DoubleValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - DoubleValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value !== "number") - return "value: number expected"; - return null; - }; - - /** - * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.DoubleValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.DoubleValue} DoubleValue - */ - DoubleValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DoubleValue) - return object; - var message = new $root.google.protobuf.DoubleValue(); - if (object.value != null) - message.value = Number(object.value); - return message; - }; - - /** - * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.DoubleValue - * @static - * @param {google.protobuf.DoubleValue} message DoubleValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DoubleValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; - return object; - }; - - /** - * Converts this DoubleValue to JSON. - * @function toJSON - * @memberof google.protobuf.DoubleValue - * @instance - * @returns {Object.} JSON object - */ - DoubleValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return DoubleValue; - })(); - - protobuf.FloatValue = (function() { - - /** - * Properties of a FloatValue. - * @memberof google.protobuf - * @interface IFloatValue - * @property {number|null} [value] FloatValue value - */ - - /** - * Constructs a new FloatValue. - * @memberof google.protobuf - * @classdesc Represents a FloatValue. - * @implements IFloatValue - * @constructor - * @param {google.protobuf.IFloatValue=} [properties] Properties to set - */ - function FloatValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FloatValue value. - * @member {number} value - * @memberof google.protobuf.FloatValue - * @instance - */ - FloatValue.prototype.value = 0; - - /** - * Creates a new FloatValue instance using the specified properties. - * @function create - * @memberof google.protobuf.FloatValue - * @static - * @param {google.protobuf.IFloatValue=} [properties] Properties to set - * @returns {google.protobuf.FloatValue} FloatValue instance - */ - FloatValue.create = function create(properties) { - return new FloatValue(properties); - }; - - /** - * Encodes the specified FloatValue message. Does not implicitly {@link google.protobuf.FloatValue.verify|verify} messages. - * @function encode - * @memberof google.protobuf.FloatValue - * @static - * @param {google.protobuf.IFloatValue} message FloatValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FloatValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 5 =*/13).float(message.value); - return writer; - }; - - /** - * Encodes the specified FloatValue message, length delimited. Does not implicitly {@link google.protobuf.FloatValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.FloatValue - * @static - * @param {google.protobuf.IFloatValue} message FloatValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - FloatValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a FloatValue message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.FloatValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.FloatValue} FloatValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FloatValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FloatValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.float(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a FloatValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.FloatValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.FloatValue} FloatValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - FloatValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a FloatValue message. - * @function verify - * @memberof google.protobuf.FloatValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - FloatValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value !== "number") - return "value: number expected"; - return null; - }; - - /** - * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FloatValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FloatValue} FloatValue - */ - FloatValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FloatValue) - return object; - var message = new $root.google.protobuf.FloatValue(); - if (object.value != null) - message.value = Number(object.value); - return message; - }; - - /** - * Creates a plain object from a FloatValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FloatValue - * @static - * @param {google.protobuf.FloatValue} message FloatValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FloatValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; - return object; - }; - - /** - * Converts this FloatValue to JSON. - * @function toJSON - * @memberof google.protobuf.FloatValue - * @instance - * @returns {Object.} JSON object - */ - FloatValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return FloatValue; - })(); - - protobuf.Int64Value = (function() { - - /** - * Properties of an Int64Value. - * @memberof google.protobuf - * @interface IInt64Value - * @property {number|string|null} [value] Int64Value value - */ - - /** - * Constructs a new Int64Value. - * @memberof google.protobuf - * @classdesc Represents an Int64Value. - * @implements IInt64Value - * @constructor - * @param {google.protobuf.IInt64Value=} [properties] Properties to set - */ - function Int64Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Int64Value value. - * @member {number|string} value - * @memberof google.protobuf.Int64Value - * @instance - */ - Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - - /** - * Creates a new Int64Value instance using the specified properties. - * @function create - * @memberof google.protobuf.Int64Value - * @static - * @param {google.protobuf.IInt64Value=} [properties] Properties to set - * @returns {google.protobuf.Int64Value} Int64Value instance - */ - Int64Value.create = function create(properties) { - return new Int64Value(properties); - }; - - /** - * Encodes the specified Int64Value message. Does not implicitly {@link google.protobuf.Int64Value.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Int64Value - * @static - * @param {google.protobuf.IInt64Value} message Int64Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Int64Value.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.value); - return writer; - }; - - /** - * Encodes the specified Int64Value message, length delimited. Does not implicitly {@link google.protobuf.Int64Value.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Int64Value - * @static - * @param {google.protobuf.IInt64Value} message Int64Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Int64Value.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an Int64Value message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Int64Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Int64Value} Int64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Int64Value.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Int64Value(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.int64(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an Int64Value message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Int64Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Int64Value} Int64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Int64Value.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an Int64Value message. - * @function verify - * @memberof google.protobuf.Int64Value - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Int64Value.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value) && !(message.value && $util.isInteger(message.value.low) && $util.isInteger(message.value.high))) - return "value: integer|Long expected"; - return null; - }; - - /** - * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Int64Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Int64Value} Int64Value - */ - Int64Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Int64Value) - return object; - var message = new $root.google.protobuf.Int64Value(); - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = false; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from an Int64Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Int64Value - * @static - * @param {google.protobuf.Int64Value} message Int64Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Int64Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; - return object; - }; - - /** - * Converts this Int64Value to JSON. - * @function toJSON - * @memberof google.protobuf.Int64Value - * @instance - * @returns {Object.} JSON object - */ - Int64Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Int64Value; - })(); - - protobuf.UInt64Value = (function() { - - /** - * Properties of a UInt64Value. - * @memberof google.protobuf - * @interface IUInt64Value - * @property {number|string|null} [value] UInt64Value value - */ - - /** - * Constructs a new UInt64Value. - * @memberof google.protobuf - * @classdesc Represents a UInt64Value. - * @implements IUInt64Value - * @constructor - * @param {google.protobuf.IUInt64Value=} [properties] Properties to set - */ - function UInt64Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * UInt64Value value. - * @member {number|string} value - * @memberof google.protobuf.UInt64Value - * @instance - */ - UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; - - /** - * Creates a new UInt64Value instance using the specified properties. - * @function create - * @memberof google.protobuf.UInt64Value - * @static - * @param {google.protobuf.IUInt64Value=} [properties] Properties to set - * @returns {google.protobuf.UInt64Value} UInt64Value instance - */ - UInt64Value.create = function create(properties) { - return new UInt64Value(properties); - }; - - /** - * Encodes the specified UInt64Value message. Does not implicitly {@link google.protobuf.UInt64Value.verify|verify} messages. - * @function encode - * @memberof google.protobuf.UInt64Value - * @static - * @param {google.protobuf.IUInt64Value} message UInt64Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UInt64Value.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.value); - return writer; - }; - - /** - * Encodes the specified UInt64Value message, length delimited. Does not implicitly {@link google.protobuf.UInt64Value.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.UInt64Value - * @static - * @param {google.protobuf.IUInt64Value} message UInt64Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UInt64Value.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a UInt64Value message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.UInt64Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.UInt64Value} UInt64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UInt64Value.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.UInt64Value(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.uint64(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a UInt64Value message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.UInt64Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.UInt64Value} UInt64Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UInt64Value.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a UInt64Value message. - * @function verify - * @memberof google.protobuf.UInt64Value - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - UInt64Value.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value) && !(message.value && $util.isInteger(message.value.low) && $util.isInteger(message.value.high))) - return "value: integer|Long expected"; - return null; - }; - - /** - * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UInt64Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UInt64Value} UInt64Value - */ - UInt64Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UInt64Value) - return object; - var message = new $root.google.protobuf.UInt64Value(); - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = true; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); - return message; - }; - - /** - * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UInt64Value - * @static - * @param {google.protobuf.UInt64Value} message UInt64Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UInt64Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; - return object; - }; - - /** - * Converts this UInt64Value to JSON. - * @function toJSON - * @memberof google.protobuf.UInt64Value - * @instance - * @returns {Object.} JSON object - */ - UInt64Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return UInt64Value; - })(); - - protobuf.Int32Value = (function() { - - /** - * Properties of an Int32Value. - * @memberof google.protobuf - * @interface IInt32Value - * @property {number|null} [value] Int32Value value - */ - - /** - * Constructs a new Int32Value. - * @memberof google.protobuf - * @classdesc Represents an Int32Value. - * @implements IInt32Value - * @constructor - * @param {google.protobuf.IInt32Value=} [properties] Properties to set - */ - function Int32Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Int32Value value. - * @member {number} value - * @memberof google.protobuf.Int32Value - * @instance - */ - Int32Value.prototype.value = 0; - - /** - * Creates a new Int32Value instance using the specified properties. - * @function create - * @memberof google.protobuf.Int32Value - * @static - * @param {google.protobuf.IInt32Value=} [properties] Properties to set - * @returns {google.protobuf.Int32Value} Int32Value instance - */ - Int32Value.create = function create(properties) { - return new Int32Value(properties); - }; - - /** - * Encodes the specified Int32Value message. Does not implicitly {@link google.protobuf.Int32Value.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Int32Value - * @static - * @param {google.protobuf.IInt32Value} message Int32Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Int32Value.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.value); - return writer; - }; - - /** - * Encodes the specified Int32Value message, length delimited. Does not implicitly {@link google.protobuf.Int32Value.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Int32Value - * @static - * @param {google.protobuf.IInt32Value} message Int32Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Int32Value.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an Int32Value message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Int32Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Int32Value} Int32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Int32Value.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Int32Value(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an Int32Value message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Int32Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Int32Value} Int32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Int32Value.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an Int32Value message. - * @function verify - * @memberof google.protobuf.Int32Value - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Int32Value.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - return null; - }; - - /** - * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Int32Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Int32Value} Int32Value - */ - Int32Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Int32Value) - return object; - var message = new $root.google.protobuf.Int32Value(); - if (object.value != null) - message.value = object.value | 0; - return message; - }; - - /** - * Creates a plain object from an Int32Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Int32Value - * @static - * @param {google.protobuf.Int32Value} message Int32Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Int32Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; - - /** - * Converts this Int32Value to JSON. - * @function toJSON - * @memberof google.protobuf.Int32Value - * @instance - * @returns {Object.} JSON object - */ - Int32Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Int32Value; - })(); - - protobuf.UInt32Value = (function() { - - /** - * Properties of a UInt32Value. - * @memberof google.protobuf - * @interface IUInt32Value - * @property {number|null} [value] UInt32Value value - */ - - /** - * Constructs a new UInt32Value. - * @memberof google.protobuf - * @classdesc Represents a UInt32Value. - * @implements IUInt32Value - * @constructor - * @param {google.protobuf.IUInt32Value=} [properties] Properties to set - */ - function UInt32Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * UInt32Value value. - * @member {number} value - * @memberof google.protobuf.UInt32Value - * @instance - */ - UInt32Value.prototype.value = 0; - - /** - * Creates a new UInt32Value instance using the specified properties. - * @function create - * @memberof google.protobuf.UInt32Value - * @static - * @param {google.protobuf.IUInt32Value=} [properties] Properties to set - * @returns {google.protobuf.UInt32Value} UInt32Value instance - */ - UInt32Value.create = function create(properties) { - return new UInt32Value(properties); - }; - - /** - * Encodes the specified UInt32Value message. Does not implicitly {@link google.protobuf.UInt32Value.verify|verify} messages. - * @function encode - * @memberof google.protobuf.UInt32Value - * @static - * @param {google.protobuf.IUInt32Value} message UInt32Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UInt32Value.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.value); - return writer; - }; - - /** - * Encodes the specified UInt32Value message, length delimited. Does not implicitly {@link google.protobuf.UInt32Value.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.UInt32Value - * @static - * @param {google.protobuf.IUInt32Value} message UInt32Value message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - UInt32Value.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a UInt32Value message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.UInt32Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.UInt32Value} UInt32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UInt32Value.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.UInt32Value(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.uint32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a UInt32Value message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.UInt32Value - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.UInt32Value} UInt32Value - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - UInt32Value.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a UInt32Value message. - * @function verify - * @memberof google.protobuf.UInt32Value - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - UInt32Value.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - return null; - }; - - /** - * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UInt32Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UInt32Value} UInt32Value - */ - UInt32Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UInt32Value) - return object; - var message = new $root.google.protobuf.UInt32Value(); - if (object.value != null) - message.value = object.value >>> 0; - return message; - }; - - /** - * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UInt32Value - * @static - * @param {google.protobuf.UInt32Value} message UInt32Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UInt32Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; - - /** - * Converts this UInt32Value to JSON. - * @function toJSON - * @memberof google.protobuf.UInt32Value - * @instance - * @returns {Object.} JSON object - */ - UInt32Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return UInt32Value; - })(); - - protobuf.BoolValue = (function() { - - /** - * Properties of a BoolValue. - * @memberof google.protobuf - * @interface IBoolValue - * @property {boolean|null} [value] BoolValue value - */ - - /** - * Constructs a new BoolValue. - * @memberof google.protobuf - * @classdesc Represents a BoolValue. - * @implements IBoolValue - * @constructor - * @param {google.protobuf.IBoolValue=} [properties] Properties to set - */ - function BoolValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BoolValue value. - * @member {boolean} value - * @memberof google.protobuf.BoolValue - * @instance - */ - BoolValue.prototype.value = false; - - /** - * Creates a new BoolValue instance using the specified properties. - * @function create - * @memberof google.protobuf.BoolValue - * @static - * @param {google.protobuf.IBoolValue=} [properties] Properties to set - * @returns {google.protobuf.BoolValue} BoolValue instance - */ - BoolValue.create = function create(properties) { - return new BoolValue(properties); - }; - - /** - * Encodes the specified BoolValue message. Does not implicitly {@link google.protobuf.BoolValue.verify|verify} messages. - * @function encode - * @memberof google.protobuf.BoolValue - * @static - * @param {google.protobuf.IBoolValue} message BoolValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BoolValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 0 =*/8).bool(message.value); - return writer; - }; - - /** - * Encodes the specified BoolValue message, length delimited. Does not implicitly {@link google.protobuf.BoolValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.BoolValue - * @static - * @param {google.protobuf.IBoolValue} message BoolValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BoolValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BoolValue message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.BoolValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.BoolValue} BoolValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BoolValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.BoolValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.bool(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BoolValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.BoolValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.BoolValue} BoolValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BoolValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BoolValue message. - * @function verify - * @memberof google.protobuf.BoolValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BoolValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value !== "boolean") - return "value: boolean expected"; - return null; - }; - - /** - * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.BoolValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.BoolValue} BoolValue - */ - BoolValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.BoolValue) - return object; - var message = new $root.google.protobuf.BoolValue(); - if (object.value != null) - message.value = Boolean(object.value); - return message; - }; - - /** - * Creates a plain object from a BoolValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.BoolValue - * @static - * @param {google.protobuf.BoolValue} message BoolValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BoolValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = false; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; - - /** - * Converts this BoolValue to JSON. - * @function toJSON - * @memberof google.protobuf.BoolValue - * @instance - * @returns {Object.} JSON object - */ - BoolValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return BoolValue; - })(); - - protobuf.StringValue = (function() { - - /** - * Properties of a StringValue. - * @memberof google.protobuf - * @interface IStringValue - * @property {string|null} [value] StringValue value - */ - - /** - * Constructs a new StringValue. - * @memberof google.protobuf - * @classdesc Represents a StringValue. - * @implements IStringValue - * @constructor - * @param {google.protobuf.IStringValue=} [properties] Properties to set - */ - function StringValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * StringValue value. - * @member {string} value - * @memberof google.protobuf.StringValue - * @instance - */ - StringValue.prototype.value = ""; - - /** - * Creates a new StringValue instance using the specified properties. - * @function create - * @memberof google.protobuf.StringValue - * @static - * @param {google.protobuf.IStringValue=} [properties] Properties to set - * @returns {google.protobuf.StringValue} StringValue instance - */ - StringValue.create = function create(properties) { - return new StringValue(properties); - }; - - /** - * Encodes the specified StringValue message. Does not implicitly {@link google.protobuf.StringValue.verify|verify} messages. - * @function encode - * @memberof google.protobuf.StringValue - * @static - * @param {google.protobuf.IStringValue} message StringValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - StringValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.value); - return writer; - }; - - /** - * Encodes the specified StringValue message, length delimited. Does not implicitly {@link google.protobuf.StringValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.StringValue - * @static - * @param {google.protobuf.IStringValue} message StringValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - StringValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a StringValue message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.StringValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.StringValue} StringValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - StringValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.StringValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a StringValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.StringValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.StringValue} StringValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - StringValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a StringValue message. - * @function verify - * @memberof google.protobuf.StringValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - StringValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isString(message.value)) - return "value: string expected"; - return null; - }; - - /** - * Creates a StringValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.StringValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.StringValue} StringValue - */ - StringValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.StringValue) - return object; - var message = new $root.google.protobuf.StringValue(); - if (object.value != null) - message.value = String(object.value); - return message; - }; - - /** - * Creates a plain object from a StringValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.StringValue - * @static - * @param {google.protobuf.StringValue} message StringValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - StringValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = ""; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; - - /** - * Converts this StringValue to JSON. - * @function toJSON - * @memberof google.protobuf.StringValue - * @instance - * @returns {Object.} JSON object - */ - StringValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return StringValue; - })(); - - protobuf.BytesValue = (function() { - - /** - * Properties of a BytesValue. - * @memberof google.protobuf - * @interface IBytesValue - * @property {Uint8Array|null} [value] BytesValue value - */ - - /** - * Constructs a new BytesValue. - * @memberof google.protobuf - * @classdesc Represents a BytesValue. - * @implements IBytesValue - * @constructor - * @param {google.protobuf.IBytesValue=} [properties] Properties to set - */ - function BytesValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BytesValue value. - * @member {Uint8Array} value - * @memberof google.protobuf.BytesValue - * @instance - */ - BytesValue.prototype.value = $util.newBuffer([]); - - /** - * Creates a new BytesValue instance using the specified properties. - * @function create - * @memberof google.protobuf.BytesValue - * @static - * @param {google.protobuf.IBytesValue=} [properties] Properties to set - * @returns {google.protobuf.BytesValue} BytesValue instance - */ - BytesValue.create = function create(properties) { - return new BytesValue(properties); - }; - - /** - * Encodes the specified BytesValue message. Does not implicitly {@link google.protobuf.BytesValue.verify|verify} messages. - * @function encode - * @memberof google.protobuf.BytesValue - * @static - * @param {google.protobuf.IBytesValue} message BytesValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BytesValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.value); - return writer; - }; - - /** - * Encodes the specified BytesValue message, length delimited. Does not implicitly {@link google.protobuf.BytesValue.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.BytesValue - * @static - * @param {google.protobuf.IBytesValue} message BytesValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BytesValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BytesValue message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.BytesValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.BytesValue} BytesValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BytesValue.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.BytesValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.value = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BytesValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.BytesValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.BytesValue} BytesValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BytesValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BytesValue message. - * @function verify - * @memberof google.protobuf.BytesValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BytesValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!(message.value && typeof message.value.length === "number" || $util.isString(message.value))) - return "value: buffer expected"; - return null; - }; - - /** - * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.BytesValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.BytesValue} BytesValue - */ - BytesValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.BytesValue) - return object; - var message = new $root.google.protobuf.BytesValue(); - if (object.value != null) - if (typeof object.value === "string") - $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); - else if (object.value.length) - message.value = object.value; - return message; - }; - - /** - * Creates a plain object from a BytesValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.BytesValue - * @static - * @param {google.protobuf.BytesValue} message BytesValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BytesValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = options.bytes === String ? "" : []; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; - return object; - }; - - /** - * Converts this BytesValue to JSON. - * @function toJSON - * @memberof google.protobuf.BytesValue - * @instance - * @returns {Object.} JSON object - */ - BytesValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return BytesValue; - })(); - - protobuf.Empty = (function() { - - /** - * Properties of an Empty. - * @memberof google.protobuf - * @interface IEmpty - */ - - /** - * Constructs a new Empty. - * @memberof google.protobuf - * @classdesc Represents an Empty. - * @implements IEmpty - * @constructor - * @param {google.protobuf.IEmpty=} [properties] Properties to set - */ - function Empty(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Creates a new Empty instance using the specified properties. - * @function create - * @memberof google.protobuf.Empty - * @static - * @param {google.protobuf.IEmpty=} [properties] Properties to set - * @returns {google.protobuf.Empty} Empty instance - */ - Empty.create = function create(properties) { - return new Empty(properties); - }; - - /** - * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Empty - * @static - * @param {google.protobuf.IEmpty} message Empty message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Empty.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - return writer; - }; - - /** - * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Empty - * @static - * @param {google.protobuf.IEmpty} message Empty message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Empty.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an Empty message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Empty - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Empty} Empty - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Empty.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Empty(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an Empty message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Empty - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Empty} Empty - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Empty.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an Empty message. - * @function verify - * @memberof google.protobuf.Empty - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Empty.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - return null; - }; - - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Empty - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Empty} Empty - */ - Empty.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Empty) - return object; - return new $root.google.protobuf.Empty(); - }; - - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Empty - * @static - * @param {google.protobuf.Empty} message Empty - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Empty.toObject = function toObject() { - return {}; - }; - - /** - * Converts this Empty to JSON. - * @function toJSON - * @memberof google.protobuf.Empty - * @instance - * @returns {Object.} JSON object - */ - Empty.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Empty; - })(); - - protobuf.Any = (function() { - - /** - * Properties of an Any. - * @memberof google.protobuf - * @interface IAny - * @property {string|null} [type_url] Any type_url - * @property {Uint8Array|null} [value] Any value - */ - - /** - * Constructs a new Any. - * @memberof google.protobuf - * @classdesc Represents an Any. - * @implements IAny - * @constructor - * @param {google.protobuf.IAny=} [properties] Properties to set - */ - function Any(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Any type_url. - * @member {string} type_url - * @memberof google.protobuf.Any - * @instance - */ - Any.prototype.type_url = ""; - - /** - * Any value. - * @member {Uint8Array} value - * @memberof google.protobuf.Any - * @instance - */ - Any.prototype.value = $util.newBuffer([]); - - /** - * Creates a new Any instance using the specified properties. - * @function create - * @memberof google.protobuf.Any - * @static - * @param {google.protobuf.IAny=} [properties] Properties to set - * @returns {google.protobuf.Any} Any instance - */ - Any.create = function create(properties) { - return new Any(properties); - }; - - /** - * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. - * @function encode - * @memberof google.protobuf.Any - * @static - * @param {google.protobuf.IAny} message Any message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Any.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.type_url != null && message.hasOwnProperty("type_url")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.type_url); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.value); - return writer; - }; - - /** - * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.Any - * @static - * @param {google.protobuf.IAny} message Any message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Any.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes an Any message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.Any - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.Any} Any - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Any.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.Any(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.type_url = reader.string(); - break; - case 2: - message.value = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes an Any message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.protobuf.Any - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.protobuf.Any} Any - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Any.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies an Any message. - * @function verify - * @memberof google.protobuf.Any - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Any.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.type_url != null && message.hasOwnProperty("type_url")) - if (!$util.isString(message.type_url)) - return "type_url: string expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!(message.value && typeof message.value.length === "number" || $util.isString(message.value))) - return "value: buffer expected"; - return null; - }; - - /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Any - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Any} Any - */ - Any.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Any) - return object; - var message = new $root.google.protobuf.Any(); - if (object.type_url != null) - message.type_url = String(object.type_url); - if (object.value != null) - if (typeof object.value === "string") - $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); - else if (object.value.length) - message.value = object.value; - return message; - }; - - /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Any - * @static - * @param {google.protobuf.Any} message Any - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Any.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.type_url = ""; - object.value = options.bytes === String ? "" : []; - } - if (message.type_url != null && message.hasOwnProperty("type_url")) - object.type_url = message.type_url; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; - return object; - }; - - /** - * Converts this Any to JSON. - * @function toJSON - * @memberof google.protobuf.Any - * @instance - * @returns {Object.} JSON object - */ - Any.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Any; - })(); - - return protobuf; - })(); - - google.type = (function() { - - /** - * Namespace type. - * @memberof google - * @namespace - */ - var type = {}; - - type.LatLng = (function() { - - /** - * Properties of a LatLng. - * @memberof google.type - * @interface ILatLng - * @property {number|null} [latitude] LatLng latitude - * @property {number|null} [longitude] LatLng longitude - */ - - /** - * Constructs a new LatLng. - * @memberof google.type - * @classdesc Represents a LatLng. - * @implements ILatLng - * @constructor - * @param {google.type.ILatLng=} [properties] Properties to set - */ - function LatLng(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * LatLng latitude. - * @member {number} latitude - * @memberof google.type.LatLng - * @instance - */ - LatLng.prototype.latitude = 0; - - /** - * LatLng longitude. - * @member {number} longitude - * @memberof google.type.LatLng - * @instance - */ - LatLng.prototype.longitude = 0; - - /** - * Creates a new LatLng instance using the specified properties. - * @function create - * @memberof google.type.LatLng - * @static - * @param {google.type.ILatLng=} [properties] Properties to set - * @returns {google.type.LatLng} LatLng instance - */ - LatLng.create = function create(properties) { - return new LatLng(properties); - }; - - /** - * Encodes the specified LatLng message. Does not implicitly {@link google.type.LatLng.verify|verify} messages. - * @function encode - * @memberof google.type.LatLng - * @static - * @param {google.type.ILatLng} message LatLng message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - LatLng.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.latitude != null && message.hasOwnProperty("latitude")) - writer.uint32(/* id 1, wireType 1 =*/9).double(message.latitude); - if (message.longitude != null && message.hasOwnProperty("longitude")) - writer.uint32(/* id 2, wireType 1 =*/17).double(message.longitude); - return writer; - }; - - /** - * Encodes the specified LatLng message, length delimited. Does not implicitly {@link google.type.LatLng.verify|verify} messages. - * @function encodeDelimited - * @memberof google.type.LatLng - * @static - * @param {google.type.ILatLng} message LatLng message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - LatLng.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a LatLng message from the specified reader or buffer. - * @function decode - * @memberof google.type.LatLng - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.type.LatLng} LatLng - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - LatLng.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.type.LatLng(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.latitude = reader.double(); - break; - case 2: - message.longitude = reader.double(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a LatLng message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.type.LatLng - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.type.LatLng} LatLng - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - LatLng.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a LatLng message. - * @function verify - * @memberof google.type.LatLng - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - LatLng.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.latitude != null && message.hasOwnProperty("latitude")) - if (typeof message.latitude !== "number") - return "latitude: number expected"; - if (message.longitude != null && message.hasOwnProperty("longitude")) - if (typeof message.longitude !== "number") - return "longitude: number expected"; - return null; - }; - - /** - * Creates a LatLng message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.type.LatLng - * @static - * @param {Object.} object Plain object - * @returns {google.type.LatLng} LatLng - */ - LatLng.fromObject = function fromObject(object) { - if (object instanceof $root.google.type.LatLng) - return object; - var message = new $root.google.type.LatLng(); - if (object.latitude != null) - message.latitude = Number(object.latitude); - if (object.longitude != null) - message.longitude = Number(object.longitude); - return message; - }; - - /** - * Creates a plain object from a LatLng message. Also converts values to other types if specified. - * @function toObject - * @memberof google.type.LatLng - * @static - * @param {google.type.LatLng} message LatLng - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - LatLng.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.latitude = 0; - object.longitude = 0; - } - if (message.latitude != null && message.hasOwnProperty("latitude")) - object.latitude = options.json && !isFinite(message.latitude) ? String(message.latitude) : message.latitude; - if (message.longitude != null && message.hasOwnProperty("longitude")) - object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; - return object; - }; - - /** - * Converts this LatLng to JSON. - * @function toJSON - * @memberof google.type.LatLng - * @instance - * @returns {Object.} JSON object - */ - LatLng.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return LatLng; - })(); - - return type; - })(); - - google.rpc = (function() { - - /** - * Namespace rpc. - * @memberof google - * @namespace - */ - var rpc = {}; - - rpc.Status = (function() { - - /** - * Properties of a Status. - * @memberof google.rpc - * @interface IStatus - * @property {number|null} [code] Status code - * @property {string|null} [message] Status message - * @property {Array.|null} [details] Status details - */ - - /** - * Constructs a new Status. - * @memberof google.rpc - * @classdesc Represents a Status. - * @implements IStatus - * @constructor - * @param {google.rpc.IStatus=} [properties] Properties to set - */ - function Status(properties) { - this.details = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Status code. - * @member {number} code - * @memberof google.rpc.Status - * @instance - */ - Status.prototype.code = 0; - - /** - * Status message. - * @member {string} message - * @memberof google.rpc.Status - * @instance - */ - Status.prototype.message = ""; - - /** - * Status details. - * @member {Array.} details - * @memberof google.rpc.Status - * @instance - */ - Status.prototype.details = $util.emptyArray; - - /** - * Creates a new Status instance using the specified properties. - * @function create - * @memberof google.rpc.Status - * @static - * @param {google.rpc.IStatus=} [properties] Properties to set - * @returns {google.rpc.Status} Status instance - */ - Status.create = function create(properties) { - return new Status(properties); - }; - - /** - * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. - * @function encode - * @memberof google.rpc.Status - * @static - * @param {google.rpc.IStatus} message Status message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Status.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.code != null && message.hasOwnProperty("code")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.code); - if (message.message != null && message.hasOwnProperty("message")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.message); - if (message.details != null && message.details.length) - for (var i = 0; i < message.details.length; ++i) - $root.google.protobuf.Any.encode(message.details[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. - * @function encodeDelimited - * @memberof google.rpc.Status - * @static - * @param {google.rpc.IStatus} message Status message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Status.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a Status message from the specified reader or buffer. - * @function decode - * @memberof google.rpc.Status - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.rpc.Status} Status - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Status.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.rpc.Status(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.code = reader.int32(); - break; - case 2: - message.message = reader.string(); - break; - case 3: - if (!(message.details && message.details.length)) - message.details = []; - message.details.push($root.google.protobuf.Any.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a Status message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.rpc.Status - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.rpc.Status} Status - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Status.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a Status message. - * @function verify - * @memberof google.rpc.Status - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Status.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.code != null && message.hasOwnProperty("code")) - if (!$util.isInteger(message.code)) - return "code: integer expected"; - if (message.message != null && message.hasOwnProperty("message")) - if (!$util.isString(message.message)) - return "message: string expected"; - if (message.details != null && message.hasOwnProperty("details")) { - if (!Array.isArray(message.details)) - return "details: array expected"; - for (var i = 0; i < message.details.length; ++i) { - var error = $root.google.protobuf.Any.verify(message.details[i]); - if (error) - return "details." + error; - } - } - return null; - }; - - /** - * Creates a Status message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.rpc.Status - * @static - * @param {Object.} object Plain object - * @returns {google.rpc.Status} Status - */ - Status.fromObject = function fromObject(object) { - if (object instanceof $root.google.rpc.Status) - return object; - var message = new $root.google.rpc.Status(); - if (object.code != null) - message.code = object.code | 0; - if (object.message != null) - message.message = String(object.message); - if (object.details) { - if (!Array.isArray(object.details)) - throw TypeError(".google.rpc.Status.details: array expected"); - message.details = []; - for (var i = 0; i < object.details.length; ++i) { - if (typeof object.details[i] !== "object") - throw TypeError(".google.rpc.Status.details: object expected"); - message.details[i] = $root.google.protobuf.Any.fromObject(object.details[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a Status message. Also converts values to other types if specified. - * @function toObject - * @memberof google.rpc.Status - * @static - * @param {google.rpc.Status} message Status - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Status.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.details = []; - if (options.defaults) { - object.code = 0; - object.message = ""; - } - if (message.code != null && message.hasOwnProperty("code")) - object.code = message.code; - if (message.message != null && message.hasOwnProperty("message")) - object.message = message.message; - if (message.details && message.details.length) { - object.details = []; - for (var j = 0; j < message.details.length; ++j) - object.details[j] = $root.google.protobuf.Any.toObject(message.details[j], options); - } - return object; - }; - - /** - * Converts this Status to JSON. - * @function toJSON - * @memberof google.rpc.Status - * @instance - * @returns {Object.} JSON object - */ - Status.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return Status; - })(); - - return rpc; - })(); - - return google; -})(); - -module.exports = $root; diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/.DS_Store b/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/.DS_Store deleted file mode 100644 index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 fields = 2; - - // Output only. The time at which the document was created. - // - // This value increases monotonically when a document is deleted then - // recreated. It can also be compared to values from other documents and - // the `read_time` of a query. - google.protobuf.Timestamp create_time = 3; - - // Output only. The time at which the document was last changed. - // - // This value is initially set to the `create_time` then increases - // monotonically with each change to the document. It can also be - // compared to values from other documents and the `read_time` of a query. - google.protobuf.Timestamp update_time = 4; -} - -// A message that can hold any of the supported value types. -message Value { - // Must have a value set. - oneof value_type { - // A null value. - google.protobuf.NullValue null_value = 11; - - // A boolean value. - bool boolean_value = 1; - - // An integer value. - int64 integer_value = 2; - - // A double value. - double double_value = 3; - - // A timestamp value. - // - // Precise only to microseconds. When stored, any additional precision is - // rounded down. - google.protobuf.Timestamp timestamp_value = 10; - - // A string value. - // - // The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. - // Only the first 1,500 bytes of the UTF-8 representation are considered by - // queries. - string string_value = 17; - - // A bytes value. - // - // Must not exceed 1 MiB - 89 bytes. - // Only the first 1,500 bytes are considered by queries. - bytes bytes_value = 18; - - // A reference to a document. For example: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - string reference_value = 5; - - // A geo point value representing a point on the surface of Earth. - google.type.LatLng geo_point_value = 8; - - // An array value. - // - // Cannot directly contain another array value, though can contain an - // map which contains another array. - ArrayValue array_value = 9; - - // A map value. - MapValue map_value = 6; - } -} - -// An array value. -message ArrayValue { - // Values in the array. - repeated Value values = 1; -} - -// A map value. -message MapValue { - // The map's fields. - // - // The map keys represent field names. Field names matching the regular - // expression `__.*__` are reserved. Reserved field names are forbidden except - // in certain documented contexts. The map keys, represented as UTF-8, must - // not exceed 1,500 bytes and cannot be empty. - map fields = 1; -} diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto b/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto deleted file mode 100644 index 7b6c8914..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/firestore.proto +++ /dev/null @@ -1,760 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.firestore.v1beta1; - -import "google/api/annotations.proto"; -import "google/firestore/v1beta1/common.proto"; -import "google/firestore/v1beta1/document.proto"; -import "google/firestore/v1beta1/query.proto"; -import "google/firestore/v1beta1/write.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; - -option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/firestore/v1beta1;firestore"; -option java_multiple_files = true; -option java_outer_classname = "FirestoreProto"; -option java_package = "com.google.firestore.v1beta1"; -option objc_class_prefix = "GCFS"; -option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; -// Specification of the Firestore API. - -// The Cloud Firestore service. -// -// This service exposes several types of comparable timestamps: -// -// * `create_time` - The time at which a document was created. Changes only -// when a document is deleted, then re-created. Increases in a strict -// monotonic fashion. -// * `update_time` - The time at which a document was last updated. Changes -// every time a document is modified. Does not change when a write results -// in no modifications. Increases in a strict monotonic fashion. -// * `read_time` - The time at which a particular state was observed. Used -// to denote a consistent snapshot of the database or the time at which a -// Document was observed to not exist. -// * `commit_time` - The time at which the writes in a transaction were -// committed. Any read with an equal or greater `read_time` is guaranteed -// to see the effects of the transaction. -service Firestore { - // Gets a single document. - rpc GetDocument(GetDocumentRequest) returns (Document) { - option (google.api.http) = { - get: "/v1beta1/{name=projects/*/databases/*/documents/*/**}" - }; - } - - // Lists documents. - rpc ListDocuments(ListDocumentsRequest) returns (ListDocumentsResponse) { - option (google.api.http) = { - get: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" - }; - } - - // Creates a new document. - rpc CreateDocument(CreateDocumentRequest) returns (Document) { - option (google.api.http) = { - post: "/v1beta1/{parent=projects/*/databases/*/documents/**}/{collection_id}" - body: "document" - }; - } - - // Updates or inserts a document. - rpc UpdateDocument(UpdateDocumentRequest) returns (Document) { - option (google.api.http) = { - patch: "/v1beta1/{document.name=projects/*/databases/*/documents/*/**}" - body: "document" - }; - } - - // Deletes a document. - rpc DeleteDocument(DeleteDocumentRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1beta1/{name=projects/*/databases/*/documents/*/**}" - }; - } - - // Gets multiple documents. - // - // Documents returned by this method are not guaranteed to be returned in the - // same order that they were requested. - rpc BatchGetDocuments(BatchGetDocumentsRequest) returns (stream BatchGetDocumentsResponse) { - option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}/documents:batchGet" - body: "*" - }; - } - - // Starts a new transaction. - rpc BeginTransaction(BeginTransactionRequest) returns (BeginTransactionResponse) { - option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}/documents:beginTransaction" - body: "*" - }; - } - - // Commits a transaction, while optionally updating documents. - rpc Commit(CommitRequest) returns (CommitResponse) { - option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}/documents:commit" - body: "*" - }; - } - - // Rolls back a transaction. - rpc Rollback(RollbackRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}/documents:rollback" - body: "*" - }; - } - - // Runs a query. - rpc RunQuery(RunQueryRequest) returns (stream RunQueryResponse) { - option (google.api.http) = { - post: "/v1beta1/{parent=projects/*/databases/*/documents}:runQuery" - body: "*" - additional_bindings { - post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:runQuery" - body: "*" - } - }; - } - - // Streams batches of document updates and deletes, in order. - rpc Write(stream WriteRequest) returns (stream WriteResponse) { - option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}/documents:write" - body: "*" - }; - } - - // Listens to changes. - rpc Listen(stream ListenRequest) returns (stream ListenResponse) { - option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}/documents:listen" - body: "*" - }; - } - - // Lists all the collection IDs underneath a document. - rpc ListCollectionIds(ListCollectionIdsRequest) returns (ListCollectionIdsResponse) { - option (google.api.http) = { - post: "/v1beta1/{parent=projects/*/databases/*/documents}:listCollectionIds" - body: "*" - additional_bindings { - post: "/v1beta1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds" - body: "*" - } - }; - } -} - -// The request for [Firestore.GetDocument][google.firestore.v1beta1.Firestore.GetDocument]. -message GetDocumentRequest { - // The resource name of the Document to get. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - string name = 1; - - // The fields to return. If not set, returns all fields. - // - // If the document has a field that is not present in this mask, that field - // will not be returned in the response. - DocumentMask mask = 2; - - // The consistency mode for this transaction. - // If not set, defaults to strong consistency. - oneof consistency_selector { - // Reads the document in a transaction. - bytes transaction = 3; - - // Reads the version of the document at the given time. - // This may not be older than 60 seconds. - google.protobuf.Timestamp read_time = 5; - } -} - -// The request for [Firestore.ListDocuments][google.firestore.v1beta1.Firestore.ListDocuments]. -message ListDocumentsRequest { - // The parent resource name. In the format: - // `projects/{project_id}/databases/{database_id}/documents` or - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - // For example: - // `projects/my-project/databases/my-database/documents` or - // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - string parent = 1; - - // The collection ID, relative to `parent`, to list. For example: `chatrooms` - // or `messages`. - string collection_id = 2; - - // The maximum number of documents to return. - int32 page_size = 3; - - // The `next_page_token` value returned from a previous List request, if any. - string page_token = 4; - - // The order to sort results by. For example: `priority desc, name`. - string order_by = 6; - - // The fields to return. If not set, returns all fields. - // - // If a document has a field that is not present in this mask, that field - // will not be returned in the response. - DocumentMask mask = 7; - - // The consistency mode for this transaction. - // If not set, defaults to strong consistency. - oneof consistency_selector { - // Reads documents in a transaction. - bytes transaction = 8; - - // Reads documents as they were at the given time. - // This may not be older than 60 seconds. - google.protobuf.Timestamp read_time = 10; - } - - // If the list should show missing documents. A missing document is a - // document that does not exist but has sub-documents. These documents will - // be returned with a key but will not have fields, [Document.create_time][google.firestore.v1beta1.Document.create_time], - // or [Document.update_time][google.firestore.v1beta1.Document.update_time] set. - // - // Requests with `show_missing` may not specify `where` or - // `order_by`. - bool show_missing = 12; -} - -// The response for [Firestore.ListDocuments][google.firestore.v1beta1.Firestore.ListDocuments]. -message ListDocumentsResponse { - // The Documents found. - repeated Document documents = 1; - - // The next page token. - string next_page_token = 2; -} - -// The request for [Firestore.CreateDocument][google.firestore.v1beta1.Firestore.CreateDocument]. -message CreateDocumentRequest { - // The parent resource. For example: - // `projects/{project_id}/databases/{database_id}/documents` or - // `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` - string parent = 1; - - // The collection ID, relative to `parent`, to list. For example: `chatrooms`. - string collection_id = 2; - - // The client-assigned document ID to use for this document. - // - // Optional. If not specified, an ID will be assigned by the service. - string document_id = 3; - - // The document to create. `name` must not be set. - Document document = 4; - - // The fields to return. If not set, returns all fields. - // - // If the document has a field that is not present in this mask, that field - // will not be returned in the response. - DocumentMask mask = 5; -} - -// The request for [Firestore.UpdateDocument][google.firestore.v1beta1.Firestore.UpdateDocument]. -message UpdateDocumentRequest { - // The updated document. - // Creates the document if it does not already exist. - Document document = 1; - - // The fields to update. - // None of the field paths in the mask may contain a reserved name. - // - // If the document exists on the server and has fields not referenced in the - // mask, they are left unchanged. - // Fields referenced in the mask, but not present in the input document, are - // deleted from the document on the server. - DocumentMask update_mask = 2; - - // The fields to return. If not set, returns all fields. - // - // If the document has a field that is not present in this mask, that field - // will not be returned in the response. - DocumentMask mask = 3; - - // An optional precondition on the document. - // The request will fail if this is set and not met by the target document. - Precondition current_document = 4; -} - -// The request for [Firestore.DeleteDocument][google.firestore.v1beta1.Firestore.DeleteDocument]. -message DeleteDocumentRequest { - // The resource name of the Document to delete. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - string name = 1; - - // An optional precondition on the document. - // The request will fail if this is set and not met by the target document. - Precondition current_document = 2; -} - -// The request for [Firestore.BatchGetDocuments][google.firestore.v1beta1.Firestore.BatchGetDocuments]. -message BatchGetDocumentsRequest { - // The database name. In the format: - // `projects/{project_id}/databases/{database_id}`. - string database = 1; - - // The names of the documents to retrieve. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - // The request will fail if any of the document is not a child resource of the - // given `database`. Duplicate names will be elided. - repeated string documents = 2; - - // The fields to return. If not set, returns all fields. - // - // If a document has a field that is not present in this mask, that field will - // not be returned in the response. - DocumentMask mask = 3; - - // The consistency mode for this transaction. - // If not set, defaults to strong consistency. - oneof consistency_selector { - // Reads documents in a transaction. - bytes transaction = 4; - - // Starts a new transaction and reads the documents. - // Defaults to a read-only transaction. - // The new transaction ID will be returned as the first response in the - // stream. - TransactionOptions new_transaction = 5; - - // Reads documents as they were at the given time. - // This may not be older than 60 seconds. - google.protobuf.Timestamp read_time = 7; - } -} - -// The streamed response for [Firestore.BatchGetDocuments][google.firestore.v1beta1.Firestore.BatchGetDocuments]. -message BatchGetDocumentsResponse { - // A single result. - // This can be empty if the server is just returning a transaction. - oneof result { - // A document that was requested. - Document found = 1; - - // A document name that was requested but does not exist. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - string missing = 2; - } - - // The transaction that was started as part of this request. - // Will only be set in the first response, and only if - // [BatchGetDocumentsRequest.new_transaction][google.firestore.v1beta1.BatchGetDocumentsRequest.new_transaction] was set in the request. - bytes transaction = 3; - - // The time at which the document was read. - // This may be monotically increasing, in this case the previous documents in - // the result stream are guaranteed not to have changed between their - // read_time and this one. - google.protobuf.Timestamp read_time = 4; -} - -// The request for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction]. -message BeginTransactionRequest { - // The database name. In the format: - // `projects/{project_id}/databases/{database_id}`. - string database = 1; - - // The options for the transaction. - // Defaults to a read-write transaction. - TransactionOptions options = 2; -} - -// The response for [Firestore.BeginTransaction][google.firestore.v1beta1.Firestore.BeginTransaction]. -message BeginTransactionResponse { - // The transaction that was started. - bytes transaction = 1; -} - -// The request for [Firestore.Commit][google.firestore.v1beta1.Firestore.Commit]. -message CommitRequest { - // The database name. In the format: - // `projects/{project_id}/databases/{database_id}`. - string database = 1; - - // The writes to apply. - // - // Always executed atomically and in order. - repeated Write writes = 2; - - // If set, applies all writes in this transaction, and commits it. - bytes transaction = 3; -} - -// The response for [Firestore.Commit][google.firestore.v1beta1.Firestore.Commit]. -message CommitResponse { - // The result of applying the writes. - // - // This i-th write result corresponds to the i-th write in the - // request. - repeated WriteResult write_results = 1; - - // The time at which the commit occurred. - google.protobuf.Timestamp commit_time = 2; -} - -// The request for [Firestore.Rollback][google.firestore.v1beta1.Firestore.Rollback]. -message RollbackRequest { - // The database name. In the format: - // `projects/{project_id}/databases/{database_id}`. - string database = 1; - - // The transaction to roll back. - bytes transaction = 2; -} - -// The request for [Firestore.RunQuery][google.firestore.v1beta1.Firestore.RunQuery]. -message RunQueryRequest { - // The parent resource name. In the format: - // `projects/{project_id}/databases/{database_id}/documents` or - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - // For example: - // `projects/my-project/databases/my-database/documents` or - // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - string parent = 1; - - // The query to run. - oneof query_type { - // A structured query. - StructuredQuery structured_query = 2; - } - - // The consistency mode for this transaction. - // If not set, defaults to strong consistency. - oneof consistency_selector { - // Reads documents in a transaction. - bytes transaction = 5; - - // Starts a new transaction and reads the documents. - // Defaults to a read-only transaction. - // The new transaction ID will be returned as the first response in the - // stream. - TransactionOptions new_transaction = 6; - - // Reads documents as they were at the given time. - // This may not be older than 60 seconds. - google.protobuf.Timestamp read_time = 7; - } -} - -// The response for [Firestore.RunQuery][google.firestore.v1beta1.Firestore.RunQuery]. -message RunQueryResponse { - // The transaction that was started as part of this request. - // Can only be set in the first response, and only if - // [RunQueryRequest.new_transaction][google.firestore.v1beta1.RunQueryRequest.new_transaction] was set in the request. - // If set, no other fields will be set in this response. - bytes transaction = 2; - - // A query result. - // Not set when reporting partial progress. - Document document = 1; - - // The time at which the document was read. This may be monotonically - // increasing; in this case, the previous documents in the result stream are - // guaranteed not to have changed between their `read_time` and this one. - // - // If the query returns no results, a response with `read_time` and no - // `document` will be sent, and this represents the time at which the query - // was run. - google.protobuf.Timestamp read_time = 3; - - // The number of results that have been skipped due to an offset between - // the last response and the current response. - int32 skipped_results = 4; -} - -// The request for [Firestore.Write][google.firestore.v1beta1.Firestore.Write]. -// -// The first request creates a stream, or resumes an existing one from a token. -// -// When creating a new stream, the server replies with a response containing -// only an ID and a token, to use in the next request. -// -// When resuming a stream, the server first streams any responses later than the -// given token, then a response containing only an up-to-date token, to use in -// the next request. -message WriteRequest { - // The database name. In the format: - // `projects/{project_id}/databases/{database_id}`. - // This is only required in the first message. - string database = 1; - - // The ID of the write stream to resume. - // This may only be set in the first message. When left empty, a new write - // stream will be created. - string stream_id = 2; - - // The writes to apply. - // - // Always executed atomically and in order. - // This must be empty on the first request. - // This may be empty on the last request. - // This must not be empty on all other requests. - repeated Write writes = 3; - - // A stream token that was previously sent by the server. - // - // The client should set this field to the token from the most recent - // [WriteResponse][google.firestore.v1beta1.WriteResponse] it has received. This acknowledges that the client has - // received responses up to this token. After sending this token, earlier - // tokens may not be used anymore. - // - // The server may close the stream if there are too many unacknowledged - // responses. - // - // Leave this field unset when creating a new stream. To resume a stream at - // a specific point, set this field and the `stream_id` field. - // - // Leave this field unset when creating a new stream. - bytes stream_token = 4; - - // Labels associated with this write request. - map labels = 5; -} - -// The response for [Firestore.Write][google.firestore.v1beta1.Firestore.Write]. -message WriteResponse { - // The ID of the stream. - // Only set on the first message, when a new stream was created. - string stream_id = 1; - - // A token that represents the position of this response in the stream. - // This can be used by a client to resume the stream at this point. - // - // This field is always set. - bytes stream_token = 2; - - // The result of applying the writes. - // - // This i-th write result corresponds to the i-th write in the - // request. - repeated WriteResult write_results = 3; - - // The time at which the commit occurred. - google.protobuf.Timestamp commit_time = 4; -} - -// A request for [Firestore.Listen][google.firestore.v1beta1.Firestore.Listen] -message ListenRequest { - // The database name. In the format: - // `projects/{project_id}/databases/{database_id}`. - string database = 1; - - // The supported target changes. - oneof target_change { - // A target to add to this stream. - Target add_target = 2; - - // The ID of a target to remove from this stream. - int32 remove_target = 3; - } - - // Labels associated with this target change. - map labels = 4; -} - -// The response for [Firestore.Listen][google.firestore.v1beta1.Firestore.Listen]. -message ListenResponse { - // The supported responses. - oneof response_type { - // Targets have changed. - TargetChange target_change = 2; - - // A [Document][google.firestore.v1beta1.Document] has changed. - DocumentChange document_change = 3; - - // A [Document][google.firestore.v1beta1.Document] has been deleted. - DocumentDelete document_delete = 4; - - // A [Document][google.firestore.v1beta1.Document] has been removed from a target (because it is no longer - // relevant to that target). - DocumentRemove document_remove = 6; - - // A filter to apply to the set of documents previously returned for the - // given target. - // - // Returned when documents may have been removed from the given target, but - // the exact documents are unknown. - ExistenceFilter filter = 5; - } -} - -// A specification of a set of documents to listen to. -message Target { - // A target specified by a set of documents names. - message DocumentsTarget { - // The names of the documents to retrieve. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - // The request will fail if any of the document is not a child resource of - // the given `database`. Duplicate names will be elided. - repeated string documents = 2; - } - - // A target specified by a query. - message QueryTarget { - // The parent resource name. In the format: - // `projects/{project_id}/databases/{database_id}/documents` or - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - // For example: - // `projects/my-project/databases/my-database/documents` or - // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - string parent = 1; - - // The query to run. - oneof query_type { - // A structured query. - StructuredQuery structured_query = 2; - } - } - - // The type of target to listen to. - oneof target_type { - // A target specified by a query. - QueryTarget query = 2; - - // A target specified by a set of document names. - DocumentsTarget documents = 3; - } - - // When to start listening. - // - // If not specified, all matching Documents are returned before any - // subsequent changes. - oneof resume_type { - // A resume token from a prior [TargetChange][google.firestore.v1beta1.TargetChange] for an identical target. - // - // Using a resume token with a different target is unsupported and may fail. - bytes resume_token = 4; - - // Start listening after a specific `read_time`. - // - // The client must know the state of matching documents at this time. - google.protobuf.Timestamp read_time = 11; - } - - // A client provided target ID. - // - // If not set, the server will assign an ID for the target. - // - // Used for resuming a target without changing IDs. The IDs can either be - // client-assigned or be server-assigned in a previous stream. All targets - // with client provided IDs must be added before adding a target that needs - // a server-assigned id. - int32 target_id = 5; - - // If the target should be removed once it is current and consistent. - bool once = 6; -} - -// Targets being watched have changed. -message TargetChange { - // The type of change. - enum TargetChangeType { - // No change has occurred. Used only to send an updated `resume_token`. - NO_CHANGE = 0; - - // The targets have been added. - ADD = 1; - - // The targets have been removed. - REMOVE = 2; - - // The targets reflect all changes committed before the targets were added - // to the stream. - // - // This will be sent after or with a `read_time` that is greater than or - // equal to the time at which the targets were added. - // - // Listeners can wait for this change if read-after-write semantics - // are desired. - CURRENT = 3; - - // The targets have been reset, and a new initial state for the targets - // will be returned in subsequent changes. - // - // After the initial state is complete, `CURRENT` will be returned even - // if the target was previously indicated to be `CURRENT`. - RESET = 4; - } - - // The type of change that occurred. - TargetChangeType target_change_type = 1; - - // The target IDs of targets that have changed. - // - // If empty, the change applies to all targets. - // - // For `target_change_type=ADD`, the order of the target IDs matches the order - // of the requests to add the targets. This allows clients to unambiguously - // associate server-assigned target IDs with added targets. - // - // For other states, the order of the target IDs is not defined. - repeated int32 target_ids = 2; - - // The error that resulted in this change, if applicable. - google.rpc.Status cause = 3; - - // A token that can be used to resume the stream for the given `target_ids`, - // or all targets if `target_ids` is empty. - // - // Not set on every target change. - bytes resume_token = 4; - - // The consistent `read_time` for the given `target_ids` (omitted when the - // target_ids are not at a consistent snapshot). - // - // The stream is guaranteed to send a `read_time` with `target_ids` empty - // whenever the entire stream reaches a new consistent snapshot. ADD, - // CURRENT, and RESET messages are guaranteed to (eventually) result in a - // new consistent snapshot (while NO_CHANGE and REMOVE messages are not). - // - // For a given stream, `read_time` is guaranteed to be monotonically - // increasing. - google.protobuf.Timestamp read_time = 6; -} - -// The request for [Firestore.ListCollectionIds][google.firestore.v1beta1.Firestore.ListCollectionIds]. -message ListCollectionIdsRequest { - // The parent document. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - // For example: - // `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - string parent = 1; - - // The maximum number of results to return. - int32 page_size = 2; - - // A page token. Must be a value from - // [ListCollectionIdsResponse][google.firestore.v1beta1.ListCollectionIdsResponse]. - string page_token = 3; -} - -// The response from [Firestore.ListCollectionIds][google.firestore.v1beta1.Firestore.ListCollectionIds]. -message ListCollectionIdsResponse { - // The collection ids. - repeated string collection_ids = 1; - - // A page token that may be used to continue the list. - string next_page_token = 2; -} diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto b/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto deleted file mode 100644 index 02d0aaaa..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/query.proto +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.firestore.v1beta1; - -import "google/api/annotations.proto"; -import "google/firestore/v1beta1/document.proto"; -import "google/protobuf/wrappers.proto"; - -option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/firestore/v1beta1;firestore"; -option java_multiple_files = true; -option java_outer_classname = "QueryProto"; -option java_package = "com.google.firestore.v1beta1"; -option objc_class_prefix = "GCFS"; -option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; - - -// A Firestore query. -message StructuredQuery { - // A selection of a collection, such as `messages as m1`. - message CollectionSelector { - // The collection ID. - // When set, selects only collections with this ID. - string collection_id = 2; - - // When false, selects only collections that are immediate children of - // the `parent` specified in the containing `RunQueryRequest`. - // When true, selects all descendant collections. - bool all_descendants = 3; - } - - // A filter. - message Filter { - // The type of filter. - oneof filter_type { - // A composite filter. - CompositeFilter composite_filter = 1; - - // A filter on a document field. - FieldFilter field_filter = 2; - - // A filter that takes exactly one argument. - UnaryFilter unary_filter = 3; - } - } - - // A filter that merges multiple other filters using the given operator. - message CompositeFilter { - // A composite filter operator. - enum Operator { - // Unspecified. This value must not be used. - OPERATOR_UNSPECIFIED = 0; - - // The results are required to satisfy each of the combined filters. - AND = 1; - } - - // The operator for combining multiple filters. - Operator op = 1; - - // The list of filters to combine. - // Must contain at least one filter. - repeated Filter filters = 2; - } - - // A filter on a specific field. - message FieldFilter { - // A field filter operator. - enum Operator { - // Unspecified. This value must not be used. - OPERATOR_UNSPECIFIED = 0; - - // Less than. Requires that the field come first in `order_by`. - LESS_THAN = 1; - - // Less than or equal. Requires that the field come first in `order_by`. - LESS_THAN_OR_EQUAL = 2; - - // Greater than. Requires that the field come first in `order_by`. - GREATER_THAN = 3; - - // Greater than or equal. Requires that the field come first in - // `order_by`. - GREATER_THAN_OR_EQUAL = 4; - - // Equal. - EQUAL = 5; - - // Contains. Requires that the field is an array. - ARRAY_CONTAINS = 7; - } - - // The field to filter by. - FieldReference field = 1; - - // The operator to filter by. - Operator op = 2; - - // The value to compare to. - Value value = 3; - } - - // A filter with a single operand. - message UnaryFilter { - // A unary operator. - enum Operator { - // Unspecified. This value must not be used. - OPERATOR_UNSPECIFIED = 0; - - // Test if a field is equal to NaN. - IS_NAN = 2; - - // Test if an exprestion evaluates to Null. - IS_NULL = 3; - } - - // The unary operator to apply. - Operator op = 1; - - // The argument to the filter. - oneof operand_type { - // The field to which to apply the operator. - FieldReference field = 2; - } - } - - // An order on a field. - message Order { - // The field to order by. - FieldReference field = 1; - - // The direction to order by. Defaults to `ASCENDING`. - Direction direction = 2; - } - - // A reference to a field, such as `max(messages.time) as max_time`. - message FieldReference { - string field_path = 2; - } - - // The projection of document's fields to return. - message Projection { - // The fields to return. - // - // If empty, all fields are returned. To only return the name - // of the document, use `['__name__']`. - repeated FieldReference fields = 2; - } - - // A sort direction. - enum Direction { - // Unspecified. - DIRECTION_UNSPECIFIED = 0; - - // Ascending. - ASCENDING = 1; - - // Descending. - DESCENDING = 2; - } - - // The projection to return. - Projection select = 1; - - // The collections to query. - repeated CollectionSelector from = 2; - - // The filter to apply. - Filter where = 3; - - // The order to apply to the query results. - // - // Firestore guarantees a stable ordering through the following rules: - // - // * Any field required to appear in `order_by`, that is not already - // specified in `order_by`, is appended to the order in field name order - // by default. - // * If an order on `__name__` is not specified, it is appended by default. - // - // Fields are appended with the same sort direction as the last order - // specified, or 'ASCENDING' if no order was specified. For example: - // - // * `SELECT * FROM Foo ORDER BY A` becomes - // `SELECT * FROM Foo ORDER BY A, __name__` - // * `SELECT * FROM Foo ORDER BY A DESC` becomes - // `SELECT * FROM Foo ORDER BY A DESC, __name__ DESC` - // * `SELECT * FROM Foo WHERE A > 1` becomes - // `SELECT * FROM Foo WHERE A > 1 ORDER BY A, __name__` - repeated Order order_by = 4; - - // A starting point for the query results. - Cursor start_at = 7; - - // A end point for the query results. - Cursor end_at = 8; - - // The number of results to skip. - // - // Applies before limit, but after all other constraints. Must be >= 0 if - // specified. - int32 offset = 6; - - // The maximum number of results to return. - // - // Applies after all other constraints. - // Must be >= 0 if specified. - google.protobuf.Int32Value limit = 5; -} - -// A position in a query result set. -message Cursor { - // The values that represent a position, in the order they appear in - // the order by clause of a query. - // - // Can contain fewer values than specified in the order by clause. - repeated Value values = 1; - - // If the position is just before or just after the given values, relative - // to the sort order defined by the query. - bool before = 2; -} diff --git a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto b/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto deleted file mode 100644 index 9901e310..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/protos/google/firestore/v1beta1/write.proto +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.firestore.v1beta1; - -import "google/api/annotations.proto"; -import "google/firestore/v1beta1/common.proto"; -import "google/firestore/v1beta1/document.proto"; -import "google/protobuf/timestamp.proto"; - -option csharp_namespace = "Google.Cloud.Firestore.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/firestore/v1beta1;firestore"; -option java_multiple_files = true; -option java_outer_classname = "WriteProto"; -option java_package = "com.google.firestore.v1beta1"; -option objc_class_prefix = "GCFS"; -option php_namespace = "Google\\Cloud\\Firestore\\V1beta1"; - - -// A write on a document. -message Write { - // The operation to execute. - oneof operation { - // A document to write. - Document update = 1; - - // A document name to delete. In the format: - // `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - string delete = 2; - - // Applies a tranformation to a document. - // At most one `transform` per document is allowed in a given request. - // An `update` cannot follow a `transform` on the same document in a given - // request. - DocumentTransform transform = 6; - } - - // The fields to update in this write. - // - // This field can be set only when the operation is `update`. - // If the mask is not set for an `update` and the document exists, any - // existing data will be overwritten. - // If the mask is set and the document on the server has fields not covered by - // the mask, they are left unchanged. - // Fields referenced in the mask, but not present in the input document, are - // deleted from the document on the server. - // The field paths in this mask must not contain a reserved field name. - DocumentMask update_mask = 3; - - // An optional precondition on the document. - // - // The write will fail if this is set and not met by the target document. - Precondition current_document = 4; -} - -// A transformation of a document. -message DocumentTransform { - // A transformation of a field of the document. - message FieldTransform { - // A value that is calculated by the server. - enum ServerValue { - // Unspecified. This value must not be used. - SERVER_VALUE_UNSPECIFIED = 0; - - // The time at which the server processed the request, with millisecond - // precision. - REQUEST_TIME = 1; - } - - // The path of the field. See [Document.fields][google.firestore.v1beta1.Document.fields] for the field path syntax - // reference. - string field_path = 1; - - // The transformation to apply on the field. - oneof transform_type { - // Sets the field to the given server value. - ServerValue set_to_server_value = 2; - - // Append the given elements in order if they are not already present in - // the current field value. - // If the field is not an array, or if the field does not yet exist, it is - // first set to the empty array. - // - // Equivalent numbers of different types (e.g. 3L and 3.0) are - // considered equal when checking if a value is missing. - // NaN is equal to NaN, and Null is equal to Null. - // If the input contains multiple equivalent values, only the first will - // be considered. - // - // The corresponding transform_result will be the null value. - ArrayValue append_missing_elements = 6; - - // Remove all of the given elements from the array in the field. - // If the field is not an array, or if the field does not yet exist, it is - // set to the empty array. - // - // Equivalent numbers of the different types (e.g. 3L and 3.0) are - // considered equal when deciding whether an element should be removed. - // NaN is equal to NaN, and Null is equal to Null. - // This will remove all equivalent values if there are duplicates. - // - // The corresponding transform_result will be the null value. - ArrayValue remove_all_from_array = 7; - } - } - - // The name of the document to transform. - string document = 1; - - // The list of transformations to apply to the fields of the document, in - // order. - // This must not be empty. - repeated FieldTransform field_transforms = 2; -} - -// The result of applying a write. -message WriteResult { - // The last update time of the document after applying the write. Not set - // after a `delete`. - // - // If the write did not actually change the document, this will be the - // previous update_time. - google.protobuf.Timestamp update_time = 1; - - // The results of applying each [DocumentTransform.FieldTransform][google.firestore.v1beta1.DocumentTransform.FieldTransform], in the - // same order. - repeated Value transform_results = 2; -} - -// A [Document][google.firestore.v1beta1.Document] has changed. -// -// May be the result of multiple [writes][google.firestore.v1beta1.Write], including deletes, that -// ultimately resulted in a new value for the [Document][google.firestore.v1beta1.Document]. -// -// Multiple [DocumentChange][google.firestore.v1beta1.DocumentChange] messages may be returned for the same logical -// change, if multiple targets are affected. -message DocumentChange { - // The new state of the [Document][google.firestore.v1beta1.Document]. - // - // If `mask` is set, contains only fields that were updated or added. - Document document = 1; - - // A set of target IDs of targets that match this document. - repeated int32 target_ids = 5; - - // A set of target IDs for targets that no longer match this document. - repeated int32 removed_target_ids = 6; -} - -// A [Document][google.firestore.v1beta1.Document] has been deleted. -// -// May be the result of multiple [writes][google.firestore.v1beta1.Write], including updates, the -// last of which deleted the [Document][google.firestore.v1beta1.Document]. -// -// Multiple [DocumentDelete][google.firestore.v1beta1.DocumentDelete] messages may be returned for the same logical -// delete, if multiple targets are affected. -message DocumentDelete { - // The resource name of the [Document][google.firestore.v1beta1.Document] that was deleted. - string document = 1; - - // A set of target IDs for targets that previously matched this entity. - repeated int32 removed_target_ids = 6; - - // The read timestamp at which the delete was observed. - // - // Greater or equal to the `commit_time` of the delete. - google.protobuf.Timestamp read_time = 4; -} - -// A [Document][google.firestore.v1beta1.Document] has been removed from the view of the targets. -// -// Sent if the document is no longer relevant to a target and is out of view. -// Can be sent instead of a DocumentDelete or a DocumentChange if the server -// can not send the new value of the document. -// -// Multiple [DocumentRemove][google.firestore.v1beta1.DocumentRemove] messages may be returned for the same logical -// write or delete, if multiple targets are affected. -message DocumentRemove { - // The resource name of the [Document][google.firestore.v1beta1.Document] that has gone out of view. - string document = 1; - - // A set of target IDs for targets that previously matched this document. - repeated int32 removed_target_ids = 2; - - // The read timestamp at which the remove was observed. - // - // Greater or equal to the `commit_time` of the change/delete/remove. - google.protobuf.Timestamp read_time = 4; -} - -// A digest of all the documents that match a given target. -message ExistenceFilter { - // The target ID to which this filter applies. - int32 target_id = 1; - - // The total count of documents that match [target_id][google.firestore.v1beta1.ExistenceFilter.target_id]. - // - // If different from the count of documents in the client that match, the - // client must manually determine which documents no longer match the target. - int32 count = 2; -} diff --git a/functions/node_modules/@google-cloud/firestore/build/src/backoff.js b/functions/node_modules/@google-cloud/firestore/build/src/backoff.js deleted file mode 100644 index 6045861c..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/backoff.js +++ /dev/null @@ -1,197 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -const logger_1 = require("./logger"); -/* - * @module firestore/backoff - * @private - * - * Contains backoff logic to facilitate RPC error handling. This class derives - * its implementation from the Firestore Mobile Web Client. - * - * @see https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/remote/backoff.ts - */ -/*! - * The default initial backoff time in milliseconds after an error. - * Set to 1s according to https://cloud.google.com/apis/design/errors. - */ -const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; -/*! - * The default maximum backoff time in milliseconds. - */ -const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; -/*! - * The default factor to increase the backup by after each failed attempt. - */ -const DEFAULT_BACKOFF_FACTOR = 1.5; -/*! - * The default jitter to distribute the backoff attempts by (0 means no - * randomization, 1.0 means +/-50% randomization). - */ -const DEFAULT_JITTER_FACTOR = 1.0; -/*! - * The timeout handler used by `ExponentialBackoff`. - */ -let delayExecution = setTimeout; -/** - * Allows overriding of the timeout handler used by the exponential backoff - * implementation. If not invoked, we default to `setTimeout()`. - * - * Used only in testing. - * - * @private - * @param {function} handler A handler than matches the API of `setTimeout()`. - */ -function setTimeoutHandler(handler) { - delayExecution = handler; -} -exports.setTimeoutHandler = setTimeoutHandler; -/** - * A helper for running delayed tasks following an exponential backoff curve - * between attempts. - * - * Each delay is made up of a "base" delay which follows the exponential - * backoff curve, and a "jitter" (+/- 50% by default) that is calculated and - * added to the base delay. This prevents clients from accidentally - * synchronizing their delays causing spikes of load to the backend. - * - * @private - */ -class ExponentialBackoff { - /** - * @param {number=} options.initialDelayMs Optional override for the initial - * retry delay. - * @param {number=} options.backoffFactor Optional override for the - * exponential backoff factor. - * @param {number=} options.maxDelayMs Optional override for the maximum - * retry delay. - * @param {number=} options.jitterFactor Optional override to control the - * jitter factor by which to randomize attempts (0 means no randomization, - * 1.0 means +/-50% randomization). It is suggested not to exceed this range. - */ - constructor(options) { - options = options || {}; - /** - * The initial delay (used as the base delay on the first retry attempt). - * Note that jitter will still be applied, so the actual delay could be as - * little as 0.5*initialDelayMs (based on a jitter factor of 1.0). - * - * @type {number} - * @private - */ - this._initialDelayMs = options.initialDelayMs !== undefined ? - options.initialDelayMs : - DEFAULT_BACKOFF_INITIAL_DELAY_MS; - /** - * The multiplier to use to determine the extended base delay after each - * attempt. - * @type {number} - * @private - */ - this._backoffFactor = options.backoffFactor !== undefined ? - options.backoffFactor : - DEFAULT_BACKOFF_FACTOR; - /** - * The maximum base delay after which no further backoff is performed. - * Note that jitter will still be applied, so the actual delay could be as - * much as 1.5*maxDelayMs (based on a jitter factor of 1.0). - * - * @type {number} - * @private - */ - this._maxDelayMs = options.maxDelayMs !== undefined ? - options.maxDelayMs : - DEFAULT_BACKOFF_MAX_DELAY_MS; - /** - * The jitter factor that controls the random distribution of the backoff - * points. - * - * @type {number} - * @private - */ - this._jitterFactor = options.jitterFactor !== undefined ? - options.jitterFactor : - DEFAULT_JITTER_FACTOR; - /** - * The backoff delay of the current attempt. - * @type {number} - * @private - */ - this._currentBaseMs = 0; - } - /** - * Resets the backoff delay. - * - * The very next backoffAndWait() will have no delay. If it is called again - * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and - * subsequent ones will increase according to the backoffFactor. - * - * @private - */ - reset() { - this._currentBaseMs = 0; - } - /** - * Resets the backoff delay to the maximum delay (e.g. for use after a - * RESOURCE_EXHAUSTED error). - * - * @private - */ - resetToMax() { - this._currentBaseMs = this._maxDelayMs; - } - /** - * Returns a promise that resolves after currentDelayMs, and increases the - * delay for any subsequent attempts. - * - * @private - * @return {Promise.} A Promise that resolves when the current delay - * elapsed. - */ - backoffAndWait() { - // First schedule using the current base (which may be 0 and should be - // honored as such). - const delayWithJitterMs = this._currentBaseMs + this._jitterDelayMs(); - if (this._currentBaseMs > 0) { - logger_1.logger('ExponentialBackoff.backoffAndWait', `Backing off for ${delayWithJitterMs} ms ` + - `(base delay: ${this._currentBaseMs} ms)`); - } - // Apply backoff factor to determine next delay and ensure it is within - // bounds. - this._currentBaseMs *= this._backoffFactor; - if (this._currentBaseMs < this._initialDelayMs) { - this._currentBaseMs = this._initialDelayMs; - } - if (this._currentBaseMs > this._maxDelayMs) { - this._currentBaseMs = this._maxDelayMs; - } - return new Promise(resolve => { - delayExecution(resolve, delayWithJitterMs); - }); - } - /** - * Returns a randomized "jitter" delay based on the current base and jitter - * factor. - * - * @private - * @returns {number} The jitter to apply based on the current delay. - */ - _jitterDelayMs() { - return (Math.random() - 0.5) * this._jitterFactor * this._currentBaseMs; - } -} -exports.ExponentialBackoff = ExponentialBackoff; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/convert.js b/functions/node_modules/@google-cloud/firestore/build/src/convert.js deleted file mode 100644 index 8cf32c74..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/convert.js +++ /dev/null @@ -1,213 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __importDefault(require("is")); -const validate_1 = require("./validate"); -const validate = validate_1.createValidator(); -/*! - * @module firestore/convert - * @private - * - * This module contains utility functions to convert - * `firestore.v1beta1.Documents` from Proto3 JSON to their equivalent - * representation in Protobuf JS. Protobuf JS is the only encoding supported by - * this client, and dependencies that use Proto3 JSON (such as the Google Cloud - * Functions SDK) are supported through this conversion and its usage in - * {@see Firestore#snapshot_}. - */ -/** - * Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS. - * - * @private - * @param {*=} timestampValue - The value to convert. - * @param {string=} argumentName - The argument name to use in the error message - * if the conversion fails. If omitted, 'timestampValue' is used. - * @return {{nanos,seconds}|undefined} The value as expected by Protobuf JS or - * undefined if no input was provided. - */ -function convertTimestamp(timestampValue, argumentName) { - let timestampProto = undefined; - if (is_1.default.string(timestampValue)) { - let date = new Date(timestampValue); - let seconds = Math.floor(date.getTime() / 1000); - let nanos = 0; - if (timestampValue.length > 20) { - const nanoString = timestampValue.substring(20, timestampValue.length - 1); - const trailingZeroes = 9 - nanoString.length; - nanos = parseInt(nanoString, 10) * Math.pow(10, trailingZeroes); - } - if (isNaN(seconds) || isNaN(nanos)) { - argumentName = argumentName || 'timestampValue'; - throw new Error(`Specify a valid ISO 8601 timestamp for "${argumentName}".`); - } - timestampProto = { - seconds: seconds || undefined, - nanos: nanos || undefined, - }; - } - else if (is_1.default.defined(timestampValue)) { - validate.isObject('timestampValue', timestampValue); - timestampProto = { - seconds: timestampValue.seconds || undefined, - nanos: timestampValue.nanos || undefined, - }; - } - return timestampProto; -} -/** - * Converts a Proto3 JSON 'bytesValue' field into Protobuf JS. - * - * @private - * @param {*} bytesValue - The value to convert. - * @return {Buffer} The value as expected by Protobuf JS. - */ -function convertBytes(bytesValue) { - if (typeof bytesValue === 'string') { - return Buffer.from(bytesValue, 'base64'); - } - else { - return bytesValue; - } -} -/** - * Detects 'valueType' from a Proto3 JSON `firestore.v1beta1.Value` proto. - * - * @private - * @param {object} proto - The `firestore.v1beta1.Value` proto. - * @return {string} - The string value for 'valueType'. - */ -function detectValueType(proto) { - if (proto.valueType) { - return proto.valueType; - } - let detectedValues = []; - if (is_1.default.defined(proto.stringValue)) { - detectedValues.push('stringValue'); - } - if (is_1.default.defined(proto.booleanValue)) { - detectedValues.push('booleanValue'); - } - if (is_1.default.defined(proto.integerValue)) { - detectedValues.push('integerValue'); - } - if (is_1.default.defined(proto.doubleValue)) { - detectedValues.push('doubleValue'); - } - if (is_1.default.defined(proto.timestampValue)) { - detectedValues.push('timestampValue'); - } - if (is_1.default.defined(proto.referenceValue)) { - detectedValues.push('referenceValue'); - } - if (is_1.default.defined(proto.arrayValue)) { - detectedValues.push('arrayValue'); - } - if (is_1.default.defined(proto.nullValue)) { - detectedValues.push('nullValue'); - } - if (is_1.default.defined(proto.mapValue)) { - detectedValues.push('mapValue'); - } - if (is_1.default.defined(proto.geoPointValue)) { - detectedValues.push('geoPointValue'); - } - if (is_1.default.defined(proto.bytesValue)) { - detectedValues.push('bytesValue'); - } - if (detectedValues.length !== 1) { - throw new Error(`Unable to infer type value fom '${JSON.stringify(proto)}'.`); - } - return detectedValues[0]; -} -/** - * Converts a `firestore.v1beta1.Value` in Proto3 JSON encoding into the - * Protobuf JS format expected by this client. - * - * @private - * @param {object} fieldValue - The `firestore.v1beta1.Value` in Proto3 JSON - * format. - * @return {object} The `firestore.v1beta1.Value` in Protobuf JS format. - */ -function convertValue(fieldValue) { - let valueType = detectValueType(fieldValue); - switch (valueType) { - case 'timestampValue': - return { - timestampValue: convertTimestamp(fieldValue.timestampValue), - }; - case 'bytesValue': - return { - bytesValue: convertBytes(fieldValue.bytesValue), - }; - case 'arrayValue': { - let arrayValue = []; - if (is_1.default.array(fieldValue.arrayValue.values)) { - for (let value of fieldValue.arrayValue.values) { - arrayValue.push(convertValue(value)); - } - } - return { - arrayValue: { - values: arrayValue, - }, - }; - } - case 'mapValue': { - let mapValue = {}; - for (let prop in fieldValue.mapValue.fields) { - if (fieldValue.mapValue.fields.hasOwnProperty(prop)) { - mapValue[prop] = convertValue(fieldValue.mapValue.fields[prop]); - } - } - return { - mapValue: { - fields: mapValue, - }, - }; - } - default: - return fieldValue; - } -} -/** - * Converts a `firestore.v1beta1.Document` in Proto3 JSON encoding into the - * Protobuf JS format expected by this client. This conversion creates a copy of - * the underlying document. - * - * @private - * @param {object} document - The `firestore.v1beta1.Document` in Proto3 JSON - * format. - * @return {object} The `firestore.v1beta1.Document` in Protobuf JS format. - */ -function convertDocument(document) { - let result = {}; - for (let prop in document) { - if (document.hasOwnProperty(prop)) { - result[prop] = convertValue(document[prop]); - } - } - return result; -} -module.exports = { - documentFromJson: convertDocument, - timestampFromJson: convertTimestamp, - valueFromJson: convertValue, - detectValueType: detectValueType, -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/document-change.js b/functions/node_modules/@google-cloud/firestore/build/src/document-change.js deleted file mode 100644 index e10ebbaf..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/document-change.js +++ /dev/null @@ -1,173 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is = __importStar(require("is")); -/** - * A DocumentChange represents a change to the documents matching a query. - * It contains the document affected and the type of change that occurred. - * - * @class - */ -class DocumentChange { - /** - * @private - * @hideconstructor - * - * @param {string} type - 'added' | 'removed' | 'modified'. - * @param {QueryDocumentSnapshot} document - The document. - * @param {number} oldIndex - The index in the documents array prior to this - * change. - * @param {number} newIndex - The index in the documents array after this - * change. - */ - constructor(type, document, oldIndex, newIndex) { - this._type = type; - this._document = document; - this._oldIndex = oldIndex; - this._newIndex = newIndex; - } - /** - * The type of change ('added', 'modified', or 'removed'). - * - * @type {string} - * @name DocumentChange#type - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * let docsArray = []; - * - * let unsubscribe = query.onSnapshot(querySnapshot => { - * for (let change of querySnapshot.docChanges) { - * console.log(`Type of change is ${change.type}`); - * } - * }); - * - * // Remove this listener. - * unsubscribe(); - */ - get type() { - return this._type; - } - /** - * The document affected by this change. - * - * @type {QueryDocumentSnapshot} - * @name DocumentChange#doc - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * let unsubscribe = query.onSnapshot(querySnapshot => { - * for (let change of querySnapshot.docChanges) { - * console.log(change.doc.data()); - * } - * }); - * - * // Remove this listener. - * unsubscribe(); - */ - get doc() { - return this._document; - } - /** - * The index of the changed document in the result set immediately prior to - * this DocumentChange (i.e. supposing that all prior DocumentChange objects - * have been applied). Is -1 for 'added' events. - * - * @type {number} - * @name DocumentChange#oldIndex - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * let docsArray = []; - * - * let unsubscribe = query.onSnapshot(querySnapshot => { - * for (let change of querySnapshot.docChanges) { - * if (change.oldIndex !== -1) { - * docsArray.splice(change.oldIndex, 1); - * } - * if (change.newIndex !== -1) { - * docsArray.splice(change.newIndex, 0, change.doc); - * } - * } - * }); - * - * // Remove this listener. - * unsubscribe(); - */ - get oldIndex() { - return this._oldIndex; - } - /** - * The index of the changed document in the result set immediately after - * this DocumentChange (i.e. supposing that all prior DocumentChange - * objects and the current DocumentChange object have been applied). - * Is -1 for 'removed' events. - * - * @type {number} - * @name DocumentChange#newIndex - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * let docsArray = []; - * - * let unsubscribe = query.onSnapshot(querySnapshot => { - * for (let change of querySnapshot.docChanges) { - * if (change.oldIndex !== -1) { - * docsArray.splice(change.oldIndex, 1); - * } - * if (change.newIndex !== -1) { - * docsArray.splice(change.newIndex, 0, change.doc); - * } - * } - * }); - * - * // Remove this listener. - * unsubscribe(); - */ - get newIndex() { - return this._newIndex; - } - /** - * Returns true if the data in this `DocumentChange` is equal to the provided - * value. - * - * @param {*} other The value to compare against. - * @return true if this `DocumentChange` is equal to the provided value. - */ - isEqual(other) { - if (this === other) { - return true; - } - return (is.instanceof(other, DocumentChange) && this._type === other._type && - this._oldIndex === other._oldIndex && - this._newIndex === other._newIndex && - this._document.isEqual(other._document)); - } -} -exports.DocumentChange = DocumentChange; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/document.js b/functions/node_modules/@google-cloud/firestore/build/src/document.js deleted file mode 100644 index 7eecf1d5..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/document.js +++ /dev/null @@ -1,1025 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -const deep_equal_1 = __importDefault(require("deep-equal")); -const is_1 = __importDefault(require("is")); -const path_1 = require("./path"); -const field_value_1 = require("./field-value"); -const timestamp_1 = require("./timestamp"); -const serializer_1 = require("./serializer"); -/** - * A DocumentSnapshot is an immutable representation for a document in a - * Firestore database. The data can be extracted with - * [data()]{@link DocumentSnapshot#data} or - * [get(fieldPath)]{@link DocumentSnapshot#get} to get a - * specific field. - * - *

For a DocumentSnapshot that points to a non-existing document, any data - * access will return 'undefined'. You can use the - * [exists]{@link DocumentSnapshot#exists} property to explicitly verify a - * document's existence. - * - * @class - */ -class DocumentSnapshot { - /** - * @private - * @hideconstructor - * - * @param {firestore/DocumentReference} ref - The reference to the - * document. - * @param {object=} fieldsProto - The fields of the Firestore `Document` - * Protobuf backing this document (or undefined if the document does not - * exist). - * @param {Timestamp} readTime - The time when this snapshot was read. - * @param {Timestamp=} createTime - The time when the document was created - * (or undefined if the document does not exist). - * @param {Timestamp=} updateTime - The time when the document was last - * updated (or undefined if the document does not exist). - */ - constructor(ref, fieldsProto, readTime, createTime, updateTime) { - this._ref = ref; - this._fieldsProto = fieldsProto; - this._serializer = ref.firestore._serializer; - this._validator = ref.firestore._validator; - this._readTime = readTime; - this._createTime = createTime; - this._updateTime = updateTime; - } - /** - * Creates a DocumentSnapshot from an object. - * - * @private - * @param {firestore/DocumentReference} ref - The reference to the document. - * @param {Object} obj - The object to store in the DocumentSnapshot. - * @return {firestore.DocumentSnapshot} The created DocumentSnapshot. - */ - static fromObject(ref, obj) { - const serializer = ref.firestore._serializer; - return new DocumentSnapshot(ref, serializer.encodeFields(obj)); - } - /** - * Creates a DocumentSnapshot from an UpdateMap. - * - * This methods expands the top-level field paths in a JavaScript map and - * turns { foo.bar : foobar } into { foo { bar : foobar }} - * - * @private - * @param {firestore/DocumentReference} ref - The reference to the document. - * @param {Map.} data - The field/value map to expand. - * @return {firestore.DocumentSnapshot} The created DocumentSnapshot. - */ - static fromUpdateMap(ref, data) { - const serializer = ref.firestore._serializer; - /** - * Merges 'value' at the field path specified by the path array into - * 'target'. - */ - function merge(target, value, path, pos) { - let key = path[pos]; - let isLast = pos === path.length - 1; - if (!is_1.default.defined(target[key])) { - if (isLast) { - if (value instanceof field_value_1.FieldTransform) { - // If there is already data at this path, we need to retain it. - // Otherwise, we don't include it in the DocumentSnapshot. - return !is_1.default.empty(target) ? target : null; - } - // The merge is done. - const leafNode = serializer.encodeValue(value); - if (leafNode) { - target[key] = leafNode; - } - return target; - } - else { - // We need to expand the target object. - const childNode = { - mapValue: { - fields: {}, - }, - }; - const nestedValue = merge(childNode.mapValue.fields, value, path, pos + 1); - if (nestedValue) { - childNode.mapValue.fields = nestedValue; - target[key] = childNode; - return target; - } - else { - return !is_1.default.empty(target) ? target : null; - } - } - } - else { - assert_1.default(!isLast, 'Can\'t merge current value into a nested object'); - target[key].mapValue.fields = - merge(target[key].mapValue.fields, value, path, pos + 1); - return target; - } - } - let res = {}; - data.forEach((value, key) => { - let components = key.toArray(); - merge(res, value, components, 0); - }); - return new DocumentSnapshot(ref, res); - } - /** - * True if the document exists. - * - * @type {boolean} - * @name DocumentSnapshot#exists - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then((documentSnapshot) => { - * if (documentSnapshot.exists) { - * console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`); - * } - * }); - */ - get exists() { - return this._fieldsProto !== undefined; - } - /** - * A [DocumentReference]{@link DocumentReference} for the document - * stored in this snapshot. - * - * @type {DocumentReference} - * @name DocumentSnapshot#ref - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then((documentSnapshot) => { - * if (documentSnapshot.exists) { - * console.log(`Found document at '${documentSnapshot.ref.path}'`); - * } - * }); - */ - get ref() { - return this._ref; - } - /** - * The ID of the document for which this DocumentSnapshot contains data. - * - * @type {string} - * @name DocumentSnapshot#id - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then((documentSnapshot) => { - * if (documentSnapshot.exists) { - * console.log(`Document found with name '${documentSnapshot.id}'`); - * } - * }); - */ - get id() { - return this._ref.id; - } - /** - * The time the document was created. Undefined for documents that don't - * exist. - * - * @type {Timestamp|undefined} - * @name DocumentSnapshot#createTime - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * if (documentSnapshot.exists) { - * let createTime = documentSnapshot.createTime; - * console.log(`Document created at '${createTime.toDate()}'`); - * } - * }); - */ - get createTime() { - return this._createTime; - } - /** - * The time the document was last updated (at the time the snapshot was - * generated). Undefined for documents that don't exist. - * - * @type {Timestamp|undefined} - * @name DocumentSnapshot#updateTime - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * if (documentSnapshot.exists) { - * let updateTime = documentSnapshot.updateTime; - * console.log(`Document updated at '${updateTime.toDate()}'`); - * } - * }); - */ - get updateTime() { - return this._updateTime; - } - /** - * The time this snapshot was read. - * - * @type {Timestamp} - * @name DocumentSnapshot#readTime - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * let readTime = documentSnapshot.readTime; - * console.log(`Document read at '${readTime.toDate()}'`); - * }); - */ - get readTime() { - return this._readTime; - } - /** - * Retrieves all fields in the document as an object. Returns 'undefined' if - * the document doesn't exist. - * - * @returns {DocumentData|undefined} An object containing all fields in the - * document or 'undefined' if the document doesn't exist. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * let data = documentSnapshot.data(); - * console.log(`Retrieved data: ${JSON.stringify(data)}`); - * }); - */ - data() { - let fields = this.protoFields(); - if (is_1.default.undefined(fields)) { - return undefined; - } - let obj = {}; - for (let prop in fields) { - if (fields.hasOwnProperty(prop)) { - obj[prop] = this._serializer.decodeValue(fields[prop]); - } - } - return obj; - } - /** - * Returns the underlying Firestore 'Fields' Protobuf in Protobuf JS format. - * - * @private - * @returns {Object} The Protobuf encoded document. - */ - protoFields() { - return this._fieldsProto; - } - /** - * Retrieves the field specified by `field`. - * - * @param {string|FieldPath} field - The field path - * (e.g. 'foo' or 'foo.bar') to a specific field. - * @returns {*} The data at the specified field location or undefined if no - * such field exists. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({ a: { b: 'c' }}).then(() => { - * return documentRef.get(); - * }).then(documentSnapshot => { - * let field = documentSnapshot.get('a.b'); - * console.log(`Retrieved field value: ${field}`); - * }); - */ - get(field) { - this._validator.isFieldPath('field', field); - let protoField = this.protoField(field); - if (protoField === undefined) { - return undefined; - } - return this._serializer.decodeValue(protoField); - } - /** - * Retrieves the field specified by 'fieldPath' in its Protobuf JS - * representation. - * - * @private - * @param {string|FieldPath} field - The path (e.g. 'foo' or - * 'foo.bar') to a specific field. - * @returns {*} The Protobuf-encoded data at the specified field location or - * undefined if no such field exists. - */ - protoField(field) { - let fields = this.protoFields(); - if (is_1.default.undefined(fields)) { - return undefined; - } - let components = path_1.FieldPath.fromArgument(field).toArray(); - while (components.length > 1) { - fields = fields[components.shift()]; - if (!fields || !fields.mapValue) { - return undefined; - } - fields = fields.mapValue.fields; - } - return fields[components[0]]; - } - /** - * Checks whether this DocumentSnapshot contains any fields. - * - * @private - * @return {boolean} - */ - get isEmpty() { - return is_1.default.undefined(this._fieldsProto) || is_1.default.empty(this._fieldsProto); - } - /** - * Convert a document snapshot to the Firestore 'Document' Protobuf. - * - * @private - * @returns {Object} - The document in the format the API expects. - */ - toProto() { - return { - update: { - name: this._ref.formattedName, - fields: this._fieldsProto, - }, - }; - } - /** - * Returns true if the document's data and path in this `DocumentSnapshot` is - * equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `DocumentSnapshot` is equal to the provided - * value. - */ - isEqual(other) { - // Since the read time is different on every document read, we explicitly - // ignore all document metadata in this comparison. - return (this === other || - (is_1.default.instance(other, DocumentSnapshot) && - this._ref.isEqual(other._ref) && - deep_equal_1.default(this._fieldsProto, other._fieldsProto, { strict: true }))); - } -} -exports.DocumentSnapshot = DocumentSnapshot; -/** - * A QueryDocumentSnapshot contains data read from a document in your - * Firestore database as part of a query. The document is guaranteed to exist - * and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data} - * or [get()]{@link DocumentSnapshot#get} to get a specific field. - * - * A QueryDocumentSnapshot offers the same API surface as a - * {@link DocumentSnapshot}. Since query results contain only existing - * documents, the [exists]{@link DocumentSnapshot#exists} property will - * always be true and [data()]{@link QueryDocumentSnapshot#data} will never - * return 'undefined'. - * - * @class - * @extends DocumentSnapshot - */ -class QueryDocumentSnapshot extends DocumentSnapshot { - /** - * @private - * @hideconstructor - * - * @param {firestore/DocumentReference} ref - The reference to the document. - * @param {object} fieldsProto - The fields of the Firestore `Document` - * Protobuf backing this document. - * @param {Timestamp} readTime - The time when this snapshot was read. - * @param {Timestamp} createTime - The time when the document was created. - * @param {Timestamp} updateTime - The time when the document was last - * updated. - */ - constructor(ref, fieldsProto, readTime, createTime, updateTime) { - super(ref, fieldsProto, readTime, createTime, updateTime); - } - /** - * The time the document was created. - * - * @type {Timestamp} - * @name QueryDocumentSnapshot#createTime - * @readonly - * @override - * - * @example - * let query = firestore.collection('col'); - * - * query.get().forEach(snapshot => { - * console.log(`Document created at '${snapshot.createTime.toDate()}'`); - * }); - */ - get createTime() { - return super.createTime; - } - /** - * The time the document was last updated (at the time the snapshot was - * generated). - * - * @type {Timestamp} - * @name QueryDocumentSnapshot#updateTime - * @readonly - * @override - * - * @example - * let query = firestore.collection('col'); - * - * query.get().forEach(snapshot => { - * console.log(`Document updated at '${snapshot.updateTime.toDate()}'`); - * }); - */ - get updateTime() { - return super.updateTime; - } - /** - * Retrieves all fields in the document as an object. - * - * @override - * - * @returns {DocumentData} An object containing all fields in the document. - * - * @example - * let query = firestore.collection('col'); - * - * query.get().forEach(documentSnapshot => { - * let data = documentSnapshot.data(); - * console.log(`Retrieved data: ${JSON.stringify(data)}`); - * }); - */ - data() { - let data = super.data(); - assert_1.default(is_1.default.defined(data), 'The data in a QueryDocumentSnapshot should always exist.'); - return data; - } -} -exports.QueryDocumentSnapshot = QueryDocumentSnapshot; -/** - * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. - * Invoke `.build()' to assemble the final snapshot. - * - * @private - * @class - */ -class DocumentSnapshotBuilder { - /** - * @private - * @hideconstructor - * - * @param {DocumentSnapshot=} snapshot An optional snapshot to base this - * builder on. - */ - constructor(snapshot) { - snapshot = snapshot || {}; - /** - * The reference to the document. - * - * @type {DocumentReference} - */ - this.ref = snapshot._ref; - /** - * The fields of the Firestore `Document` Protobuf backing this document. - * - * @type {object} - */ - this.fieldsProto = snapshot._fieldsProto; - /** - * The time when this document was read. - * - * @type {Timestamp} - */ - this.readTime = snapshot._readTime; - /** - * The time when this document was created. - * - * @type {Timestamp} - */ - this.createTime = snapshot._createTime; - /** - * The time when this document was last updated. - * - * @type {Timestamp} - */ - this.updateTime = snapshot._updateTime; - } - /** - * Builds the DocumentSnapshot. - * - * @private - * @returns {QueryDocumentSnapshot|DocumentSnapshot} Returns either a - * QueryDocumentSnapshot (if `fieldsProto` was provided) or a - * DocumentSnapshot. - */ - build() { - assert_1.default(is_1.default.defined(this.fieldsProto) === is_1.default.defined(this.createTime), 'Create time should be set iff document exists.'); - assert_1.default(is_1.default.defined(this.fieldsProto) === is_1.default.defined(this.updateTime), 'Update time should be set iff document exists.'); - return this.fieldsProto ? - new QueryDocumentSnapshot(this.ref, this.fieldsProto, this.readTime, this.createTime, this.updateTime) : - new DocumentSnapshot(this.ref, undefined, this.readTime); - } -} -/** - * @private - * @name DocumentSnapshot.DocumentSnapshotBuilder - * @see DocumentSnapshotBuilder - */ -DocumentSnapshot.Builder = DocumentSnapshotBuilder; -/** - * A Firestore Document Mask contains the field paths affected by an update. - * - * @class - * @private - */ -class DocumentMask { - /** - * @private - * @hideconstructor - * - * @param {Array.} fieldPaths - The field paths in this mask. - */ - constructor(fieldPaths) { - this._sortedPaths = fieldPaths; - this._sortedPaths.sort((a, b) => a.compareTo(b)); - } - /** - * Creates a document mask with the field paths of a document. - * - * @private - * @param {Map.} data A map with - * fields to modify. Only the keys are used to extract the document mask. - * @returns {DocumentMask} - */ - static fromUpdateMap(data) { - let fieldPaths = []; - data.forEach((value, key) => { - if (!(value instanceof field_value_1.FieldTransform) || value.includeInDocumentMask) { - fieldPaths.push(path_1.FieldPath.fromArgument(key)); - } - }); - return new DocumentMask(fieldPaths); - } - /** - * Creates a document mask from an array of field paths. - * - * @private - * @param {Array.} fieldMask A list of field paths. - * @returns {DocumentMask} - */ - static fromFieldMask(fieldMask) { - let fieldPaths = []; - for (const fieldPath of fieldMask) { - fieldPaths.push(path_1.FieldPath.fromArgument(fieldPath)); - } - return new DocumentMask(fieldPaths); - } - /** - * Creates a document mask with the field names of a document. - * - * @private - * @param {DocumentData} data An object with fields to modify. Only the keys - * are used to extract the document mask. - * @returns {DocumentMask} - */ - static fromObject(data) { - let fieldPaths = []; - const extractFieldPaths = function (currentData, currentPath) { - let isEmpty = true; - for (let key in currentData) { - if (currentData.hasOwnProperty(key)) { - isEmpty = false; - // We don't split on dots since fromObject is called with - // DocumentData. - const childSegment = new path_1.FieldPath(key); - const childPath = currentPath ? currentPath.append(childSegment) : childSegment; - const value = currentData[key]; - if (value instanceof field_value_1.FieldTransform) { - if (value.includeInDocumentMask) { - fieldPaths.push(childPath); - } - } - else if (serializer_1.isPlainObject(value)) { - extractFieldPaths(value, childPath); - } - else { - fieldPaths.push(childPath); - } - } - } - // Add a field path for an explicitly updated empty map. - if (currentPath && isEmpty) { - fieldPaths.push(currentPath); - } - }; - extractFieldPaths(data); - return new DocumentMask(fieldPaths); - } - /** - * Returns true if this document mask contains no fields. - * - * @private - * @return {boolean} Whether this document mask is empty. - */ - get isEmpty() { - return this._sortedPaths.length === 0; - } - /** - * Removes the specified values from a sorted field path array. - * - * @private - * @param {Array.} input - A sorted array of FieldPaths. - * @param {Array.} values - An array of FieldPaths to remove. - */ - static removeFromSortedArray(input, values) { - for (let i = 0; i < input.length;) { - let removed = false; - for (const fieldPath of values) { - if (input[i].isEqual(fieldPath)) { - input.splice(i, 1); - removed = true; - break; - } - } - if (!removed) { - ++i; - } - } - } - /** - * Removes the field path specified in 'fieldPaths' from this document mask. - * - * @private - * @param {Array.} fieldPaths An array of FieldPaths. - */ - removeFields(fieldPaths) { - DocumentMask.removeFromSortedArray(this._sortedPaths, fieldPaths); - } - /** - * Returns whether this document mask contains 'fieldPath'. - * - * @private - * @param {FieldPath} fieldPath The field path to test. - * @return {boolean} Whether this document mask contains 'fieldPath'. - */ - contains(fieldPath) { - for (const sortedPath of this._sortedPaths) { - const cmp = sortedPath.compareTo(fieldPath); - if (cmp === 0) { - return true; - } - else if (cmp > 0) { - return false; - } - } - return false; - } - /** - * Removes all properties from 'data' that are not contained in this document - * mask. - * - * @private - * @param {Object} data - An object to filter. - * @return {Object} A shallow copy of the object filtered by this document - * mask. - */ - applyTo(data) { - /*! - * Applies this DocumentMask to 'data' and computes the list of field paths - * that were specified in the mask but are not present in 'data'. - */ - const applyDocumentMask = data => { - const remainingPaths = this._sortedPaths.slice(0); - const processObject = (currentData, currentPath) => { - let result = null; - Object.keys(currentData).forEach(key => { - const childPath = currentPath ? currentPath.append(key) : new path_1.FieldPath(key); - if (this.contains(childPath)) { - DocumentMask.removeFromSortedArray(remainingPaths, [childPath]); - result = result || {}; - result[key] = currentData[key]; - } - else if (is_1.default.object(currentData[key])) { - const childObject = processObject(currentData[key], childPath); - if (childObject) { - result = result || {}; - result[key] = childObject; - } - } - }); - return result; - }; - // processObject() returns 'null' if the DocumentMask is empty. - const filteredData = processObject(data) || {}; - return { - filteredData: filteredData, - remainingPaths: remainingPaths, - }; - }; - const result = applyDocumentMask(data); - if (result.remainingPaths.length !== 0) { - throw new Error(`Input data is missing for field '${result.remainingPaths[0].toString()}'.`); - } - return result.filteredData; - } - /** - * Converts a document mask to the Firestore 'DocumentMask' Proto. - * - * @private - * @returns {Object} A Firestore 'DocumentMask' Proto. - */ - toProto() { - if (this.isEmpty) { - return {}; - } - let encodedPaths = []; - for (const fieldPath of this._sortedPaths) { - encodedPaths.push(fieldPath.formattedName); - } - return { - fieldPaths: encodedPaths, - }; - } -} -exports.DocumentMask = DocumentMask; -/** - * A Firestore Document Transform. - * - * A DocumentTransform contains pending server-side transforms and their - * corresponding field paths. - * - * @private - * @class - */ -class DocumentTransform { - /** - * @private - * @hideconstructor - * - * @param {DocumentReference} ref The DocumentReference for this - * transform. - * @param {Map.} transforms A Map of FieldPaths to - * FieldTransforms. - */ - constructor(ref, transforms) { - this._ref = ref; - this._validator = ref.firestore._validator; - this._transforms = transforms; - } - /** - * Generates a DocumentTransform from a JavaScript object. - * - * @private - * @param {firestore/DocumentReference} ref The `DocumentReference` to - * use for the DocumentTransform. - * @param {Object} obj The object to extract the transformations from. - * @returns {firestore.DocumentTransform} The Document Transform. - */ - static fromObject(ref, obj) { - let updateMap = new Map(); - for (let prop in obj) { - if (obj.hasOwnProperty(prop)) { - updateMap.set(new path_1.FieldPath(prop), obj[prop]); - } - } - return DocumentTransform.fromUpdateMap(ref, updateMap); - } - /** - * Generates a DocumentTransform from an Update Map. - * - * @private - * @param {firestore/DocumentReference} ref The `DocumentReference` to - * use for the DocumentTransform. - * @param {Map} data The map to extract the transformations from. - * @returns {firestore.DocumentTransform}} The Document Transform. - */ - static fromUpdateMap(ref, data) { - let transforms = new Map(); - function encode_(val, path, allowTransforms) { - if (val instanceof field_value_1.FieldTransform && val.includeInDocumentTransform) { - if (allowTransforms) { - transforms.set(path, val); - } - else { - throw new Error(`${val.methodName}() is not supported inside of array values.`); - } - } - else if (is_1.default.array(val)) { - for (let i = 0; i < val.length; ++i) { - // We need to verify that no array value contains a document transform - encode_(val[i], path.append(String(i)), false); - } - } - else if (serializer_1.isPlainObject(val)) { - for (let prop in val) { - if (val.hasOwnProperty(prop)) { - encode_(val[prop], path.append(new path_1.FieldPath(prop)), allowTransforms); - } - } - } - } - data.forEach((value, key) => { - encode_(value, path_1.FieldPath.fromArgument(key), true); - }); - return new DocumentTransform(ref, transforms); - } - /** - * Whether this DocumentTransform contains any actionable transformations. - * - * @private - * @type {boolean} - * @readonly - */ - get isEmpty() { - return this._transforms.size === 0; - } - /** - * Returns the array of fields in this DocumentTransform. - * - * @private - * @type {Array.} - * @readonly - */ - get fields() { - return Array.from(this._transforms.keys()); - } - /** Validates the user provided field values in this document transform. */ - validate() { - this._transforms.forEach(transform => transform.validate(this._validator)); - } - /** - * Converts a document transform to the Firestore 'DocumentTransform' Proto. - * - * @private - * @param {Serializer} serializer - The Firestore serializer - * @returns {Object|null} A Firestore 'DocumentTransform' Proto or 'null' if - * this transform is empty. - */ - toProto(serializer) { - if (this.isEmpty) { - return null; - } - const protoTransforms = []; - this._transforms.forEach((transform, path) => { - protoTransforms.push(transform.toProto(serializer, path)); - }); - return { - transform: { - document: this._ref.formattedName, - fieldTransforms: protoTransforms, - }, - }; - } -} -exports.DocumentTransform = DocumentTransform; -/*! - * A Firestore Precondition encapsulates options for database writes. - * - * @private - * @class - */ -class Precondition { - /** - * @private - * @hideconstructor - * - * @param {boolean=} options.exists - Whether the referenced document should - * exist in Firestore, - * @param {Timestamp=} options.lastUpdateTime - The last update time of the - * referenced document in Firestore. - * @param options - */ - constructor(options) { - if (is_1.default.object(options)) { - this._exists = options.exists; - this._lastUpdateTime = options.lastUpdateTime; - } - } - /** - * Generates the Protobuf `Preconditon` object for this precondition. - * - * @private - * @returns {Object|null} The `Preconditon` Protobuf object or 'null' if there - * are no preconditions. - */ - toProto() { - if (this.isEmpty) { - return null; - } - let proto = {}; - if (is_1.default.defined(this._lastUpdateTime)) { - proto.updateTime = this._lastUpdateTime.toProto().timestampValue; - } - else { - proto.exists = this._exists; - } - return proto; - } - /** - * Whether this DocumentTransform contains any enforcement. - * - * @private - * @type {boolean} - * @readonly - */ - get isEmpty() { - return this._exists === undefined && !this._lastUpdateTime; - } -} -exports.Precondition = Precondition; -/*! - * Validates the use of 'options' as a Precondition and enforces that 'exists' - * and 'lastUpdateTime' use valid types. - * - * @param {boolean=} options.exists - Whether the referenced document - * should exist. - * @param {Timestamp=} options.lastUpdateTime - The last update time - * of the referenced document in Firestore. - * @param {boolean} allowExist Whether to allow the 'exists' preconditions. - * @returns {boolean} 'true' if the input is a valid Precondition. - */ -function validatePrecondition(precondition, allowExist) { - if (!is_1.default.object(precondition)) { - throw new Error('Input is not an object.'); - } - let conditions = 0; - if (is_1.default.defined(precondition.exists)) { - ++conditions; - if (!allowExist) { - throw new Error('"exists" is not an allowed condition.'); - } - if (!is_1.default.boolean(precondition.exists)) { - throw new Error('"exists" is not a boolean.'); - } - } - if (is_1.default.defined(precondition.lastUpdateTime)) { - ++conditions; - if (!is_1.default.instance(precondition.lastUpdateTime, timestamp_1.Timestamp)) { - throw new Error('"lastUpdateTime" is not a Firestore Timestamp.'); - } - } - if (conditions > 1) { - throw new Error('Input contains more than one condition.'); - } - return true; -} -exports.validatePrecondition = validatePrecondition; -/*! - * Validates the use of 'options' as SetOptions and enforces that 'merge' is a - * boolean. - * - * @param {boolean=} options.merge - Whether set() should merge the provided - * data into an existing document. - * @param {boolean=} options.mergeFields - Whether set() should only merge the - * specified set of fields. - * @returns {boolean} 'true' if the input is a valid SetOptions object. - */ -function validateSetOptions(options) { - if (!is_1.default.object(options)) { - throw new Error('Input is not an object.'); - } - if (is_1.default.defined(options.merge) && !is_1.default.boolean(options.merge)) { - throw new Error('"merge" is not a boolean.'); - } - if (is_1.default.defined(options.mergeFields)) { - if (!is_1.default.array(options.mergeFields)) { - throw new Error('"mergeFields" is not an array.'); - } - for (let i = 0; i < options.mergeFields.length; ++i) { - try { - path_1.FieldPath.validateFieldPath(options.mergeFields[i]); - } - catch (err) { - throw new Error(`Argument at index ${i} is not a valid FieldPath. ${err.message}`); - } - } - } - if (is_1.default.defined(options.merge) && is_1.default.defined(options.mergeFields)) { - throw new Error('You cannot specify both "merge" and "mergeFields".'); - } - return true; -} -exports.validateSetOptions = validateSetOptions; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/field-value.js b/functions/node_modules/@google-cloud/firestore/build/src/field-value.js deleted file mode 100644 index 18d459b2..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/field-value.js +++ /dev/null @@ -1,324 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const deep_equal_1 = __importDefault(require("deep-equal")); -const validate_1 = require("./validate"); -const firestore_proto_api_1 = require("../protos/firestore_proto_api"); -var api = firestore_proto_api_1.google.firestore.v1beta1; -const validate = validate_1.createValidator(); -/** - * Sentinel values that can be used when writing documents with set(), create() - * or update(). - * - * @class - */ -class FieldValue { - /** - * @private - * @hideconstructor - */ - constructor() { } - /** - * Returns a sentinel for use with update() or set() with {merge:true} to mark - * a field for deletion. - * - * @returns {FieldValue} The sentinel value to use in your objects. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * let data = { a: 'b', c: 'd' }; - * - * documentRef.set(data).then(() => { - * return documentRef.update({a: Firestore.FieldValue.delete()}); - * }).then(() => { - * // Document now only contains { c: 'd' } - * }); - */ - static delete() { - return DeleteTransform.DELETE_SENTINEL; - } - /** - * Returns a sentinel used with set(), create() or update() to include a - * server-generated timestamp in the written data. - * - * @return {FieldValue} The FieldValue sentinel for use in a call to set(), - * create() or update(). - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({ - * time: Firestore.FieldValue.serverTimestamp() - * }).then(() => { - * return documentRef.get(); - * }).then(doc => { - * console.log(`Server time set to ${doc.get('time')}`); - * }); - */ - static serverTimestamp() { - return ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL; - } - /** - * Returns a special value that can be used with set(), create() or update() - * that tells the server to union the given elements with any array value that - * already exists on the server. Each specified element that doesn't already - * exist in the array will be added to the end. If the field being modified is - * not already an array it will be overwritten with an array containing - * exactly the specified elements. - * - * @param {...*} elements The elements to union into the array. - * @return {FieldValue} The FieldValue sentinel for use in a call to set(), - * create() or update(). - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.update( - * 'array', Firestore.FieldValue.arrayUnion('foo') - * ).then(() => { - * return documentRef.get(); - * }).then(doc => { - * // doc.get('array') contains field 'foo' - * }); - */ - static arrayUnion(...elements) { - validate.minNumberOfArguments('FieldValue.arrayUnion', arguments, 1); - return new ArrayUnionTransform(elements); - } - /** - * Returns a special value that can be used with set(), create() or update() - * that tells the server to remove the given elements from any array value - * that already exists on the server. All instances of each element specified - * will be removed from the array. If the field being modified is not already - * an array it will be overwritten with an empty array. - * - * @param {...*} elements The elements to remove from the array. - * @return {FieldValue} The FieldValue sentinel for use in a call to set(), - * create() or update(). - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.update( - * 'array', Firestore.FieldValue.arrayRemove('foo') - * ).then(() => { - * return documentRef.get(); - * }).then(doc => { - * // doc.get('array') no longer contains field 'foo' - * }); - */ - static arrayRemove(...elements) { - validate.minNumberOfArguments('FieldValue.arrayRemove', arguments, 1); - return new ArrayRemoveTransform(elements); - } - /** - * Returns true if this `FieldValue` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `FieldValue` is equal to the provided value. - */ - isEqual(other) { - return this === other; - } -} -exports.FieldValue = FieldValue; -/** - * An internal interface shared by all field transforms. - * - * A 'FieldTransform` subclass should implement '.includeInDocumentMask', - * '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform' - * is 'true'). - * - * @private - * @abstract - */ -class FieldTransform extends FieldValue { -} -exports.FieldTransform = FieldTransform; -/** - * A transform that deletes a field from a Firestore document. - * - * @private - */ -class DeleteTransform extends FieldTransform { - constructor() { - super(); - } - /** - * Deletes are included in document masks. - */ - get includeInDocumentMask() { - return true; - } - /** - * Deletes are are omitted from document transforms. - */ - get includeInDocumentTransform() { - return false; - } - get methodName() { - return 'FieldValue.delete'; - } - validate() { - return true; - } - toProto(serializer, fieldPath) { - throw new Error('FieldValue.delete() should not be included in a FieldTransform'); - } -} -/** - * Sentinel value for a field delete. - */ -DeleteTransform.DELETE_SENTINEL = new DeleteTransform(); -exports.DeleteTransform = DeleteTransform; -/** - * A transform that sets a field to the Firestore server time. - * - * @private - */ -class ServerTimestampTransform extends FieldTransform { - constructor() { - super(); - } - /** - * Server timestamps are omitted from document masks. - * - * @private - */ - get includeInDocumentMask() { - return false; - } - /** - * Server timestamps are included in document transforms. - * - * @private - */ - get includeInDocumentTransform() { - return true; - } - get methodName() { - return 'FieldValue.serverTimestamp'; - } - validate() { - return true; - } - toProto(serializer, fieldPath) { - return { - fieldPath: fieldPath.formattedName, - setToServerValue: api.DocumentTransform.FieldTransform.ServerValue.REQUEST_TIME, - }; - } -} -/** - * Sentinel value for a server timestamp. - * - * @private - */ -ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL = new ServerTimestampTransform(); -/** - * Transforms an array value via a union operation. - * - * @private - */ -class ArrayUnionTransform extends FieldTransform { - constructor(elements) { - super(); - this.elements = elements; - } - /** - * Array transforms are omitted from document masks. - */ - get includeInDocumentMask() { - return false; - } - /** - * Array transforms are included in document transforms. - */ - get includeInDocumentTransform() { - return true; - } - get methodName() { - return 'FieldValue.arrayUnion'; - } - validate(validator) { - let valid = true; - for (let i = 0; valid && i < this.elements.length; ++i) { - valid = validator.isArrayElement(i, this.elements[i], { allowDeletes: 'none', allowTransforms: false }); - } - return valid; - } - toProto(serializer, fieldPath) { - const encodedElements = serializer.encodeValue(this.elements).arrayValue; - return { - fieldPath: fieldPath.formattedName, - appendMissingElements: encodedElements - }; - } - isEqual(other) { - return (this === other || - (other instanceof ArrayUnionTransform && - deep_equal_1.default(this.elements, other.elements, { strict: true }))); - } -} -/** - * Transforms an array value via a remove operation. - * - * @private - */ -class ArrayRemoveTransform extends FieldTransform { - constructor(elements) { - super(); - this.elements = elements; - } - /** - * Array transforms are omitted from document masks. - */ - get includeInDocumentMask() { - return false; - } - /** - * Array transforms are included in document transforms. - */ - get includeInDocumentTransform() { - return true; - } - get methodName() { - return 'FieldValue.arrayRemove'; - } - validate(validator) { - let valid = true; - for (let i = 0; valid && i < this.elements.length; ++i) { - valid = validator.isArrayElement(i, this.elements[i], { allowDeletes: 'none', allowTransforms: false }); - } - return valid; - } - toProto(serializer, fieldPath) { - const encodedElements = serializer.encodeValue(this.elements).arrayValue; - return { - fieldPath: fieldPath.formattedName, - removeAllFromArray: encodedElements - }; - } - isEqual(other) { - return (this === other || - (other instanceof ArrayRemoveTransform && - deep_equal_1.default(this.elements, other.elements, { strict: true }))); - } -} diff --git a/functions/node_modules/@google-cloud/firestore/build/src/geo-point.js b/functions/node_modules/@google-cloud/firestore/build/src/geo-point.js deleted file mode 100644 index d4c06c6b..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/geo-point.js +++ /dev/null @@ -1,108 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -const validate_1 = require("./validate"); -const validate = validate_1.createValidator(); -/** - * An immutable object representing a geographic location in Firestore. The - * location is represented as a latitude/longitude pair. - * - * @class - */ -class GeoPoint { - /** - * Creates a [GeoPoint]{@link GeoPoint}. - * - * @param {number} latitude The latitude as a number between -90 and 90. - * @param {number} longitude The longitude as a number between -180 and 180. - * - * @example - * let data = { - * google: new Firestore.GeoPoint(37.422, 122.084) - * }; - * - * firestore.doc('col/doc').set(data).then(() => { - * console.log(`Location is ${data.google.latitude}, ` + - * `${data.google.longitude}`); - * }); - */ - constructor(latitude, longitude) { - validate.isNumber('latitude', latitude, -90, 90); - validate.isNumber('longitude', longitude, -180, 180); - this._latitude = latitude; - this._longitude = longitude; - } - /** - * The latitude as a number between -90 and 90. - * - * @type {number} - * @name GeoPoint#latitude - * @readonly - */ - get latitude() { - return this._latitude; - } - /** - * The longitude as a number between -180 and 180. - * - * @type {number} - * @name GeoPoint#longitude - * @readonly - */ - get longitude() { - return this._longitude; - } - /** - * Returns a string representation for this GeoPoint. - * - * @return {string} The string representation. - */ - toString() { - return `GeoPoint { latitude: ${this.latitude}, longitude: ${this.longitude} }`; - } - /** - * Returns true if this `GeoPoint` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `GeoPoint` is equal to the provided value. - */ - isEqual(other) { - return (this === other || - (other instanceof GeoPoint && this.latitude === other.latitude && - this.longitude === other.longitude)); - } - /** - * Converts the GeoPoint to a google.type.LatLng proto. - * @private - */ - toProto() { - return { - geoPointValue: { - latitude: this.latitude, - longitude: this.longitude, - } - }; - } - /** - * Converts a google.type.LatLng proto to its GeoPoint representation. - * @private - */ - static fromProto(proto) { - return new GeoPoint(proto.latitude || 0, proto.longitude || 0); - } -} -exports.GeoPoint = GeoPoint; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/index.js b/functions/node_modules/@google-cloud/firestore/build/src/index.js deleted file mode 100644 index 0fc22e61..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/index.js +++ /dev/null @@ -1,1275 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -const bun_1 = __importDefault(require("bun")); -const extend_1 = __importDefault(require("extend")); -const is_1 = __importDefault(require("is")); -const through2_1 = __importDefault(require("through2")); -const projectify_1 = require("@google-cloud/projectify"); -const reference_1 = require("./reference"); -const document_1 = require("./document"); -const field_value_1 = require("./field-value"); -const validate_1 = require("./validate"); -const write_batch_1 = require("./write-batch"); -const transaction_1 = require("./transaction"); -const timestamp_1 = require("./timestamp"); -const path_1 = require("./path"); -const pool_1 = require("./pool"); -const document_change_1 = require("./document-change"); -const serializer_1 = require("./serializer"); -const geo_point_1 = require("./geo-point"); -const logger_1 = require("./logger"); -const util_1 = require("./util"); -const convert = __importStar(require("./convert")); -const libVersion = require('../../package.json').version; -logger_1.setLibVersion(libVersion); -/*! - * DO NOT REMOVE THE FOLLOWING NAMESPACE DEFINITIONS - */ -/** - * @namespace google.protobuf - */ -/** - * @namespace google.rpc - */ -/** - * @namespace google.firestore.v1beta1 - */ -/*! - * @see v1beta1 - */ -let v1beta1; // Lazy-loaded in `_runRequest()` -/*! - * HTTP header for the resource prefix to improve routing and project isolation - * by the backend. - * @type {string} - */ -const CLOUD_RESOURCE_HEADER = 'google-cloud-resource-prefix'; -/*! - * The maximum number of times to retry idempotent requests. - * @type {number} - */ -const MAX_REQUEST_RETRIES = 5; -/*! - * The maximum number of concurrent requests supported by a single GRPC channel, - * as enforced by Google's Frontend. If the SDK issues more than 100 concurrent - * operations, we need to use more than one GAPIC client since these clients - * multiplex all requests over a single channel. - * - * @type {number} - */ -const MAX_CONCURRENT_REQUESTS_PER_CLIENT = 100; -/*! - * GRPC Error code for 'UNAVAILABLE'. - * @type {number} - */ -const GRPC_UNAVAILABLE = 14; -/*! - * The maximum depth of a Firestore object. - * - * @type {number} - */ -const MAX_DEPTH = 20; -/** - * Document data (e.g. for use with - * [set()]{@link DocumentReference#set}) consisting of fields mapped - * to values. - * - * @typedef {Object.} DocumentData - */ -/** - * Update data (for use with [update]{@link DocumentReference#update}) - * that contains paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that - * contain dots reference nested fields within the document. - * - * @typedef {Object.} UpdateData - */ -/** - * An options object that configures conditional behavior of - * [update()]{@link DocumentReference#update} and - * [delete()]{@link DocumentReference#delete} calls in - * [DocumentReference]{@link DocumentReference}, - * [WriteBatch]{@link WriteBatch}, and - * [Transaction]{@link Transaction}. Using Preconditions, these calls - * can be restricted to only apply to documents that match the specified - * conditions. - * - * @property {string} lastUpdateTime - The update time to enforce (specified as - * an ISO 8601 string). - * @typedef {Object} Precondition - */ -/** - * An options object that configures the behavior of - * [set()]{@link DocumentReference#set} calls in - * [DocumentReference]{@link DocumentReference}, - * [WriteBatch]{@link WriteBatch}, and - * [Transaction]{@link Transaction}. These calls can be - * configured to perform granular merges instead of overwriting the target - * documents in their entirety by providing a SetOptions object with - * { merge : true }. - * - * @property {boolean} merge - Changes the behavior of a set() call to only - * replace the values specified in its data argument. Fields omitted from the - * set() call remain untouched. - * @typedef {Object} SetOptions - */ -/** - * The Firestore client represents a Firestore Database and is the entry point - * for all Firestore operations. - * - * @see [Firestore Documentation]{@link https://firebase.google.com/docs/firestore/} - * - * @class - * - * @example Install the client library with npm: npm install --save - * @google-cloud/firestore - * - * @example Import the client library - * var Firestore = require('@google-cloud/firestore'); - * - * @example Create a client that uses Application - * Default Credentials (ADC): var firestore = new Firestore(); - * - * @example Create a client with explicit - * credentials: var firestore = new Firestore({ projectId: - * 'your-project-id', keyFilename: '/path/to/keyfile.json' - * }); - * - * @example include:samples/quickstart.js - * region_tag:firestore_quickstart - * Full quickstart example: - */ -class Firestore { - /** - * @param {Object=} settings - [Configuration object](#/docs). - * @param {string=} settings.projectId The Firestore Project ID. Can be - * omitted in environments that support `Application Default Credentials` - * {@see https://cloud.google.com/docs/authentication} - * @param {string=} settings.keyFilename Local file containing the Service - * Account credentials. Can be omitted in environments that support - * `Application Default Credentials` - * {@see https://cloud.google.com/docs/authentication} - * @param {boolean=} settings.timestampsInSnapshots Enables the use of - * `Timestamp`s for timestamp fields in `DocumentSnapshots`.
- * Currently, Firestore returns timestamp fields as `Date` but `Date` only - * supports millisecond precision, which leads to truncation and causes - * unexpected behavior when using a timestamp from a snapshot as a part - * of a subsequent query. - *
Setting `timestampsInSnapshots` to true will cause Firestore to return - * `Timestamp` values instead of `Date` avoiding this kind of problem. To - * make this work you must also change any code that uses `Date` to use - * `Timestamp` instead. - *
NOTE: in the future `timestampsInSnapshots: true` will become the - * default and this option will be removed so you should change your code to - * use `Timestamp` now and opt-in to this new behavior as soon as you can. - */ - constructor(settings) { - settings = extend_1.default({}, settings, { - libName: 'gccl', - libVersion: libVersion, - }); - this._validator = new validate_1.Validator({ - ArrayElement: (name, value) => validateFieldValue(name, value, /* depth */ 0, /*inArray=*/ true), - DeletePrecondition: precondition => document_1.validatePrecondition(precondition, /* allowExists= */ true), - Document: validateDocumentData, - DocumentReference: reference_1.validateDocumentReference, - FieldPath: path_1.FieldPath.validateFieldPath, - FieldValue: validateFieldValue, - FieldOrder: reference_1.validateFieldOrder, - QueryComparison: reference_1.validateComparisonOperator, - QueryValue: validateFieldValue, - ResourcePath: path_1.ResourcePath.validateResourcePath, - SetOptions: document_1.validateSetOptions, - UpdateMap: write_batch_1.validateUpdateMap, - UpdatePrecondition: precondition => document_1.validatePrecondition(precondition, /* allowExists= */ false), - }); - /** - * A client pool to distribute requests over multiple GAPIC clients in order - * to work around a connection limit of 100 concurrent requests per client. - * @private - * @type {ClientPool|null} - */ - this._clientPool = null; - /** - * Whether the initialization settings can still be changed by invoking - * `settings()`. - * @private - * @type {boolean} - */ - this._settingsFrozen = false; - /** - * A Promise that resolves when client initialization completes. Can be - * 'null' if initialization hasn't started yet. - * @private - * @type {Promise|null} - */ - this._clientInitialized = null; - /** - * The configuration options for the GAPIC client. - * @private - * @type {Object} - */ - this._initalizationSettings = null; - /** - * The serializer to use for the Protobuf transformation. - * @private - * @type {Serializer} - */ - this._serializer = null; - this.validateAndApplySettings(settings); - // GCF currently tears down idle connections after two minutes. Requests - // that are issued after this period may fail. On GCF, we therefore issue - // these requests as part of a transaction so that we can safely retry until - // the network link is reestablished. - // - // The environment variable FUNCTION_TRIGGER_TYPE is used to detect the GCF - // environment. - this._preferTransactions = is_1.default.defined(process.env.FUNCTION_TRIGGER_TYPE); - this._lastSuccessfulRequest = null; - if (this._preferTransactions) { - logger_1.logger('Firestore', null, 'Detected GCF environment'); - } - logger_1.logger('Firestore', null, 'Initialized Firestore'); - } - /** - * Specifies custom settings to be used to configure the `Firestore` - * instance. Can only be invoked once and before any other Firestore method. - * - * If settings are provided via both `settings()` and the `Firestore` - * constructor, both settings objects are merged and any settings provided via - * `settings()` take precedence. - * - * @param {object} settings The settings to use for all Firestore operations. - */ - settings(settings) { - this._validator.isObject('settings', settings); - this._validator.isOptionalString('settings.projectId', settings.projectId); - this._validator.isOptionalBoolean('settings.timestampsInSnapshots', settings.timestampsInSnapshots); - if (this._clientInitialized) { - throw new Error('Firestore has already been started and its settings can no longer ' + - 'be changed. You can only call settings() before calling any other ' + - 'methods on a Firestore object.'); - } - if (this._settingsFrozen) { - throw new Error('Firestore.settings() has already be called. You can only call ' + - 'settings() once, and only before calling any other methods on a ' + - 'Firestore object.'); - } - const mergedSettings = extend_1.default({}, this._initalizationSettings, settings); - this.validateAndApplySettings(mergedSettings); - this._settingsFrozen = true; - } - validateAndApplySettings(settings) { - this._validator.isOptionalBoolean('settings.timestampsInSnapshots', settings.timestampsInSnapshots); - this._timestampsInSnapshotsEnabled = !!settings.timestampsInSnapshots; - if (settings && settings.projectId) { - this._validator.isString('settings.projectId', settings.projectId); - this._referencePath = new path_1.ResourcePath(settings.projectId, '(default)'); - } - else { - // Initialize a temporary reference path that will be overwritten during - // project ID detection. - this._referencePath = new path_1.ResourcePath('{{projectId}}', '(default)'); - } - this._initalizationSettings = settings; - this._serializer = new serializer_1.Serializer(this, this._timestampsInSnapshotsEnabled); - } - /** - * The root path to the database. - * - * @private - * @type {string} - */ - get formattedName() { - return this._referencePath.formattedName; - } - /** - * Gets a [DocumentReference]{@link DocumentReference} instance that - * refers to the document at the specified path. - * - * @param {string} documentPath - A slash-separated path to a document. - * @returns {DocumentReference} The - * [DocumentReference]{@link DocumentReference} instance. - * - * @example - * let documentRef = firestore.doc('collection/document'); - * console.log(`Path of document is ${documentRef.path}`); - */ - doc(documentPath) { - this._validator.isResourcePath('documentPath', documentPath); - let path = this._referencePath.append(documentPath); - if (!path.isDocument) { - throw new Error(`Argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`); - } - return new reference_1.DocumentReference(this, path); - } - /** - * Gets a [CollectionReference]{@link CollectionReference} instance - * that refers to the collection at the specified path. - * - * @param {string} collectionPath - A slash-separated path to a collection. - * @returns {CollectionReference} The - * [CollectionReference]{@link CollectionReference} instance. - * - * @example - * let collectionRef = firestore.collection('collection'); - * - * // Add a document with an auto-generated ID. - * collectionRef.add({foo: 'bar'}).then((documentRef) => { - * console.log(`Added document at ${documentRef.path})`); - * }); - */ - collection(collectionPath) { - this._validator.isResourcePath('collectionPath', collectionPath); - let path = this._referencePath.append(collectionPath); - if (!path.isCollection) { - throw new Error(`Argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`); - } - return new reference_1.CollectionReference(this, path); - } - /** - * Creates a [WriteBatch]{@link WriteBatch}, used for performing - * multiple writes as a single atomic operation. - * - * @returns {WriteBatch} A WriteBatch that operates on this Firestore - * client. - * - * @example - * let writeBatch = firestore.batch(); - * - * // Add two documents in an atomic batch. - * let data = { foo: 'bar' }; - * writeBatch.set(firestore.doc('col/doc1'), data); - * writeBatch.set(firestore.doc('col/doc2'), data); - * - * writeBatch.commit().then(res => { - * console.log(`Added document at ${res.writeResults[0].updateTime}`); - * }); - */ - batch() { - return new write_batch_1.WriteBatch(this); - } - /** - * Creates a [DocumentSnapshot]{@link DocumentSnapshot} or a - * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} from a - * `firestore.v1beta1.Document` proto (or from a resource name for missing - * documents). - * - * This API is used by Google Cloud Functions and can be called with both - * 'Proto3 JSON' and 'Protobuf JS' encoded data. - * - * @private - * @param {object|string} documentOrName - The Firestore 'Document' proto or - * the resource name of a missing document. - * @param {object=} readTime - A 'Timestamp' proto indicating the time this - * document was read. - * @param {string=} encoding - One of 'json' or 'protobufJS'. Applies to both - * the 'document' Proto and 'readTime'. Defaults to 'protobufJS'. - * @returns {DocumentSnapshot|QueryDocumentSnapshot} - A QueryDocumentSnapshot - * for existing documents, otherwise a DocumentSnapshot. - */ - snapshot_(documentOrName, readTime, encoding) { - // TODO: Assert that Firestore Project ID is valid. - let convertTimestamp; - let convertDocument; - if (!is_1.default.defined(encoding) || encoding === 'protobufJS') { - convertTimestamp = data => data; - convertDocument = data => data; - } - else if (encoding === 'json') { - // Google Cloud Functions calls us with Proto3 JSON format data, which we - // must convert to Protobuf JS. - convertTimestamp = convert.timestampFromJson; - convertDocument = convert.documentFromJson; - } - else { - throw new Error(`Unsupported encoding format. Expected 'json' or 'protobufJS', ` + - `but was '${encoding}'.`); - } - const document = new document_1.DocumentSnapshot.Builder(); - if (is_1.default.string(documentOrName)) { - document.ref = new reference_1.DocumentReference(this, path_1.ResourcePath.fromSlashSeparatedString(documentOrName)); - } - else { - document.ref = new reference_1.DocumentReference(this, path_1.ResourcePath.fromSlashSeparatedString(documentOrName.name)); - document.fieldsProto = - documentOrName.fields ? convertDocument(documentOrName.fields) : {}; - document.createTime = timestamp_1.Timestamp.fromProto(convertTimestamp(documentOrName.createTime, 'documentOrName.createTime')); - document.updateTime = timestamp_1.Timestamp.fromProto(convertTimestamp(documentOrName.updateTime, 'documentOrName.updateTime')); - } - if (readTime) { - document.readTime = - timestamp_1.Timestamp.fromProto(convertTimestamp(readTime, 'readTime')); - } - return document.build(); - } - /** - * Executes the given updateFunction and commits the changes applied within - * the transaction. - * - * You can use the transaction object passed to 'updateFunction' to read and - * modify Firestore documents under lock. Transactions are committed once - * 'updateFunction' resolves and attempted up to five times on failure. - * - * @param {function(Transaction)} updateFunction - The - * function to execute within the transaction - * context. - * @param {object=} transactionOptions - Transaction options. - * @param {number=} transactionOptions.maxAttempts - The maximum number of - * attempts for this transaction. - * @returns {Promise} If the transaction completed successfully or was - * explicitly aborted (by the updateFunction returning a failed Promise), the - * Promise returned by the updateFunction will be returned here. Else if the - * transaction failed, a rejected Promise with the corresponding failure - * error will be returned. - * - * @example - * let counterTransaction = firestore.runTransaction(transaction => { - * let documentRef = firestore.doc('col/doc'); - * return transaction.get(documentRef).then(doc => { - * if (doc.exists) { - * let count = doc.get('count') || 0; - * if (count > 10) { - * return Promise.reject('Reached maximum count'); - * } - * transaction.update(documentRef, { count: ++count }); - * return Promise.resolve(count); - * } - * - * transaction.create(documentRef, { count: 1 }); - * return Promise.resolve(1); - * }); - * }); - * - * counterTransaction.then(res => { - * console.log(`Count updated to ${res}`); - * }); - */ - runTransaction(updateFunction, transactionOptions) { - this._validator.isFunction('updateFunction', updateFunction); - const defaultAttempts = 5; - let attemptsRemaining = defaultAttempts; - let previousTransaction; - if (is_1.default.defined(transactionOptions)) { - this._validator.isObject('transactionOptions', transactionOptions); - this._validator.isOptionalInteger('transactionOptions.maxAttempts', transactionOptions.maxAttempts, 1); - attemptsRemaining = transactionOptions.maxAttempts || attemptsRemaining; - previousTransaction = transactionOptions.previousTransaction; - } - const transaction = new transaction_1.Transaction(this, previousTransaction); - const requestTag = transaction.requestTag; - let result; - --attemptsRemaining; - return transaction.begin() - .then(() => { - let promise = updateFunction(transaction); - result = is_1.default.instanceof(promise, Promise) ? - promise : - Promise.reject(new Error('You must return a Promise in your transaction()-callback.')); - return result.catch(err => { - logger_1.logger('Firestore.runTransaction', requestTag, 'Rolling back transaction after callback error:', err); - // Rollback the transaction and return the failed result. - return transaction.rollback().then(() => { - return result; - }); - }); - }) - .then(() => { - return transaction.commit().then(() => result).catch(err => { - if (attemptsRemaining > 0) { - logger_1.logger('Firestore.runTransaction', requestTag, `Retrying transaction after error: ${JSON.stringify(err)}.`); - return this.runTransaction(updateFunction, { - previousTransaction: transaction, - maxAttempts: attemptsRemaining, - }); - } - logger_1.logger('Firestore.runTransaction', requestTag, 'Exhausted transaction retries, returning error: %s', err); - return Promise.reject(err); - }); - }); - } - /** - * Fetches the root collections that are associated with this Firestore - * database. - * - * @returns {Promise.>} A Promise that resolves - * with an array of CollectionReferences. - * - * @example - * firestore.getCollections().then(collections => { - * for (let collection of collections) { - * console.log(`Found collection with id: ${collection.id}`); - * } - * }); - */ - getCollections() { - let rootDocument = new reference_1.DocumentReference(this, this._referencePath); - return rootDocument.getCollections(); - } - /** - * Retrieves multiple documents from Firestore. - * - * @param {...DocumentReference} documents - The document references - * to receive. - * @returns {Promise>} A Promise that - * contains an array with the resulting document snapshots. - * - * @example - * let documentRef1 = firestore.doc('col/doc1'); - * let documentRef2 = firestore.doc('col/doc2'); - * - * firestore.getAll(documentRef1, documentRef2).then(docs => { - * console.log(`First document: ${JSON.stringify(docs[0])}`); - * console.log(`Second document: ${JSON.stringify(docs[1])}`); - * }); - */ - getAll(documents) { - documents = is_1.default.array(arguments[0]) ? arguments[0].slice() : - Array.prototype.slice.call(arguments); - for (let i = 0; i < documents.length; ++i) { - this._validator.isDocumentReference(i, documents[i]); - } - return this.getAll_(documents, util_1.requestTag()); - } - /** - * Internal method to retrieve multiple documents from Firestore, optionally - * as part of a transaction. - * - * @private - * @param {Array.} docRefs - The documents - * to receive. - * @param {string} requestTag A unique client-assigned identifier for this - * request. - * @param {bytes=} transactionId - transactionId - The transaction ID to use - * for this read. - * @returns {Promise>} A Promise that contains an array with - * the resulting documents. - */ - getAll_(docRefs, requestTag, transactionId) { - const requestedDocuments = new Set(); - const retrievedDocuments = new Map(); - let request = { - database: this.formattedName, - transaction: transactionId, - }; - for (let docRef of docRefs) { - requestedDocuments.add(docRef.formattedName); - } - request.documents = Array.from(requestedDocuments); - const self = this; - return self.readStream('batchGetDocuments', request, requestTag, true) - .then(stream => { - return new Promise((resolve, reject) => { - stream - .on('error', err => { - logger_1.logger('Firestore.getAll_', requestTag, 'GetAll failed with error:', err); - reject(err); - }) - .on('data', response => { - try { - let document; - if (response.found) { - logger_1.logger('Firestore.getAll_', requestTag, 'Received document: %s', response.found.name); - document = - self.snapshot_(response.found, response.readTime); - } - else { - logger_1.logger('Firestore.getAll_', requestTag, 'Document missing: %s', response.missing); - document = self.snapshot_(response.missing, response.readTime); - } - let path = document.ref.path; - retrievedDocuments.set(path, document); - } - catch (err) { - logger_1.logger('Firestore.getAll_', requestTag, 'GetAll failed with exception:', err); - reject(err); - } - }) - .on('end', () => { - logger_1.logger('Firestore.getAll_', requestTag, 'Received %d results', retrievedDocuments.size); - // BatchGetDocuments doesn't preserve document order. We use - // the request order to sort the resulting documents. - const orderedDocuments = []; - for (let docRef of docRefs) { - let document = retrievedDocuments.get(docRef.path); - if (!is_1.default.defined(document)) { - reject(new Error(`Did not receive document for "${docRef.path}".`)); - } - orderedDocuments.push(document); - } - resolve(orderedDocuments); - }); - stream.resume(); - }); - }); - } - /** - * Executes a new request using the first available GAPIC client. - * - * @private - */ - _runRequest(op) { - // Initialize the client pool if this is the first request. - if (!this._clientInitialized) { - if (!this._timestampsInSnapshotsEnabled) { - console.error(` -The behavior for Date objects stored in Firestore is going to change -AND YOUR APP MAY BREAK. -To hide this warning and ensure your app does not break, you need to add the -following code to your app before calling any other Cloud Firestore methods: - - const firestore = new Firestore(); - const settings = {/* your settings... */ timestampsInSnapshots: true}; - firestore.settings(settings); - -With this change, timestamps stored in Cloud Firestore will be read back as -Firebase Timestamp objects instead of as system Date objects. So you will also -need to update code expecting a Date to instead expect a Timestamp. For example: - - // Old: - const date = snapshot.get('created_at'); - // New: - const timestamp = snapshot.get('created_at'); - const date = timestamp.toDate(); - -Please audit all existing usages of Date when you enable the new behavior. In a -future release, the behavior will change to the new behavior, so if you do not -follow these steps, YOUR APP MAY BREAK.`); - } - this._clientInitialized = this._initClientPool().then(clientPool => { - this._clientPool = clientPool; - }); - } - return this._clientInitialized.then(() => this._clientPool.run(op)); - } - /** - * Initializes the client pool and invokes Project ID detection. Returns a - * Promise on completion. - * - * @private - * @return {Promise} - */ - _initClientPool() { - assert_1.default(!this._clientInitialized, 'Client pool already initialized'); - const clientPool = new pool_1.ClientPool(MAX_CONCURRENT_REQUESTS_PER_CLIENT, () => { - const gapicClient = module.exports.v1beta1(this._initalizationSettings); - logger_1.logger('Firestore', null, 'Initialized Firestore GAPIC Client'); - return gapicClient; - }); - const projectIdProvided = this._referencePath.projectId !== '{{projectId}}'; - if (projectIdProvided) { - return Promise.resolve(clientPool); - } - else { - return clientPool.run(client => this._detectProjectId(client)) - .then(projectId => { - this._referencePath = - new path_1.ResourcePath(projectId, this._referencePath.databaseId); - return clientPool; - }); - } - } - /** - * Auto-detects the Firestore Project ID. - * - * @private - * @param {object} gapicClient - The Firestore GAPIC client. - * @return {Promise} A Promise that resolves with the Project ID. - */ - _detectProjectId(gapicClient) { - return new Promise((resolve, reject) => { - gapicClient.getProjectId((err, projectId) => { - if (err) { - logger_1.logger('Firestore._detectProjectId', null, 'Failed to detect project ID: %s', err); - reject(err); - } - else { - logger_1.logger('Firestore._detectProjectId', null, 'Detected project ID: %s', projectId); - resolve(projectId); - } - }); - }); - } - /** - * Decorate the request options of an API request. This is used to replace - * any `{{projectId}}` placeholders with the value detected from the user's - * environment, if one wasn't provided manually. - * - * @private - */ - _decorateRequest(request) { - let decoratedRequest = extend_1.default(true, {}, request); - decoratedRequest = - projectify_1.replaceProjectIdToken(decoratedRequest, this._referencePath.projectId); - let decoratedGax = { otherArgs: { headers: {} } }; - decoratedGax.otherArgs.headers[CLOUD_RESOURCE_HEADER] = this.formattedName; - return { request: decoratedRequest, gax: decoratedGax }; - } - /** - * A function returning a Promise that can be retried. - * - * @private - * @callback retryFunction - * @returns {Promise} A Promise indicating the function's success. - */ - /** - * Helper method that retries failed Promises. - * - * If 'delayMs' is specified, waits 'delayMs' between invocations. Otherwise, - * schedules the first attempt immediately, and then waits 100 milliseconds - * for further attempts. - * - * @private - * @param {number} attemptsRemaining - The number of available attempts. - * @param {string} requestTag - A unique client-assigned identifier for this - * request. - * @param {retryFunction} func - Method returning a Promise than can be - * retried. - * @param {number=} delayMs - How long to wait before issuing a this retry. - * Defaults to zero. - * @returns {Promise} - A Promise with the function's result if successful - * within `attemptsRemaining`. Otherwise, returns the last rejected Promise. - */ - _retry(attemptsRemaining, requestTag, func, delayMs) { - let self = this; - let currentDelay = delayMs || 0; - let nextDelay = delayMs || 100; - --attemptsRemaining; - return new Promise(resolve => { - setTimeout(resolve, currentDelay); - }) - .then(func) - .then(result => { - self._lastSuccessfulRequest = new Date().getTime(); - return result; - }) - .catch(err => { - if (is_1.default.defined(err.code) && err.code !== GRPC_UNAVAILABLE) { - logger_1.logger('Firestore._retry', requestTag, 'Request failed with unrecoverable error:', err); - return Promise.reject(err); - } - if (attemptsRemaining === 0) { - logger_1.logger('Firestore._retry', requestTag, 'Request failed with error:', err); - return Promise.reject(err); - } - logger_1.logger('Firestore._retry', requestTag, 'Retrying request that failed with error:', err); - return self._retry(attemptsRemaining, requestTag, func, nextDelay); - }); - } - /** - * Opens the provided stream and waits for it to become healthy. If an error - * occurs before the first byte is read, the method rejects the returned - * Promise. - * - * @private - * @param {Stream} resultStream - The Node stream to monitor. - * @param {string} requestTag A unique client-assigned identifier for this - * request. - * @param {Object=} request - If specified, the request that should be written - * to the stream after it opened. - * @returns {Promise.} The given Stream once it is considered healthy. - */ - _initializeStream(resultStream, requestTag, request) { - /** The last error we received and have not forwarded yet. */ - let errorReceived = null; - /** - * Whether we have resolved the Promise and returned the stream to the - * caller. - */ - let streamReleased = false; - /** - * Whether the stream end has been reached. This has to be forwarded to the - * caller.. - */ - let endCalled = false; - return new Promise((resolve, reject) => { - const releaseStream = () => { - if (errorReceived) { - logger_1.logger('Firestore._initializeStream', requestTag, 'Emit error:', errorReceived); - resultStream.emit('error', errorReceived); - errorReceived = null; - } - else if (!streamReleased) { - logger_1.logger('Firestore._initializeStream', requestTag, 'Releasing stream'); - streamReleased = true; - resultStream.pause(); - // Calling 'stream.pause()' only holds up 'data' events and not the - // 'end' event we intend to forward here. We therefore need to wait - // until the API consumer registers their listeners (in the .then() - // call) before emitting any further events. - resolve(resultStream); - // We execute the forwarding of the 'end' event via setTimeout() as - // V8 guarantees that the above the Promise chain is resolved before - // any calls invoked via setTimeout(). - setTimeout(() => { - if (endCalled) { - logger_1.logger('Firestore._initializeStream', requestTag, 'Forwarding stream close'); - resultStream.emit('end'); - } - }, 0); - } - }; - // We capture any errors received and buffer them until the caller has - // registered a listener. We register our event handler as early as - // possible to avoid the default stream behavior (which is just to log and - // continue). - resultStream.on('readable', () => { - releaseStream(); - }); - resultStream.on('end', () => { - logger_1.logger('Firestore._initializeStream', requestTag, 'Received stream end'); - endCalled = true; - releaseStream(); - }); - resultStream.on('error', err => { - logger_1.logger('Firestore._initializeStream', requestTag, 'Received stream error:', err); - // If we receive an error before we were able to receive any data, - // reject this stream. - if (!streamReleased) { - logger_1.logger('Firestore._initializeStream', requestTag, 'Received initial error:', err); - streamReleased = true; - reject(err); - } - else { - errorReceived = err; - } - }); - if (is_1.default.defined(request)) { - logger_1.logger('Firestore._initializeStream', requestTag, 'Sending request: %j', request); - resultStream.write(request, 'utf-8', () => { - logger_1.logger('Firestore._initializeStream', requestTag, 'Marking stream as healthy'); - releaseStream(); - }); - } - }); - } - /** - * A funnel for all non-streaming API requests, assigning a project ID where - * necessary within the request options. - * - * @private - * @param {function} methodName - Name of the veneer API endpoint that takes a - * request and GAX options. - * @param {Object} request - The Protobuf request to send. - * @param {string} requestTag A unique client-assigned identifier for this - * request. - * @param {boolean} allowRetries - Whether this is an idempotent request that - * can be retried. - * @returns {Promise.} A Promise with the request result. - */ - request(methodName, request, requestTag, allowRetries) { - let attempts = allowRetries ? MAX_REQUEST_RETRIES : 1; - return this._runRequest(gapicClient => { - const decorated = this._decorateRequest(request); - return this._retry(attempts, requestTag, () => { - return new Promise((resolve, reject) => { - logger_1.logger('Firestore.request', requestTag, 'Sending request: %j', decorated.request); - gapicClient[methodName](decorated.request, decorated.gax, (err, result) => { - if (err) { - logger_1.logger('Firestore.request', requestTag, 'Received error:', err); - reject(err); - } - else { - logger_1.logger('Firestore.request', requestTag, 'Received response: %j', result); - resolve(result); - } - }); - }); - }); - }); - } - /** - * A funnel for read-only streaming API requests, assigning a project ID where - * necessary within the request options. - * - * The stream is returned in paused state and needs to be resumed once all - * listeners are attached. - * - * @private - * @param {string} methodName - Name of the streaming Veneer API endpoint that - * takes a request and GAX options. - * @param {Object} request - The Protobuf request to send. - * @param {string} requestTag A unique client-assigned identifier for this - * request. - * @param {boolean} allowRetries - Whether this is an idempotent request that - * can be retried. - * @returns {Promise.} A Promise with the resulting read-only stream. - */ - readStream(methodName, request, requestTag, allowRetries) { - let attempts = allowRetries ? MAX_REQUEST_RETRIES : 1; - return this._runRequest(gapicClient => { - const decorated = this._decorateRequest(request); - return this._retry(attempts, requestTag, () => { - return new Promise((resolve, reject) => { - try { - logger_1.logger('Firestore.readStream', requestTag, 'Sending request: %j', decorated.request); - let stream = gapicClient[methodName](decorated.request, decorated.gax); - let logStream = through2_1.default.obj(function (chunk, enc, callback) { - logger_1.logger('Firestore.readStream', requestTag, 'Received response: %j', chunk); - this.push(chunk); - callback(); - }); - resolve(bun_1.default([stream, logStream])); - } - catch (err) { - logger_1.logger('Firestore.readStream', requestTag, 'Received error:', err); - reject(err); - } - }) - .then(stream => this._initializeStream(stream, requestTag)); - }); - }); - } - /** - * A funnel for read-write streaming API requests, assigning a project ID - * where necessary for all writes. - * - * The stream is returned in paused state and needs to be resumed once all - * listeners are attached. - * - * @private - * @param {string} methodName - Name of the streaming Veneer API endpoint that - * takes GAX options. - * @param {Object} request - The Protobuf request to send as the first stream - * message. - * @param {string} requestTag A unique client-assigned identifier for this - * request. - * @param {boolean} allowRetries - Whether this is an idempotent request that - * can be retried. - * @returns {Promise.} A Promise with the resulting read/write stream. - */ - readWriteStream(methodName, request, requestTag, allowRetries) { - let self = this; - let attempts = allowRetries ? MAX_REQUEST_RETRIES : 1; - return this._runRequest(gapicClient => { - const decorated = this._decorateRequest(request); - return this._retry(attempts, requestTag, () => { - return Promise.resolve().then(() => { - logger_1.logger('Firestore.readWriteStream', requestTag, 'Opening stream'); - // The generated bi-directional streaming API takes the list of GAX - // headers as its second argument. - let requestStream = gapicClient[methodName]({}, decorated.gax); - // The transform stream to assign the project ID. - let transform = through2_1.default.obj(function (chunk, encoding, callback) { - let decoratedChunk = extend_1.default(true, {}, chunk); - projectify_1.replaceProjectIdToken(decoratedChunk, self._referencePath.projectId); - logger_1.logger('Firestore.readWriteStream', requestTag, 'Streaming request: %j', decoratedChunk); - requestStream.write(decoratedChunk, encoding, callback); - }); - let logStream = through2_1.default.obj(function (chunk, enc, callback) { - logger_1.logger('Firestore.readWriteStream', requestTag, 'Received response: %j', chunk); - this.push(chunk); - callback(); - }); - let resultStream = bun_1.default([transform, requestStream, logStream]); - return this._initializeStream(resultStream, requestTag, request); - }); - }); - }); - } -} -/** - * Validates a JavaScript value for usage as a Firestore value. - * - * @private - * @param {Object} val JavaScript value to validate. - * @param {string} options.allowDeletes At what level field deletes are - * supported (acceptable values are 'none', 'root' or 'all'). - * @param {boolean} options.allowServerTimestamps Whether server timestamps - * are supported. - * @param {number=} depth The current depth of the traversal. - * @param {number=} inArray Whether we are inside an array. - * @returns {boolean} 'true' when the object is valid. - * @throws {Error} when the object is invalid. - */ -function validateFieldValue(val, options, depth, inArray) { - assert_1.default(['none', 'root', 'all'].indexOf(options.allowDeletes) !== -1, 'Expected \'none\', \'root\', or \'all\' for \'options.allowDeletes\''); - assert_1.default(typeof options.allowTransforms === 'boolean', 'Expected boolean for \'options.allowTransforms\''); - if (!depth) { - depth = 1; - } - else if (depth > MAX_DEPTH) { - throw new Error(`Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`); - } - inArray = inArray || false; - if (is_1.default.array(val)) { - for (let prop of val) { - validateFieldValue(val[prop], options, depth + 1, /* inArray= */ true); - } - } - else if (serializer_1.isPlainObject(val)) { - for (let prop in val) { - if (val.hasOwnProperty(prop)) { - validateFieldValue(val[prop], options, depth + 1, inArray); - } - } - } - else if (val instanceof field_value_1.DeleteTransform) { - if (inArray) { - throw new Error(`${val.methodName}() cannot be used inside of an array.`); - } - else if ((options.allowDeletes === 'root' && depth > 1) || - options.allowDeletes === 'none') { - throw new Error(`${val.methodName}() must appear at the top-level and can only be used in update() or set() with {merge:true}.`); - } - } - else if (val instanceof field_value_1.FieldTransform) { - if (inArray) { - throw new Error(`${val.methodName}() cannot be used inside of an array.`); - } - else if (!options.allowTransforms) { - throw new Error(`${val.methodName}() can only be used in set(), create() or update().`); - } - } - else if (is_1.default.instanceof(val, reference_1.DocumentReference)) { - return true; - } - else if (is_1.default.instanceof(val, geo_point_1.GeoPoint)) { - return true; - } - else if (is_1.default.instanceof(val, timestamp_1.Timestamp)) { - return true; - } - else if (is_1.default.instanceof(val, path_1.FieldPath)) { - throw new Error('Cannot use object of type "FieldPath" as a Firestore value.'); - } - else if (is_1.default.object(val)) { - throw validate_1.customObjectError(val); - } - return true; -} -/** - * Validates a JavaScript object for usage as a Firestore document. - * - * @private - * @param {Object} obj JavaScript object to validate. - * @param {string} options.allowDeletes At what level field deletes are - * supported (acceptable values are 'none', 'root' or 'all'). - * @param {boolean} options.allowServerTimestamps Whether server timestamps - * are supported. - * @param {boolean} options.allowEmpty Whether empty documents are supported. - * @returns {boolean} 'true' when the object is valid. - * @throws {Error} when the object is invalid. - */ -function validateDocumentData(obj, options) { - assert_1.default(typeof options.allowEmpty === 'boolean', 'Expected boolean for \'options.allowEmpty\''); - if (!serializer_1.isPlainObject(obj)) { - throw new Error('Input is not a plain JavaScript object.'); - } - options = options || {}; - let isEmpty = true; - for (let prop in obj) { - if (obj.hasOwnProperty(prop)) { - isEmpty = false; - validateFieldValue(obj[prop], options, /* depth= */ 1); - } - } - if (options.allowEmpty === false && isEmpty) { - throw new Error('At least one field must be updated.'); - } - return true; -} -/** - * A logging function that takes a single string. - * - * @callback Firestore~logFunction - * @param {string} Log message - */ -/** - * Sets the log function for all active Firestore instances. - * - * @method Firestore.setLogFunction - * @param {Firestore~logFunction} logger - A log function that takes a single - * string. - */ -Firestore.setLogFunction = logger_1.setLogFunction; -/** - * The default export of the `@google-cloud/firestore` package is the - * {@link Firestore} class. - * - * See {@link Firestore} and {@link ClientConfig} for client methods and - * configuration options. - * - * @module {Firestore} @google-cloud/firestore - * @alias nodejs-firestore - * - * @example Install the client library with npm: npm install --save - * @google-cloud/firestore - * - * @example Import the client library - * var Firestore = require('@google-cloud/firestore'); - * - * @example Create a client that uses Application - * Default Credentials (ADC): var firestore = new Firestore(); - * - * @example Create a client with explicit - * credentials: var firestore = new Firestore({ projectId: - * 'your-project-id', keyFilename: '/path/to/keyfile.json' - * }); - * - * @example include:samples/quickstart.js - * region_tag:firestore_quickstart - * Full quickstart example: - */ -module.exports = Firestore; -module.exports.default = Firestore; -module.exports.Firestore = Firestore; -/** - * {@link v1beta1} factory function. - * - * @name Firestore.v1beta1 - * @see v1beta1 - * @type {function} - */ -Object.defineProperty(module.exports, 'v1beta1', { - // The v1beta1 module is very large. To avoid pulling it in from static - // scope, we lazy-load and cache the module. - get: () => { - if (!v1beta1) { - v1beta1 = require('./v1beta1'); - } - return v1beta1; - }, -}); -/** - * {@link GeoPoint} class. - * - * @name Firestore.GeoPoint - * @see GeoPoint - * @type {Constructor} - */ -module.exports.GeoPoint = geo_point_1.GeoPoint; -/** - * {@link Transaction} class. - * - * @name Firestore.Transaction - * @see Transaction - * @type Transaction - */ -module.exports.Transaction = transaction_1.Transaction; -/** - * {@link WriteBatch} class. - * - * @name Firestore.WriteBatch - * @see WriteBatch - * @type WriteBatch - */ -module.exports.WriteBatch = write_batch_1.WriteBatch; -/** - * {@link DocumentReference} class. - * - * @name Firestore.DocumentReference - * @see DocumentReference - * @type DocumentReference - */ -module.exports.DocumentReference = reference_1.DocumentReference; -/** - * {@link WriteResult} class. - * - * @name Firestore.WriteResult - * @see WriteResult - * @type WriteResult - */ -module.exports.WriteResult = write_batch_1.WriteResult; -/** - * {@link DocumentSnapshot} DocumentSnapshot. - * - * @name Firestore.DocumentSnapshot - * @see DocumentSnapshot - * @type DocumentSnapshot - */ -module.exports.DocumentSnapshot = document_1.DocumentSnapshot; -/** - * {@link QueryDocumentSnapshot} class. - * - * @name Firestore.QueryDocumentSnapshot - * @see QueryDocumentSnapshot - * @type QueryDocumentSnapshot - */ -module.exports.QueryDocumentSnapshot = document_1.QueryDocumentSnapshot; -/** - * {@link CollectionReference} class. - * - * @name Firestore.CollectionReference - * @see CollectionReference - * @type CollectionReference - */ -module.exports.CollectionReference = reference_1.CollectionReference; -/** - * {@link QuerySnapshot} class. - * - * @name Firestore.QuerySnapshot - * @see QuerySnapshot - * @type QuerySnapshot - */ -module.exports.QuerySnapshot = reference_1.QuerySnapshot; -/** - * {@link DocumentChange} class. - * - * @name Firestore.DocumentChange - * @see DocumentChange - * @type DocumentChange - */ -module.exports.DocumentChange = document_change_1.DocumentChange; -/** - * {@link Query} class. - * - * @name Firestore.Query - * @see Query - * @type Query - */ -module.exports.Query = reference_1.Query; -/** - * {@link FieldValue} class. - * - * @name Firestore.FieldValue - * @see FieldValue - */ -module.exports.FieldValue = field_value_1.FieldValue; -/** - * {@link FieldPath} class. - * - * @name Firestore.FieldPath - * @see FieldPath - * @type {Constructor} - */ -module.exports.FieldPath = path_1.FieldPath; -/** - * {@link Timestamp} class. - * - * @name Firestore.Timestamp - * @see Timestamp - * @type Timestamp - */ -module.exports.Timestamp = timestamp_1.Timestamp; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/logger.js b/functions/node_modules/@google-cloud/firestore/build/src/logger.js deleted file mode 100644 index d2b6288c..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/logger.js +++ /dev/null @@ -1,60 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const util_1 = __importDefault(require("util")); -const validate_1 = require("./validate"); -const validate = validate_1.createValidator(); -/*! The Firestore library version */ -let libVersion; -/*! The external function used to emit logs. */ -let logFunction = (msg) => { }; -/** - * Log function to use for debug output. By default, we don't perform any - * logging. - * - * @private - */ -function logger(methodName, requestTag, logMessage, ...additionalArgs) { - requestTag = requestTag || '#####'; - const formattedMessage = util_1.default.format(logMessage, ...additionalArgs); - const time = new Date().toISOString(); - logFunction(`Firestore (${libVersion}) ${time} ${requestTag} [${methodName}]: ` + - formattedMessage); -} -exports.logger = logger; -/** - * Sets the log function for all active Firestore instances. - * - * @private - */ -function setLogFunction(logger) { - validate.isFunction('logger', logger); - logFunction = logger; -} -exports.setLogFunction = setLogFunction; -/** - * Sets the log function for all active Firestore instances. - * - * @private - */ -function setLibVersion(version) { - libVersion = version; -} -exports.setLibVersion = setLibVersion; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/order.js b/functions/node_modules/@google-cloud/firestore/build/src/order.js deleted file mode 100644 index cd9e60ad..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/order.js +++ /dev/null @@ -1,238 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is = __importStar(require("is")); -const convert_1 = require("./convert"); -const path_1 = require("./path"); -const validate_1 = require("./validate"); -/*! - * The type order as defined by the backend. - */ -var TypeOrder; -(function (TypeOrder) { - TypeOrder[TypeOrder["NULL"] = 0] = "NULL"; - TypeOrder[TypeOrder["BOOLEAN"] = 1] = "BOOLEAN"; - TypeOrder[TypeOrder["NUMBER"] = 2] = "NUMBER"; - TypeOrder[TypeOrder["TIMESTAMP"] = 3] = "TIMESTAMP"; - TypeOrder[TypeOrder["STRING"] = 4] = "STRING"; - TypeOrder[TypeOrder["BLOB"] = 5] = "BLOB"; - TypeOrder[TypeOrder["REF"] = 6] = "REF"; - TypeOrder[TypeOrder["GEO_POINT"] = 7] = "GEO_POINT"; - TypeOrder[TypeOrder["ARRAY"] = 8] = "ARRAY"; - TypeOrder[TypeOrder["OBJECT"] = 9] = "OBJECT"; -})(TypeOrder || (TypeOrder = {})); -/*! - * @private - */ -function typeOrder(val) { - const valueType = convert_1.detectValueType(val); - switch (valueType) { - case 'nullValue': - return TypeOrder.NULL; - case 'integerValue': - return TypeOrder.NUMBER; - case 'doubleValue': - return TypeOrder.NUMBER; - case 'stringValue': - return TypeOrder.STRING; - case 'booleanValue': - return TypeOrder.BOOLEAN; - case 'arrayValue': - return TypeOrder.ARRAY; - case 'timestampValue': - return TypeOrder.TIMESTAMP; - case 'geoPointValue': - return TypeOrder.GEO_POINT; - case 'bytesValue': - return TypeOrder.BLOB; - case 'referenceValue': - return TypeOrder.REF; - case 'mapValue': - return TypeOrder.OBJECT; - default: - throw validate_1.customObjectError(val); - } -} -/*! - * @private - */ -function primitiveComparator(left, right) { - if (left < right) { - return -1; - } - if (left > right) { - return 1; - } - return 0; -} -exports.primitiveComparator = primitiveComparator; -/*! - * Utility function to compare doubles (using Firestore semantics for NaN). - * @private - */ -function compareNumbers(left, right) { - if (left < right) { - return -1; - } - if (left > right) { - return 1; - } - if (left === right) { - return 0; - } - // one or both are NaN. - if (isNaN(left)) { - return isNaN(right) ? 0 : -1; - } - return 1; -} -/*! - * @private - */ -function compareNumberProtos(left, right) { - let leftValue, rightValue; - if (left.integerValue !== undefined) { - leftValue = Number(left.integerValue); - } - else { - leftValue = Number(left.doubleValue); - } - if (right.integerValue !== undefined) { - rightValue = Number(right.integerValue); - } - else { - rightValue = Number(right.doubleValue); - } - return compareNumbers(leftValue, rightValue); -} -/*! - * @private - */ -function compareTimestamps(left, right) { - const seconds = primitiveComparator(left.seconds || 0, right.seconds || 0); - if (seconds !== 0) { - return seconds; - } - return primitiveComparator(left.nanos || 0, right.nanos || 0); -} -/*! - * @private - */ -function compareBlobs(left, right) { - if (!is.instanceof(left, Buffer) || !is.instanceof(right, Buffer)) { - throw new Error('Blobs can only be compared if they are Buffers.'); - } - return Buffer.compare(left, right); -} -/*! - * @private - */ -function compareReferenceProtos(left, right) { - const leftPath = path_1.ResourcePath.fromSlashSeparatedString(left.referenceValue); - const rightPath = path_1.ResourcePath.fromSlashSeparatedString(right.referenceValue); - return leftPath.compareTo(rightPath); -} -/*! - * @private - */ -function compareGeoPoints(left, right) { - return (primitiveComparator(left.latitude || 0, right.latitude || 0) || - primitiveComparator(left.longitude || 0, right.longitude || 0)); -} -/*! - * @private - */ -function compareArrays(left, right) { - for (let i = 0; i < left.length && i < right.length; i++) { - const valueComparison = compare(left[i], right[i]); - if (valueComparison !== 0) { - return valueComparison; - } - } - // If all the values matched so far, just check the length. - return primitiveComparator(left.length, right.length); -} -/*! - * @private - */ -function compareObjects(left, right) { - // This requires iterating over the keys in the object in order and doing a - // deep comparison. - const leftKeys = Object.keys(left); - const rightKeys = Object.keys(right); - leftKeys.sort(); - rightKeys.sort(); - for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) { - const keyComparison = primitiveComparator(leftKeys[i], rightKeys[i]); - if (keyComparison !== 0) { - return keyComparison; - } - const key = leftKeys[i]; - const valueComparison = compare(left[key], right[key]); - if (valueComparison !== 0) { - return valueComparison; - } - } - // If all the keys matched so far, just check the length. - return primitiveComparator(leftKeys.length, rightKeys.length); -} -/*! - * @private - */ -function compare(left, right) { - // First compare the types. - const leftType = typeOrder(left); - const rightType = typeOrder(right); - const typeComparison = primitiveComparator(leftType, rightType); - if (typeComparison !== 0) { - return typeComparison; - } - // So they are the same type. - switch (leftType) { - case TypeOrder.NULL: - // Nulls are all equal. - return 0; - case TypeOrder.BOOLEAN: - return primitiveComparator(left.booleanValue, right.booleanValue); - case TypeOrder.STRING: - return primitiveComparator(left.stringValue, right.stringValue); - case TypeOrder.NUMBER: - return compareNumberProtos(left, right); - case TypeOrder.TIMESTAMP: - return compareTimestamps(left.timestampValue, right.timestampValue); - case TypeOrder.BLOB: - return compareBlobs(left.bytesValue, right.bytesValue); - case TypeOrder.REF: - return compareReferenceProtos(left, right); - case TypeOrder.GEO_POINT: - return compareGeoPoints(left.geoPointValue, right.geoPointValue); - case TypeOrder.ARRAY: - return compareArrays(left.arrayValue.values || [], right.arrayValue.values || []); - case TypeOrder.OBJECT: - return compareObjects(left.mapValue.fields || {}, right.mapValue.fields || {}); - default: - throw new Error(`Encountered unknown type order: ${leftType}`); - } -} -exports.compare = compare; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/path.js b/functions/node_modules/@google-cloud/firestore/build/src/path.js deleted file mode 100644 index 23b07c5e..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/path.js +++ /dev/null @@ -1,510 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __importDefault(require("is")); -const validate_1 = require("./validate"); -const validate = validate_1.createValidator(); -/*! - * A regular expression to verify an absolute Resource Path in Firestore. It - * extracts the project ID, the database name and the relative resource path - * if available. - * - * @type {RegExp} - */ -const RESOURCE_PATH_RE = -// Note: [\s\S] matches all characters including newlines. -/^projects\/([^/]*)\/databases\/([^/]*)(?:\/documents\/)?([\s\S]*)$/; -/*! - * A regular expression to verify whether a field name can be passed to the - * backend without escaping. - * - * @type {RegExp} - */ -const UNESCAPED_FIELD_NAME_RE = /^[_a-zA-Z][_a-zA-Z0-9]*$/; -/*! - * A regular expression to verify field paths that are passed to the API as - * strings. Field paths that do not match this expression have to be provided - * as a [FieldPath]{@link FieldPath} object. - * - * @type {RegExp} - */ -const FIELD_PATH_RE = /^[^*~/[\]]+$/; -/** - * An abstract class representing a Firestore path. - * - * Subclasses have to implement `split()` and `canonicalString()`. - * - * @private - * @class - */ -class Path { - /** - * Creates a new Path with the given segments. - * - * @private - * @hideconstructor - * @param {string[]} segments - Sequence of parts of a path. - */ - constructor(segments) { - this.segments = segments; - } - /** - * String representation as expected by the proto API. - * - * @private - * @type {string} - */ - get formattedName() { - return this.canonicalString(); - } - /** - * Create a child path beneath the current level. - * - * @private - * @param {string|T} relativePath - Relative path to append to the current - * path. - * @returns {T} The new path. - * @template T - */ - append(relativePath) { - if (relativePath instanceof Path) { - return this.construct(this.segments.concat(relativePath.segments)); - } - return this.construct(this.segments.concat(this.split(relativePath))); - } - /** - * Returns the path of the parent node. - * - * @private - * @returns {T|null} The new path or null if we are already at the root. - * @returns {T} The new path. - * @template T - */ - parent() { - if (this.segments.length === 0) { - return null; - } - return this.construct(this.segments.slice(0, this.segments.length - 1)); - } - /** - * Checks whether the current path is a prefix of the specified path. - * - * @private - * @param {Path} other - The path to check against. - * @returns {boolean} 'true' iff the current path is a prefix match with - * 'other'. - */ - isPrefixOf(other) { - if (other.segments.length < this.segments.length) { - return false; - } - for (let i = 0; i < this.segments.length; i++) { - if (this.segments[i] !== other.segments[i]) { - return false; - } - } - return true; - } - /** - * Returns a string representation of this path. - * - * @private - * @returns {string} A string representing this path. - */ - toString() { - return this.formattedName; - } - /** - * Compare the current path against another Path object. - * - * @private - * @param {Path} other - The path to compare to. - * @returns {number} -1 if current < other, 1 if current > other, 0 if equal - */ - compareTo(other) { - const len = Math.min(this.segments.length, other.segments.length); - for (let i = 0; i < len; i++) { - if (this.segments[i] < other.segments[i]) { - return -1; - } - if (this.segments[i] > other.segments[i]) { - return 1; - } - } - if (this.segments.length < other.segments.length) { - return -1; - } - if (this.segments.length > other.segments.length) { - return 1; - } - return 0; - } - /** - * Returns a copy of the underlying segments. - * - * @private - * @returns {Array.} A copy of the segments that make up this path. - */ - toArray() { - return this.segments.slice(); - } - /** - * Returns true if this `Path` is equal to the provided value. - * - * @private - * @param {*} other The value to compare against. - * @return {boolean} true if this `Path` is equal to the provided value. - */ - isEqual(other) { - return (this === other || - (is_1.default.instanceof(other, this.constructor) && - this.compareTo(other) === 0)); - } -} -/** - * A slash-separated path for navigating resources (documents and collections) - * within Firestore. - * - * @private - * @class - */ -class ResourcePath extends Path { - /** - * Constructs a Firestore Resource Path. - * - * @private - * @hideconstructor - * - * @param {string} projectId - The Firestore project id. - * @param {string} databaseId - The Firestore database id. - * @param {string[]?} segments - Sequence of names of the parts of - * the path. - */ - constructor(projectId, databaseId, segments) { - const elements = segments instanceof Array ? - segments : - Array.prototype.slice.call(arguments, 2); - super(elements); - this.projectId = projectId; - this.databaseId = databaseId; - } - /** - * String representation of the path relative to the database root. - * - * @private - * @type {string} - */ - get relativeName() { - return this.segments.join('/'); - } - /** - * Indicates whether this ResourcePath points to a document. - * - * @private - * @type {boolean} - */ - get isDocument() { - return this.segments.length > 0 && this.segments.length % 2 === 0; - } - /** - * Indicates whether this ResourcePath points to a collection. - * - * @private - * @type {boolean} - */ - get isCollection() { - return this.segments.length % 2 === 1; - } - /** - * The last component of the path. - * - * @private - * @type {string|null} - */ - get id() { - if (this.segments.length > 0) { - return this.segments[this.segments.length - 1]; - } - return null; - } - /** - * Returns true if the given string can be used as a relative or absolute - * resource path. - * - * @private - * @param {string} resourcePath - The path to validate. - * @throws if the string can't be used as a resource path. - * @returns {boolean} 'true' when the path is valid. - */ - static validateResourcePath(resourcePath) { - if (!is_1.default.string(resourcePath) || resourcePath === '') { - throw new Error(`Path must be a non-empty string.`); - } - if (resourcePath.indexOf('//') >= 0) { - throw new Error('Paths must not contain //.'); - } - return true; - } - /** - * Creates a resource path from an absolute Firestore path. - * - * @private - * @param {string} absolutePath - A string representation of a Resource Path. - * @returns {ResourcePath} The new ResourcePath. - */ - static fromSlashSeparatedString(absolutePath) { - const elements = RESOURCE_PATH_RE.exec(absolutePath); - if (elements) { - const project = elements[1]; - const database = elements[2]; - const path = elements[3]; - return new ResourcePath(project, database).append(path); - } - throw new Error(`Resource name '${absolutePath}' is not valid.`); - } - /** - * Splits a string into path segments, using slashes as separators. - * - * @private - * @override - * @param {string} relativePath - The path to split. - * @returns {Array.} - The split path segments. - */ - split(relativePath) { - // We may have an empty segment at the beginning or end if they had a - // leading or trailing slash (which we allow). - return relativePath.split('/').filter(segment => segment.length > 0); - } - /** - * String representation of a ResourcePath as expected by the API. - * - * @private - * @override - * @returns {string} The representation as expected by the API. - */ - canonicalString() { - let components = [ - 'projects', - this.projectId, - 'databases', - this.databaseId, - ]; - if (this.segments.length > 0) { - components = components.concat('documents', this.segments); - } - return components.join('/'); - } - /** - * Constructs a new instance of ResourcePath. We need this instead of using - * the normal constructor because polymorphic 'this' doesn't work on static - * methods. - * - * @private - * @override - * @param {Array.} segments - Sequence of names of the parts of the - * path. - * @returns {ResourcePath} The newly created ResourcePath. - */ - construct(segments) { - return new ResourcePath(this.projectId, this.databaseId, segments); - } - /** - * Compare the current path against another ResourcePath object. - * - * @private - * @override - * @param {ResourcePath} other - The path to compare to. - * @returns {number} -1 if current < other, 1 if current > other, 0 if equal - */ - compareTo(other) { - // Ignore DocumentReference with {{projectId}} placeholders and assume that - // the resolved IDs match the provided ResourcePath. We could alternatively - // try to resolve the Project ID here, but this is asynchronous as it - // requires Disk I/O. - if (this.projectId !== '{{projectId}}' && - other.projectId !== '{{projectId}}') { - if (this.projectId < other.projectId) { - return -1; - } - if (this.projectId > other.projectId) { - return 1; - } - } - if (this.databaseId < other.databaseId) { - return -1; - } - if (this.databaseId > other.databaseId) { - return 1; - } - return super.compareTo(other); - } - /** - * Converts this ResourcePath to the Firestore Proto representation. - * - * @private - */ - toProto() { - return { - referenceValue: this.formattedName, - }; - } -} -exports.ResourcePath = ResourcePath; -/** - * A dot-separated path for navigating sub-objects within a document. - * - * @class - */ -class FieldPath extends Path { - /** - * Constructs a Firestore Field Path. - * - * @param {...string|string[]} segments - Sequence of field names that form - * this path. - * - * @example - * let query = firestore.collection('col'); - * let fieldPath = new FieldPath('f.o.o', 'bar'); - * - * query.where(fieldPath, '==', 42).get().then(snapshot => { - * snapshot.forEach(document => { - * console.log(`Document contains {'f.o.o' : {'bar' : 42}}`); - * }); - * }); - */ - constructor(segments) { - validate.minNumberOfArguments('FieldPath', arguments, 1); - const elements = segments instanceof Array ? - segments : - Array.prototype.slice.call(arguments); - for (let i = 0; i < elements.length; ++i) { - validate.isString(i, elements[i]); - if (elements[i].length === 0) { - throw new Error(`Argument at index ${i} should not be empty.`); - } - } - super(elements); - } - /** - * A special FieldPath value to refer to the ID of a document. It can be used - * in queries to sort or filter by the document ID. - * - * @returns {FieldPath} - */ - static documentId() { - return FieldPath._DOCUMENT_ID; - } - /** - * Returns true if the provided value can be used as a field path argument. - * - * @private - * @param {string|FieldPath} fieldPath - The value to verify. - * @throws if the string can't be used as a field path. - * @returns {boolean} 'true' when the path is valid. - */ - static validateFieldPath(fieldPath) { - if (!(fieldPath instanceof FieldPath)) { - if (!is_1.default.string(fieldPath)) { - throw validate_1.customObjectError(fieldPath); - } - if (fieldPath.indexOf('..') >= 0) { - throw new Error(`Paths must not contain '..' in them.`); - } - if (fieldPath.startsWith('.') || fieldPath.endsWith('.')) { - throw new Error(`Paths must not start or end with '.'.`); - } - if (!FIELD_PATH_RE.test(fieldPath)) { - throw new Error(`Paths can't be empty and must not contain '*~/[]'.`); - } - } - return true; - } - /** - * Turns a field path argument into a [FieldPath]{@link FieldPath}. - * Supports FieldPaths as input (which are passed through) and dot-separated - * strings. - * - * @private - * @param {string|FieldPath} fieldPath - The FieldPath to create. - * @returns {FieldPath} A field path representation. - */ - static fromArgument(fieldPath) { - // validateFieldPath() is used in all public API entry points to validate - // that fromArgument() is only called with a Field Path or a string. - return fieldPath instanceof FieldPath ? fieldPath : - new FieldPath(fieldPath.split('.')); - } - /** - * String representation of a FieldPath as expected by the API. - * - * @private - * @override - * @returns {string} The representation as expected by the API. - */ - canonicalString() { - return this.segments - .map(str => { - return UNESCAPED_FIELD_NAME_RE.test(str) ? - str : - '`' + str.replace('\\', '\\\\').replace('`', '\\`') + '`'; - }) - .join('.'); - } - /** - * Splits a string into path segments, using dots as separators. - * - * @private - * @override - * @param {string} fieldPath - The path to split. - * @returns {Array.} - The split path segments. - */ - split(fieldPath) { - return fieldPath.split('.'); - } - /** - * Constructs a new instance of FieldPath. We need this instead of using - * the normal constructor because polymorphic 'this' doesn't work on static - * methods. - * - * @private - * @override - * @param {Array.} segments - Sequence of field names. - * @returns {ResourcePath} The newly created FieldPath. - */ - construct(segments) { - return new FieldPath(segments); - } - /** - * Returns true if this `FieldPath` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `FieldPath` is equal to the provided value. - */ - isEqual(other) { - return super.isEqual(other); - } -} -/** - * A special sentinel value to refer to the ID of a document. - * - * @private - */ -FieldPath._DOCUMENT_ID = new FieldPath('__name__'); -exports.FieldPath = FieldPath; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/pool.js b/functions/node_modules/@google-cloud/firestore/build/src/pool.js deleted file mode 100644 index 2ad0ecf6..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/pool.js +++ /dev/null @@ -1,124 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -/** - * An auto-resizing pool that distributes concurrent operations over multiple - * clients of type `T`. - * - * ClientPool is used within Firestore to manage a pool of GAPIC clients and - * automatically initializes multiple clients if we issue more than 100 - * concurrent operations. - * - * @private - */ -class ClientPool { - /** - * @param concurrentOperationLimit - The number of operations that each client - * can handle. - * @param clientFactory - A factory function called as needed when new clients - * are required. - */ - constructor(concurrentOperationLimit, clientFactory) { - this.concurrentOperationLimit = concurrentOperationLimit; - this.clientFactory = clientFactory; - /** Stores each active clients and how many operations it has outstanding. */ - this.activeClients = new Map(); - } - /** - * Returns an already existing client if it has less than the maximum number - * of concurrent operations or initializes and returns a new client. - */ - acquire() { - let selectedClient = null; - let selectedRequestCount = 0; - this.activeClients.forEach((requestCount, client) => { - if (!selectedClient && requestCount < this.concurrentOperationLimit) { - selectedClient = client; - selectedRequestCount = requestCount; - } - }); - if (!selectedClient) { - selectedClient = this.clientFactory(); - assert_1.default(!this.activeClients.has(selectedClient), 'The provided client factory returned an existing instance'); - } - this.activeClients.set(selectedClient, selectedRequestCount + 1); - return selectedClient; - } - /** - * Reduces the number of operations for the provided client, potentially - * removing it from the pool of active clients. - */ - release(client) { - let requestCount = this.activeClients.get(client) || 0; - assert_1.default(requestCount > 0, 'No active request'); - requestCount = requestCount - 1; - this.activeClients.set(client, requestCount); - if (requestCount === 0) { - this.garbageCollect(); - } - } - /** - * The number of currently registered clients. - * - * @return Number of currently registered clients. - */ - // Visible for testing. - get size() { - return this.activeClients.size; - } - /** - * Runs the provided operation in this pool. This function may create an - * additional client if all existing clients already operate at the concurrent - * operation limit. - * - * @param op - A callback function that returns a Promise. The client T will - * be returned to the pool when callback finishes. - * @return A Promise that resolves with the result of `op`. - */ - run(op) { - const client = this.acquire(); - return op(client) - .catch(err => { - this.release(client); - return Promise.reject(err); - }) - .then(res => { - this.release(client); - return res; - }); - } - /** - * Deletes clients that are no longer executing operations. Keeps up to one - * idle client to reduce future initialization costs. - */ - garbageCollect() { - let idleClients = 0; - this.activeClients.forEach((requestCount, client) => { - if (requestCount === 0) { - ++idleClients; - if (idleClients > 1) { - this.activeClients.delete(client); - } - } - }); - } -} -exports.ClientPool = ClientPool; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/reference.js b/functions/node_modules/@google-cloud/firestore/build/src/reference.js deleted file mode 100644 index 87bb667d..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/reference.js +++ /dev/null @@ -1,1782 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const bun_1 = __importDefault(require("bun")); -const deep_equal_1 = __importDefault(require("deep-equal")); -const extend_1 = __importDefault(require("extend")); -const is_1 = __importDefault(require("is")); -const through2_1 = __importDefault(require("through2")); -const order_1 = require("./order"); -const logger_1 = require("./logger"); -const document_1 = require("./document"); -const document_change_1 = require("./document-change"); -const watch_1 = require("./watch"); -const write_batch_1 = require("./write-batch"); -const timestamp_1 = require("./timestamp"); -const path_1 = require("./path"); -const util_1 = require("./util"); -const validate_1 = require("./validate"); -/*! - * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' - * (descending or ascending). - * - * @private - */ -const directionOperators = { - asc: 'ASCENDING', - ASC: 'ASCENDING', - desc: 'DESCENDING', - DESC: 'DESCENDING', -}; -/*! - * Filter conditions in a `Query.where()` clause are specified using the - * strings '<', '<=', '==', '>=', and '>'. - * - * @private - */ -const comparisonOperators = { - '<': 'LESS_THAN', - '<=': 'LESS_THAN_OR_EQUAL', - '=': 'EQUAL', - '==': 'EQUAL', - '>': 'GREATER_THAN', - '>=': 'GREATER_THAN_OR_EQUAL', - 'array-contains': 'ARRAY_CONTAINS' -}; -/** - * onSnapshot() callback that receives a QuerySnapshot. - * - * @callback querySnapshotCallback - * @param {QuerySnapshot} snapshot - A query snapshot. - */ -/** - * onSnapshot() callback that receives a DocumentSnapshot. - * - * @callback documentSnapshotCallback - * @param {DocumentSnapshot} snapshot - A document snapshot. - */ -/** - * onSnapshot() callback that receives an error. - * - * @callback errorCallback - * @param {Error} err - An error from a listen. - */ -/** - * A DocumentReference refers to a document location in a Firestore database - * and can be used to write, read, or listen to the location. The document at - * the referenced location may or may not exist. A DocumentReference can - * also be used to create a - * [CollectionReference]{@link CollectionReference} to a - * subcollection. - * - * @class - */ -class DocumentReference { - /** - * @private - * @hideconstructor - * - * @param {Firestore} firestore - The Firestore Database client. - * @param {ResourcePath} path - The Path of this reference. - */ - constructor(firestore, path) { - this._firestore = firestore; - this._validator = firestore._validator; - this._referencePath = path; - } - /** - * The string representation of the DocumentReference's location. - * @private - * @type {string} - * @name DocumentReference#formattedName - */ - get formattedName() { - return this._referencePath.formattedName; - } - /** - * The [Firestore]{@link Firestore} instance for the Firestore - * database (useful for performing transactions, etc.). - * - * @type {Firestore} - * @name DocumentReference#firestore - * @readonly - * - * @example - * let collectionRef = firestore.collection('col'); - * - * collectionRef.add({foo: 'bar'}).then(documentReference => { - * let firestore = documentReference.firestore; - * console.log(`Root location for document is ${firestore.formattedName}`); - * }); - */ - get firestore() { - return this._firestore; - } - /** - * A string representing the path of the referenced document (relative - * to the root of the database). - * - * @type {string} - * @name DocumentReference#path - * @readonly - * - * @example - * let collectionRef = firestore.collection('col'); - * - * collectionRef.add({foo: 'bar'}).then(documentReference => { - * console.log(`Added document at '${documentReference.path}'`); - * }); - */ - get path() { - return this._referencePath.relativeName; - } - /** - * The last path element of the referenced document. - * - * @type {string} - * @name DocumentReference#id - * @readonly - * - * @example - * let collectionRef = firestore.collection('col'); - * - * collectionRef.add({foo: 'bar'}).then(documentReference => { - * console.log(`Added document with name '${documentReference.id}'`); - * }); - */ - get id() { - return this._referencePath.id; - } - /** - * A reference to the collection to which this DocumentReference belongs. - * - * @name DocumentReference#parent - * @type {CollectionReference} - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * let collectionRef = documentRef.parent; - * - * collectionRef.where('foo', '==', 'bar').get().then(results => { - * console.log(`Found ${results.size} matches in parent collection`); - * }): - */ - get parent() { - return createCollectionReference(this._firestore, this._referencePath.parent()); - } - /** - * Returns the [ResourcePath]{@link ResourcePath} for this - * DocumentReference. - * - * @private - * @type {ResourcePath} - * @readonly - */ - get ref() { - return this._referencePath; - } - /** - * Retrieve a document from the database. Fails the Promise if the document is - * not found. - * - * @returns {Promise.} A Promise resolved with a - * DocumentSnapshot for the retrieved document on success. For missing - * documents, DocumentSnapshot.exists will be false. If the get() fails for - * other reasons, the Promise will be rejected. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * if (documentSnapshot.exists) { - * console.log('Document retrieved successfully.'); - * } - * }); - */ - get() { - return this._firestore.getAll([this]).then(result => { - return result[0]; - }); - } - /** - * Gets a [CollectionReference]{@link CollectionReference} instance - * that refers to the collection at the specified path. - * - * @param {string} collectionPath - A slash-separated path to a collection. - * @returns {CollectionReference} A reference to the new - * subcollection. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * let subcollection = documentRef.collection('subcollection'); - * console.log(`Path to subcollection: ${subcollection.path}`); - */ - collection(collectionPath) { - this._validator.isResourcePath('collectionPath', collectionPath); - let path = this._referencePath.append(collectionPath); - if (!path.isCollection) { - throw new Error(`Argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`); - } - return createCollectionReference(this._firestore, path); - } - /** - * Fetches the subcollections that are direct children of this document. - * - * @returns {Promise.>} A Promise that resolves - * with an array of CollectionReferences. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.getCollections().then(collections => { - * for (let collection of collections) { - * console.log(`Found subcollection with id: ${collection.id}`); - * } - * }); - */ - getCollections() { - const request = { - parent: this._referencePath.formattedName, - }; - return this._firestore.request('listCollectionIds', request, util_1.requestTag()) - .then(collectionIds => { - let collections = []; - // We can just sort this list using the default comparator since it - // will only contain collection ids. - collectionIds.sort(); - for (let collectionId of collectionIds) { - collections.push(this.collection(collectionId)); - } - return collections; - }); - } - /** - * Create a document with the provided object values. This will fail the write - * if a document exists at its location. - * - * @param {DocumentData} data - An object that contains the fields and data to - * serialize as the document. - * @returns {Promise.} A Promise that resolves with the - * write time of this create. - * - * @example - * let documentRef = firestore.collection('col').doc(); - * - * documentRef.create({foo: 'bar'}).then((res) => { - * console.log(`Document created at ${res.updateTime}`); - * }).catch((err) => { - * console.log(`Failed to create document: ${err}`); - * }); - */ - create(data) { - let writeBatch = new write_batch_1.WriteBatch(this._firestore); - return writeBatch.create(this, data).commit().then(writeResults => { - return Promise.resolve(writeResults[0]); - }); - } - /** - * Deletes the document referred to by this `DocumentReference`. - * - * A delete for a non-existing document is treated as a success (unless - * lastUptimeTime is provided). - * - * @param {Precondition=} precondition - A precondition to enforce for this - * delete. - * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the - * document was last updated at lastUpdateTime. Fails the delete if the - * document was last updated at a different time. - * @returns {Promise.} A Promise that resolves with the - * delete time. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.delete().then(() => { - * console.log('Document successfully deleted.'); - * }); - */ - delete(precondition) { - let writeBatch = new write_batch_1.WriteBatch(this._firestore); - return writeBatch.delete(this, precondition).commit().then(writeResults => { - return Promise.resolve(writeResults[0]); - }); - } - /** - * Writes to the document referred to by this DocumentReference. If the - * document does not yet exist, it will be created. If you pass - * [SetOptions]{@link SetOptions}, the provided data can be merged into an - * existing document. - * - * @param {DocumentData} data - A map of the fields and values for the - * document. - * @param {SetOptions=} options - An object to configure the set behavior. - * @param {boolean=} options.merge - If true, set() merges the values - * specified in its data argument. Fields omitted from this set() call - * remain untouched. - * @param {Array.=} options.mergeFields - If provided, - * set() only replaces the specified field paths. Any field path that is not - * specified is ignored and remains untouched. - * @returns {Promise.} A Promise that resolves with the - * write time of this set. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({foo: 'bar'}).then(res => { - * console.log(`Document written at ${res.updateTime}`); - * }); - */ - set(data, options) { - let writeBatch = new write_batch_1.WriteBatch(this._firestore); - return writeBatch.set(this, data, options).commit().then(writeResults => { - return Promise.resolve(writeResults[0]); - }); - } - /** - * Updates fields in the document referred to by this DocumentReference. - * If the document doesn't yet exist, the update fails and the returned - * Promise will be rejected. - * - * The update() method accepts either an object with field paths encoded as - * keys and field values encoded as values, or a variable number of arguments - * that alternate between field paths and field values. - * - * A Precondition restricting this update can be specified as the last - * argument. - * - * @param {UpdateData|string|FieldPath} dataOrField - An object - * containing the fields and values with which to update the document - * or the path of the first field to update. - * @param { - * ...(*|string|FieldPath|Precondition)} preconditionOrValues - - * An alternating list of field paths and values to update or a Precondition - * to restrict this update. - * @returns Promise. A Promise that resolves once the - * data has been successfully written to the backend. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.update({foo: 'bar'}).then(res => { - * console.log(`Document updated at ${res.updateTime}`); - * }); - */ - update(dataOrField, preconditionOrValues) { - this._validator.minNumberOfArguments('update', arguments, 1); - let writeBatch = new write_batch_1.WriteBatch(this._firestore); - preconditionOrValues = Array.prototype.slice.call(arguments, 1); - return writeBatch.update - .apply(writeBatch, [this, dataOrField].concat(preconditionOrValues)) - .commit() - .then(writeResults => { - return Promise.resolve(writeResults[0]); - }); - } - /** - * Attaches a listener for DocumentSnapshot events. - * - * @param {documentSnapshotCallback} onNext - A callback to be called every - * time a new `DocumentSnapshot` is available. - * @param {errorCallback=} onError - A callback to be called if the listen - * fails or is cancelled. No further callbacks will occur. If unset, errors - * will be logged to the console. - * - * @returns {function()} An unsubscribe function that can be called to cancel - * the snapshot listener. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * let unsubscribe = documentRef.onSnapshot(documentSnapshot => { - * if (documentSnapshot.exists) { - * console.log(documentSnapshot.data()); - * } - * }, err => { - * console.log(`Encountered error: ${err}`); - * }); - * - * // Remove this listener. - * unsubscribe(); - */ - onSnapshot(onNext, onError) { - this._validator.isFunction('onNext', onNext); - this._validator.isOptionalFunction('onError', onError); - if (!is_1.default.defined(onError)) { - onError = console.error; - } - let watch = watch_1.Watch.forDocument(this); - return watch.onSnapshot((readTime, size, docs) => { - for (let document of docs()) { - if (document.ref.path === this.path) { - onNext(document); - return; - } - } - // The document is missing. - let document = new document_1.DocumentSnapshot.Builder(); - document.ref = - new DocumentReference(this._firestore, this._referencePath); - document.readTime = readTime; - onNext(document.build()); - }, onError); - } - /** - * Returns true if this `DocumentReference` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `DocumentReference` is equal to the provided - * value. - */ - isEqual(other) { - return (this === other || - (is_1.default.instanceof(other, DocumentReference) && - this._firestore === other._firestore && - this._referencePath.isEqual(other._referencePath))); - } - /** - * Converts this DocumentReference to the Firestore Proto representation. - * - * @private - */ - toProto() { - return { - referenceValue: this.formattedName - }; - } -} -exports.DocumentReference = DocumentReference; -/** - * A Query order-by field. - * - * @private - * @class - */ -class FieldOrder { - /** - * @private - * @hideconstructor - * - * @param {FieldPath} field - The name of a document field (member) - * on which to order query results. - * @param {string=} direction One of 'ASCENDING' (default) or 'DESCENDING' to - * set the ordering direction to ascending or descending, respectively. - */ - constructor(field, direction) { - this._field = field; - this._direction = direction || directionOperators.ASC; - } - /** - * The path of the field on which to order query results. - * - * @private - * @type {FieldPath} - */ - get field() { - return this._field; - } - /** - * One of 'ASCENDING' (default) or 'DESCENDING'. - * - * @private - * @type {string} - */ - get direction() { - return this._direction; - } - /** - * Generates the proto representation for this field order. - * - * @private - * @returns {Object} - */ - toProto() { - return { - field: { - fieldPath: this._field.formattedName, - }, - direction: this._direction, - }; - } -} -/*! - * A field constraint for a Query where clause. - * - * @private - * @class - */ -class FieldFilter { - /** - * @private - * @hideconstructor - * - * @param {FieldPath} field - The path of the property value to - * compare. - * @param {string} opString - A comparison operation. - * @param {*} value The value to which to compare the - * field for inclusion in a query. - */ - constructor(serializer, field, opString, value) { - this._serializer = serializer; - this._field = field; - this._opString = opString; - this._value = value; - } - /** - * Returns the field path of this filter. - * - * @private - * @return {FieldPath} - */ - get field() { - return this._field; - } - /** - * Returns whether this FieldFilter uses an equals comparison. - * - * @private - * @return {boolean} - */ - isInequalityFilter() { - return this._opString === 'GREATER_THAN' || - this._opString === 'GREATER_THAN_OR_EQUAL' || - this._opString === 'LESS_THAN' || - this._opString === 'LESS_THAN_OR_EQUAL'; - } - /** - * Generates the proto representation for this field filter. - * - * @private - * @returns {Object} - */ - toProto() { - if (typeof this._value === 'number' && isNaN(this._value)) { - return { - unaryFilter: { - field: { - fieldPath: this._field.formattedName, - }, - op: 'IS_NAN', - }, - }; - } - if (this._value === null) { - return { - unaryFilter: { - field: { - fieldPath: this._field.formattedName, - }, - op: 'IS_NULL', - }, - }; - } - return { - fieldFilter: { - field: { - fieldPath: this._field.formattedName, - }, - op: this._opString, - value: this._serializer.encodeValue(this._value), - }, - }; - } -} -/** - * A QuerySnapshot contains zero or more - * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} objects - * representing the results of a query. The documents can be accessed as an - * array via the [documents]{@link QuerySnapshot#documents} property - * or enumerated using the [forEach]{@link QuerySnapshot#forEach} - * method. The number of documents can be determined via the - * [empty]{@link QuerySnapshot#empty} and - * [size]{@link QuerySnapshot#size} properties. - * - * @class QuerySnapshot - */ -class QuerySnapshot { - /** - * @private - * @hideconstructor - * - * @param {Query} query - The originating query. - * @param {Timestamp} readTime - The time when this query snapshot was - * obtained. - * @param {number} size - The number of documents in the result set. - * @param {function} docs - A callback returning a sorted array of documents - * matching this query - * @param {function} changes - A callback returning a sorted array of - * document change events for this snapshot. - */ - constructor(query, readTime, size, docs, changes) { - this._query = query; - this._validator = query.firestore._validator; - this._readTime = readTime; - this._size = size; - this._docs = docs; - this._materializedDocs = null; - this._changes = changes; - this._materializedChanges = null; - } - /** - * The query on which you called get() or onSnapshot() in order to get this - * QuerySnapshot. - * - * @type {Query} - * @name QuerySnapshot#query - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.limit(10).get().then(querySnapshot => { - * console.log(`Returned first batch of results`); - * let query = querySnapshot.query; - * return query.offset(10).get(); - * }).then(() => { - * console.log(`Returned second batch of results`); - * }); - */ - get query() { - return this._query; - } - /** - * An array of all the documents in this QuerySnapshot. - * - * @type {Array.} - * @name QuerySnapshot#docs - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.get().then(querySnapshot => { - * let docs = querySnapshot.docs; - * for (let doc of docs) { - * console.log(`Document found at path: ${doc.ref.path}`); - * } - * }); - */ - get docs() { - if (this._materializedDocs) { - return this._materializedDocs; - } - this._materializedDocs = this._docs(); - this._docs = null; - return this._materializedDocs; - } - /** - * An array of all changes in this QuerySnapshot. - * - * @type {Array.} - * @name QuerySnapshot#docChanges - * @readonly - */ - get docChanges() { - if (this._materializedChanges) { - return this._materializedChanges; - } - this._materializedChanges = this._changes(); - this._changes = null; - return this._materializedChanges; - } - /** - * True if there are no documents in the QuerySnapshot. - * - * @type {boolean} - * @name QuerySnapshot#empty - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.get().then(querySnapshot => { - * if (querySnapshot.empty) { - * console.log('No documents found.'); - * } - * }); - */ - get empty() { - return this._size === 0; - } - /** - * The number of documents in the QuerySnapshot. - * - * @type {number} - * @name QuerySnapshot#size - * @readonly - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.get().then(querySnapshot => { - * console.log(`Found ${querySnapshot.size} documents.`); - * }); - */ - get size() { - return this._size; - } - /** - * The time this query snapshot was obtained. - * - * @type {Timestamp} - * @name QuerySnapshot#readTime - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.get().then((querySnapshot) => { - * let readTime = querySnapshot.readTime; - * console.log(`Query results returned at '${readTime.toDate()}'`); - * }); - */ - get readTime() { - return this._readTime; - } - /** - * Enumerates all of the documents in the QuerySnapshot. - * - * @param {function} callback - A callback to be called with a - * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} for each document in - * the snapshot. - * @param {*=} thisArg The `this` binding for the callback.. - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Document found at path: ${documentSnapshot.ref.path}`); - * }); - * }); - */ - forEach(callback, thisArg) { - this._validator.isFunction('callback', callback); - for (let doc of this.docs) { - callback.call(thisArg, doc); - } - } - /** - * Returns true if the document data in this `QuerySnapshot` is equal to the - * provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `QuerySnapshot` is equal to the provided - * value. - */ - isEqual(other) { - // Since the read time is different on every query read, we explicitly - // ignore all metadata in this comparison. - if (this === other) { - return true; - } - if (!is_1.default.instanceof(other, QuerySnapshot)) { - return false; - } - if (this._size !== other._size) { - return false; - } - if (!this._query.isEqual(other._query)) { - return false; - } - if (this._materializedDocs && !this._materializedChanges) { - // If we have only materialized the documents, we compare them first. - return (isArrayEqual(this.docs, other.docs) && - isArrayEqual(this.docChanges, other.docChanges)); - } - // Otherwise, we compare the changes first as we expect there to be fewer. - return (isArrayEqual(this.docChanges, other.docChanges) && - isArrayEqual(this.docs, other.docs)); - } -} -exports.QuerySnapshot = QuerySnapshot; -/** - * A Query refers to a query which you can read or stream from. You can also - * construct refined Query objects by adding filters and ordering. - * - * @class Query - */ -class Query { - /** - * @private - * @hideconstructor - * - * @param {Firestore} firestore - The Firestore Database client. - * @param {ResourcePath} path Path of the collection to be queried. - * @param {Array.=} fieldOrders - Sequence of fields to - * control the order of results. - * @param {Array.=} fieldFilters - Sequence of fields - * constraining the results of the query. - * @param {object=} queryOptions Additional query options. - */ - constructor(firestore, path, fieldFilters, fieldOrders, queryOptions) { - this._firestore = firestore; - this._serializer = firestore._serializer; - this._validator = firestore._validator; - this._referencePath = path; - this._fieldFilters = fieldFilters || []; - this._fieldOrders = fieldOrders || []; - this._queryOptions = queryOptions || {}; - } - /** - * Detects the argument type for Firestore cursors. - * - * @private - * @param {Array.} fieldValuesOrDocumentSnapshot - A - * snapshot of the document or a set of field values. - * @returns {boolean} 'true' if the input is a single DocumentSnapshot.. - */ - static _isDocumentSnapshot(fieldValuesOrDocumentSnapshot) { - return (fieldValuesOrDocumentSnapshot.length === 1 && - is_1.default.instance(fieldValuesOrDocumentSnapshot[0], document_1.DocumentSnapshot)); - } - /** - * Extracts field values from the DocumentSnapshot based on the provided - * field order. - * - * @private - * @param {DocumentSnapshot} documentSnapshot - The document to extract the - * fields from. - * @param {Array.} fieldOrders - The field order that defines what - * fields we should extract. - * @return {Array.<*>} The field values to use. - * @private - */ - static _extractFieldValues(documentSnapshot, fieldOrders) { - let fieldValues = []; - for (let fieldOrder of fieldOrders) { - if (path_1.FieldPath._DOCUMENT_ID.isEqual(fieldOrder.field)) { - fieldValues.push(documentSnapshot.ref); - } - else { - let fieldValue = documentSnapshot.get(fieldOrder.field); - if (is_1.default.undefined(fieldValue)) { - throw new Error(`Field '${fieldOrder - .field}' is missing in the provided DocumentSnapshot. Please provide a ` + - 'document that contains values for all specified orderBy() and ' + - 'where() constraints.'); - } - else { - fieldValues.push(fieldValue); - } - } - } - return fieldValues; - } - /** - * The string representation of the Query's location. - * @private - * @type {string} - * @name Query#formattedName - */ - get formattedName() { - return this._referencePath.formattedName; - } - /** - * The [Firestore]{@link Firestore} instance for the Firestore - * database (useful for performing transactions, etc.). - * - * @type {Firestore} - * @name Query#firestore - * @readonly - * - * @example - * let collectionRef = firestore.collection('col'); - * - * collectionRef.add({foo: 'bar'}).then(documentReference => { - * let firestore = documentReference.firestore; - * console.log(`Root location for document is ${firestore.formattedName}`); - * }); - */ - get firestore() { - return this._firestore; - } - /** - * Creates and returns a new [Query]{@link Query} with the additional filter - * that documents must contain the specified field and that its value should - * satisfy the relation constraint provided. - * - * Returns a new Query that constrains the value of a Document property. - * - * This function returns a new (immutable) instance of the Query (rather than - * modify the existing instance) to impose the filter. - * - * @param {string|FieldPath} fieldPath - The name of a property - * value to compare. - * @param {string} opStr - A comparison operation in the form of a string - * (e.g., "<"). - * @param {*} value - The value to which to compare the field for inclusion in - * a query. - * @returns {Query} The created Query. - * - * @example - * let collectionRef = firestore.collection('col'); - * - * collectionRef.where('foo', '==', 'bar').get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - where(fieldPath, opStr, value) { - this._validator.isFieldPath('fieldPath', fieldPath); - this._validator.isQueryComparison('opStr', opStr, value); - this._validator.isQueryValue('value', value, { - allowDeletes: 'none', - allowTransforms: false, - }); - if (this._queryOptions.startAt || this._queryOptions.endAt) { - throw new Error('Cannot specify a where() filter after calling startAt(), ' + - 'startAfter(), endBefore() or endAt().'); - } - fieldPath = path_1.FieldPath.fromArgument(fieldPath); - if (path_1.FieldPath._DOCUMENT_ID.isEqual(fieldPath)) { - value = this._convertReference(value); - } - let combinedFilters = this._fieldFilters.concat(new FieldFilter(this._serializer, fieldPath, comparisonOperators[opStr], value)); - return new Query(this._firestore, this._referencePath, combinedFilters, this._fieldOrders, this._queryOptions); - } - /** - * Creates and returns a new [Query]{@link Query} instance that applies a - * field mask to the result and returns only the specified subset of fields. - * You can specify a list of field paths to return, or use an empty list to - * only return the references of matching documents. - * - * This function returns a new (immutable) instance of the Query (rather than - * modify the existing instance) to impose the field mask. - * - * @param {...(string|FieldPath)} fieldPaths - The field paths to - * return. - * @returns {Query} The created Query. - * - * @example - * let collectionRef = firestore.collection('col'); - * let documentRef = collectionRef.doc('doc'); - * - * return documentRef.set({x:10, y:5}).then(() => { - * return collectionRef.where('x', '>', 5).select('y').get(); - * }).then((res) => { - * console.log(`y is ${res.docs[0].get('y')}.`); - * }); - */ - select(fieldPaths) { - fieldPaths = [].slice.call(arguments); - let result = []; - if (fieldPaths.length === 0) { - result.push({ fieldPath: path_1.FieldPath._DOCUMENT_ID.formattedName }); - } - else { - for (let i = 0; i < fieldPaths.length; ++i) { - this._validator.isFieldPath(i, fieldPaths[i]); - result.push({ - fieldPath: path_1.FieldPath.fromArgument(fieldPaths[i]).formattedName, - }); - } - } - let options = extend_1.default(true, {}, this._queryOptions); - options.selectFields = { fields: result }; - return new Query(this._firestore, this._referencePath, this._fieldFilters, this._fieldOrders, options); - } - /** - * Creates and returns a new [Query]{@link Query} that's additionally sorted - * by the specified field, optionally in descending order instead of - * ascending. - * - * This function returns a new (immutable) instance of the Query (rather than - * modify the existing instance) to impose the field mask. - * - * @param {string|FieldPath} fieldPath - The field to sort by. - * @param {string=} directionStr - Optional direction to sort by ('asc' or - * 'desc'). If not specified, order will be ascending. - * @returns {Query} The created Query. - * - * @example - * let query = firestore.collection('col').where('foo', '>', 42); - * - * query.orderBy('foo', 'desc').get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - orderBy(fieldPath, directionStr) { - this._validator.isFieldPath('fieldPath', fieldPath); - this._validator.isOptionalFieldOrder('directionStr', directionStr); - if (this._queryOptions.startAt || this._queryOptions.endAt) { - throw new Error('Cannot specify an orderBy() constraint after calling ' + - 'startAt(), startAfter(), endBefore() or endAt().'); - } - let newOrder = new FieldOrder(path_1.FieldPath.fromArgument(fieldPath), directionOperators[directionStr]); - let combinedOrders = this._fieldOrders.concat(newOrder); - return new Query(this._firestore, this._referencePath, this._fieldFilters, combinedOrders, this._queryOptions); - } - /** - * Creates and returns a new [Query]{@link Query} that's additionally limited - * to only return up to the specified number of documents. - * - * This function returns a new (immutable) instance of the Query (rather than - * modify the existing instance) to impose the limit. - * - * @param {number} limit - The maximum number of items to return. - * @returns {Query} The created Query. - * - * @example - * let query = firestore.collection('col').where('foo', '>', 42); - * - * query.limit(1).get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - limit(limit) { - this._validator.isInteger('limit', limit); - let options = extend_1.default(true, {}, this._queryOptions); - options.limit = limit; - return new Query(this._firestore, this._referencePath, this._fieldFilters, this._fieldOrders, options); - } - /** - * Specifies the offset of the returned results. - * - * This function returns a new (immutable) instance of the - * [Query]{@link Query} (rather than modify the existing instance) - * to impose the offset. - * - * @param {number} offset - The offset to apply to the Query results - * @returns {Query} The created Query. - * - * @example - * let query = firestore.collection('col').where('foo', '>', 42); - * - * query.limit(10).offset(20).get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - offset(offset) { - this._validator.isInteger('offset', offset); - let options = extend_1.default(true, {}, this._queryOptions); - options.offset = offset; - return new Query(this._firestore, this._referencePath, this._fieldFilters, this._fieldOrders, options); - } - /** - * Returns true if this `Query` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `Query` is equal to the provided value. - */ - isEqual(other) { - if (this === other) { - return true; - } - return (is_1.default.instanceof(other, Query) && - this._referencePath.isEqual(other._referencePath) && - deep_equal_1.default(this._fieldFilters, other._fieldFilters, { strict: true }) && - deep_equal_1.default(this._fieldOrders, other._fieldOrders, { strict: true }) && - deep_equal_1.default(this._queryOptions, other._queryOptions, { strict: true })); - } - /** - * Computes the backend ordering semantics for DocumentSnapshot cursors. - * - * @private - * @param {Array.} cursorValuesOrDocumentSnapshot - The - * snapshot of the document or the set of field values to use as the boundary. - * @returns {Array.} The implicit ordering semantics. - */ - _createImplicitOrderBy(cursorValuesOrDocumentSnapshot) { - if (!Query._isDocumentSnapshot(cursorValuesOrDocumentSnapshot)) { - return this._fieldOrders; - } - let fieldOrders = this._fieldOrders.slice(); - let hasDocumentId = false; - if (fieldOrders.length === 0) { - // If no explicit ordering is specified, use the first inequality to - // define an implicit order. - for (let fieldFilter of this._fieldFilters) { - if (fieldFilter.isInequalityFilter()) { - fieldOrders.push(new FieldOrder(fieldFilter.field, 'ASCENDING')); - break; - } - } - } - else { - for (let fieldOrder of fieldOrders) { - if (path_1.FieldPath._DOCUMENT_ID.isEqual(fieldOrder.field)) { - hasDocumentId = true; - } - } - } - if (!hasDocumentId) { - // Add implicit sorting by name, using the last specified direction. - let lastDirection = fieldOrders.length === 0 ? - directionOperators.ASC : - fieldOrders[fieldOrders.length - 1].direction; - fieldOrders.push(new FieldOrder(path_1.FieldPath.documentId(), lastDirection)); - } - return fieldOrders; - } - /** - * Builds a Firestore 'Position' proto message. - * - * @private - * @param {Array.} fieldOrders - The field orders to use for this - * cursor. - * @param {Array.} cursorValuesOrDocumentSnapshot - The - * snapshot of the document or the set of field values to use as the - * boundary. - * @param before - Whether the query boundary lies just before or after the - * provided data. - * @returns {Object} The proto message. - */ - _createCursor(fieldOrders, cursorValuesOrDocumentSnapshot, before) { - let fieldValues; - if (Query._isDocumentSnapshot(cursorValuesOrDocumentSnapshot)) { - fieldValues = Query._extractFieldValues(cursorValuesOrDocumentSnapshot[0], fieldOrders); - } - else { - fieldValues = cursorValuesOrDocumentSnapshot; - } - if (fieldValues.length > fieldOrders.length) { - throw new Error('Too many cursor values specified. The specified ' + - 'values must match the orderBy() constraints of the query.'); - } - let options = { - values: [], - }; - if (before) { - options.before = true; - } - for (let i = 0; i < fieldValues.length; ++i) { - let fieldValue = fieldValues[i]; - if (path_1.FieldPath._DOCUMENT_ID.isEqual(fieldOrders[i].field)) { - fieldValue = this._convertReference(fieldValue); - } - this._validator.isQueryValue(i, fieldValue, { - allowDeletes: 'none', - allowTransforms: false, - }); - options.values.push(this._serializer.encodeValue(fieldValue)); - } - return options; - } - /** - * Validates that a value used with FieldValue.documentId() is either a - * string or a DocumentReference that is part of the query`s result set. - * Throws a validation error or returns a DocumentReference that can - * directly be used in the Query. - * - * @param {*} reference - The value to validate. - * @throws If the value cannot be used for this query. - * @return {DocumentReference} If valid, returns a DocumentReference that - * can be used with the query. - * @private - */ - _convertReference(reference) { - if (is_1.default.string(reference)) { - reference = new DocumentReference(this._firestore, this._referencePath.append(reference)); - } - else if (is_1.default.instance(reference, DocumentReference)) { - if (!this._referencePath.isPrefixOf(reference.ref)) { - throw new Error(`'${reference.path}' is not part of the query result set and ` + - 'cannot be used as a query boundary.'); - } - } - else { - throw new Error('The corresponding value for FieldPath.documentId() must be a ' + - 'string or a DocumentReference.'); - } - if (reference.ref.parent().compareTo(this._referencePath) !== 0) { - throw new Error('Only a direct child can be used as a query boundary. ' + - `Found: '${reference.path}'.`); - } - return reference; - } - /** - * Creates and returns a new [Query]{@link Query} that starts at the provided - * set of field values relative to the order of the query. The order of the - * provided values must match the order of the order by clauses of the query. - * - * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot - The snapshot - * of the document the query results should start at or the field values to - * start this query at, in order of the query's order by. - * @returns {Query} A query with the new starting point. - * - * @example - * let query = firestore.collection('col'); - * - * query.orderBy('foo').startAt(42).get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - startAt(fieldValuesOrDocumentSnapshot) { - let options = extend_1.default(true, {}, this._queryOptions); - fieldValuesOrDocumentSnapshot = [].slice.call(arguments); - let fieldOrders = this._createImplicitOrderBy(fieldValuesOrDocumentSnapshot); - options.startAt = - this._createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, true); - return new Query(this._firestore, this._referencePath, this._fieldFilters, fieldOrders, options); - } - /** - * Creates and returns a new [Query]{@link Query} that starts after the - * provided set of field values relative to the order of the query. The order - * of the provided values must match the order of the order by clauses of the - * query. - * - * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot - The snapshot - * of the document the query results should start after or the field values to - * start this query after, in order of the query's order by. - * @returns {Query} A query with the new starting point. - * - * @example - * let query = firestore.collection('col'); - * - * query.orderBy('foo').startAfter(42).get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - startAfter(fieldValuesOrDocumentSnapshot) { - let options = extend_1.default(true, {}, this._queryOptions); - fieldValuesOrDocumentSnapshot = [].slice.call(arguments); - let fieldOrders = this._createImplicitOrderBy(fieldValuesOrDocumentSnapshot); - options.startAt = - this._createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, false); - return new Query(this._firestore, this._referencePath, this._fieldFilters, fieldOrders, options); - } - /** - * Creates and returns a new [Query]{@link Query} that ends before the set of - * field values relative to the order of the query. The order of the provided - * values must match the order of the order by clauses of the query. - * - * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot - The snapshot - * of the document the query results should end before or the field values to - * end this query before, in order of the query's order by. - * @returns {Query} A query with the new ending point. - * - * @example - * let query = firestore.collection('col'); - * - * query.orderBy('foo').endBefore(42).get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - endBefore(fieldValuesOrDocumentSnapshot) { - let options = extend_1.default(true, {}, this._queryOptions); - fieldValuesOrDocumentSnapshot = [].slice.call(arguments); - let fieldOrders = this._createImplicitOrderBy(fieldValuesOrDocumentSnapshot); - options.endAt = - this._createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, true); - return new Query(this._firestore, this._referencePath, this._fieldFilters, fieldOrders, options); - } - /** - * Creates and returns a new [Query]{@link Query} that ends at the provided - * set of field values relative to the order of the query. The order of the - * provided values must match the order of the order by clauses of the query. - * - * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot - The snapshot - * of the document the query results should end at or the field values to end - * this query at, in order of the query's order by. - * @returns {Query} A query with the new ending point. - * - * @example - * let query = firestore.collection('col'); - * - * query.orderBy('foo').endAt(42).get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - endAt(fieldValuesOrDocumentSnapshot) { - let options = extend_1.default(true, {}, this._queryOptions); - fieldValuesOrDocumentSnapshot = [].slice.call(arguments); - let fieldOrders = this._createImplicitOrderBy(fieldValuesOrDocumentSnapshot); - options.endAt = - this._createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, false); - return new Query(this._firestore, this._referencePath, this._fieldFilters, fieldOrders, options); - } - /** - * Executes the query and returns the results as a - * [QuerySnapshot]{@link QuerySnapshot}. - * - * @returns {Promise.} A Promise that resolves with the results - * of the Query. - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * query.get().then(querySnapshot => { - * querySnapshot.forEach(documentSnapshot => { - * console.log(`Found document at ${documentSnapshot.ref.path}`); - * }); - * }); - */ - get() { - return this._get(); - } - /** - * Internal get() method that accepts an optional transaction id. - * - * @private - * @param {bytes=} queryOptions.transactionId - A transaction ID. - */ - _get(queryOptions) { - let self = this; - let docs = []; - return new Promise((resolve, reject) => { - let readTime; - self._stream(queryOptions) - .on('error', err => { - reject(err); - }) - .on('data', result => { - readTime = result.readTime; - if (result.document) { - let document = result.document; - docs.push(document); - } - }) - .on('end', () => { - resolve(new QuerySnapshot(this, readTime, docs.length, () => docs, () => { - let changes = []; - for (let i = 0; i < docs.length; ++i) { - changes.push(new document_change_1.DocumentChange(document_change_1.DocumentChange.ADDED, docs[i], -1, i)); - } - return changes; - })); - }); - }); - } - /** - * Executes the query and streams the results as - * [QueryDocumentSnapshots]{@link QueryDocumentSnapshot}. - * - * @returns {Stream.} A stream of - * QueryDocumentSnapshots. - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * let count = 0; - * - * query.stream().on('data', (documentSnapshot) => { - * console.log(`Found document with name '${documentSnapshot.id}'`); - * ++count; - * }).on('end', () => { - * console.log(`Total count is ${count}`); - * }); - */ - stream() { - let responseStream = this._stream(); - let transform = through2_1.default.obj(function (chunk, encoding, callback) { - // Only send chunks with documents. - if (chunk.document) { - this.push(chunk.document); - } - callback(); - }); - return bun_1.default([responseStream, transform]); - } - /** - * Internal method for serializing a query to its RunQuery proto - * representation with an optional transaction id. - * - * @param {bytes=} queryOptions.transactionId - A transaction ID. - * @private - * @returns Serialized JSON for the query. - */ - toProto(queryOptions) { - let reqOpts = { - parent: this._referencePath.parent().formattedName, - structuredQuery: { - from: [ - { - collectionId: this._referencePath.id, - }, - ], - }, - }; - let structuredQuery = reqOpts.structuredQuery; - if (this._fieldFilters.length === 1) { - structuredQuery.where = this._fieldFilters[0].toProto(); - } - else if (this._fieldFilters.length > 1) { - let filters = []; - for (let fieldFilter of this._fieldFilters) { - filters.push(fieldFilter.toProto()); - } - structuredQuery.where = { - compositeFilter: { - op: 'AND', - filters: filters, - }, - }; - } - if (this._fieldOrders.length) { - let orderBy = []; - for (let fieldOrder of this._fieldOrders) { - orderBy.push(fieldOrder.toProto()); - } - structuredQuery.orderBy = orderBy; - } - if (this._queryOptions.limit) { - structuredQuery.limit = { value: this._queryOptions.limit }; - } - if (this._queryOptions.offset) { - structuredQuery.offset = this._queryOptions.offset; - } - if (this._queryOptions.startAt) { - structuredQuery.startAt = this._queryOptions.startAt; - } - if (this._queryOptions.endAt) { - structuredQuery.endAt = this._queryOptions.endAt; - } - if (this._queryOptions.selectFields) { - structuredQuery.select = this._queryOptions.selectFields; - } - if (queryOptions && queryOptions.transactionId) { - reqOpts.transaction = queryOptions.transactionId; - } - return reqOpts; - } - /** - * Internal streaming method that accepts an optional transaction id. - * - * @param {bytes=} queryOptions.transactionId - A transaction ID. - * @private - * @returns {stream} A stream of document results. - */ - _stream(queryOptions) { - const request = this.toProto(queryOptions); - const tag = util_1.requestTag(); - const self = this; - const stream = through2_1.default.obj(function (proto, enc, callback) { - const readTime = timestamp_1.Timestamp.fromProto(proto.readTime); - if (proto.document) { - let document = self.firestore.snapshot_(proto.document, proto.readTime); - this.push({ document, readTime }); - } - else { - this.push({ readTime }); - } - callback(); - }); - this._firestore.readStream('runQuery', request, tag, true) - .then(backendStream => { - backendStream.on('error', err => { - logger_1.logger('Query._stream', tag, 'Query failed with stream error:', err); - stream.destroy(err); - }); - backendStream.resume(); - backendStream.pipe(stream); - }) - .catch(err => { - stream.destroy(err); - }); - return stream; - } - /** - * Attaches a listener for QuerySnapshot events. - * - * @param {querySnapshotCallback} onNext - A callback to be called every time - * a new [QuerySnapshot]{@link QuerySnapshot} is available. - * @param {errorCallback=} onError - A callback to be called if the listen - * fails or is cancelled. No further callbacks will occur. - * - * @returns {function()} An unsubscribe function that can be called to cancel - * the snapshot listener. - * - * @example - * let query = firestore.collection('col').where('foo', '==', 'bar'); - * - * let unsubscribe = query.onSnapshot(querySnapshot => { - * console.log(`Received query snapshot of size ${querySnapshot.size}`); - * }, err => { - * console.log(`Encountered error: ${err}`); - * }); - * - * // Remove this listener. - * unsubscribe(); - */ - onSnapshot(onNext, onError) { - this._validator.isFunction('onNext', onNext); - this._validator.isOptionalFunction('onError', onError); - if (!is_1.default.defined(onError)) { - onError = console.error; - } - let watch = watch_1.Watch.forQuery(this); - return watch.onSnapshot((readTime, size, docs, changes) => { - onNext(new QuerySnapshot(this, readTime, size, docs, changes)); - }, onError); - } - /** - * Returns a function that can be used to sort QueryDocumentSnapshots - * according to the sort criteria of this query. - * - * @private - */ - comparator() { - return (doc1, doc2) => { - // Add implicit sorting by name, using the last specified direction. - let lastDirection = this._fieldOrders.length === 0 ? - directionOperators.ASC : - this._fieldOrders[this._fieldOrders.length - 1].direction; - let orderBys = this._fieldOrders.concat(new FieldOrder(path_1.FieldPath._DOCUMENT_ID, lastDirection)); - for (let orderBy of orderBys) { - let comp; - if (path_1.FieldPath._DOCUMENT_ID.isEqual(orderBy.field)) { - comp = doc1.ref._referencePath.compareTo(doc2.ref._referencePath); - } - else { - const v1 = doc1.protoField(orderBy.field); - const v2 = doc2.protoField(orderBy.field); - if (!is_1.default.defined(v1) || !is_1.default.defined(v2)) { - throw new Error('Trying to compare documents on fields that ' + - 'don\'t exist. Please include the fields you are ordering on ' + - 'in your select() call.'); - } - comp = order_1.compare(v1, v2); - } - if (comp !== 0) { - const direction = orderBy.direction === directionOperators.ASC ? 1 : -1; - return direction * comp; - } - } - return 0; - }; - } -} -exports.Query = Query; -/** - * A CollectionReference object can be used for adding documents, getting - * document references, and querying for documents (using the methods - * inherited from [Query]{@link Query}). - * - * @class - * @extends Query - */ -class CollectionReference extends Query { - /** - * @private - * @hideconstructor - * - * @param {Firestore} firestore - The Firestore Database client. - * @param {ResourcePath} path - The Path of this collection. - */ - constructor(firestore, path) { - super(firestore, path); - } - /** - * The last path element of the referenced collection. - * - * @type {string} - * @name CollectionReference#id - * @readonly - * - * @example - * let collectionRef = firestore.collection('col/doc/subcollection'); - * console.log(`ID of the subcollection: ${collectionRef.id}`); - */ - get id() { - return this._referencePath.id; - } - /** - * A reference to the containing Document if this is a subcollection, else - * null. - * - * @type {DocumentReference} - * @name CollectionReference#parent - * @readonly - * - * @example - * let collectionRef = firestore.collection('col/doc/subcollection'); - * let documentRef = collectionRef.parent; - * console.log(`Parent name: ${documentRef.path}`); - */ - get parent() { - return new DocumentReference(this._firestore, this._referencePath.parent()); - } - /** - * A string representing the path of the referenced collection (relative - * to the root of the database). - * - * @type {string} - * @name CollectionReference#path - * @readonly - * - * @example - * let collectionRef = firestore.collection('col/doc/subcollection'); - * console.log(`Path of the subcollection: ${collectionRef.path}`); - */ - get path() { - return this._referencePath.relativeName; - } - /** - * Gets a [DocumentReference]{@link DocumentReference} instance that - * refers to the document at the specified path. If no path is specified, an - * automatically-generated unique ID will be used for the returned - * DocumentReference. - * - * @param {string=} documentPath - A slash-separated path to a document. - * @returns {DocumentReference} The `DocumentReference` - * instance. - * - * @example - * let collectionRef = firestore.collection('col'); - * let documentRefWithName = collectionRef.doc('doc'); - * let documentRefWithAutoId = collectionRef.doc(); - * console.log(`Reference with name: ${documentRefWithName.path}`); - * console.log(`Reference with auto-id: ${documentRefWithAutoId.path}`); - */ - doc(documentPath) { - if (arguments.length === 0) { - documentPath = util_1.autoId(); - } - else { - this._validator.isResourcePath('documentPath', documentPath); - } - let path = this._referencePath.append(documentPath); - if (!path.isDocument) { - throw new Error(`Argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`); - } - return new DocumentReference(this._firestore, path); - } - /** - * Add a new document to this collection with the specified data, assigning - * it a document ID automatically. - * - * @param {DocumentData} data - An Object containing the data for the new - * document. - * @returns {Promise.} A Promise resolved with a - * [DocumentReference]{@link DocumentReference} pointing to the - * newly created document. - * - * @example - * let collectionRef = firestore.collection('col'); - * collectionRef.add({foo: 'bar'}).then(documentReference => { - * console.log(`Added document with name: ${documentReference.id}`); - * }); - */ - add(data) { - this._validator.isDocument('data', data, { - allowEmpty: true, - allowDeletes: 'none', - allowTransforms: true, - }); - let documentRef = this.doc(); - return documentRef.create(data).then(() => { - return Promise.resolve(documentRef); - }); - } - /** - * Returns true if this `CollectionReference` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `CollectionReference` is equal to the - * provided value. - */ - isEqual(other) { - return (this === other || - (is_1.default.instanceof(other, CollectionReference) && super.isEqual(other))); - } -} -exports.CollectionReference = CollectionReference; -/*! - * Creates a new CollectionReference. Invoked by DocumentReference to avoid - * invalid declaration order. - * - * @param {Firestore} firestore - The Firestore Database client. - * @param {ResourcePath} path - The path of this collection. - * @returns {CollectionReference} - */ -function createCollectionReference(firestore, path) { - return new CollectionReference(firestore, path); -} -/*! - * Validates the input string as a field order direction. - * - * @param {string=} str Order direction to validate. - * @throws {Error} when the direction is invalid - */ -function validateFieldOrder(str) { - if (!is_1.default.string(str) || !is_1.default.defined(directionOperators[str])) { - throw new Error('Order must be one of "asc" or "desc".'); - } - return true; -} -exports.validateFieldOrder = validateFieldOrder; -/*! - * Validates the input string as a field comparison operator. - * - * @param {string} str Field comparison operator to validate. - * @param {*} val Value that is used in the filter. - * @throws {Error} when the comparison operation is invalid - */ -function validateComparisonOperator(str, val) { - if (is_1.default.string(str) && comparisonOperators[str]) { - let op = comparisonOperators[str]; - if (typeof val === 'number' && isNaN(val) && op !== 'EQUAL') { - throw new Error('Invalid query. You can only perform equals comparisons on NaN.'); - } - if (val === null && op !== 'EQUAL') { - throw new Error('Invalid query. You can only perform equals comparisons on Null.'); - } - return true; - } - throw new Error('Operator must be one of "<", "<=", "==", ">", or ">=".'); -} -exports.validateComparisonOperator = validateComparisonOperator; -/*! - * Validates that 'value' is a DocumentReference. - * - * @param {*} value The argument to validate. - * @returns 'true' is value is an instance of DocumentReference. - */ -function validateDocumentReference(value) { - if (is_1.default.instanceof(value, DocumentReference)) { - return true; - } - throw validate_1.customObjectError(value); -} -exports.validateDocumentReference = validateDocumentReference; -/** - * Verifies euqality for an array of objects using the `isEqual` interface. - * - * @private - * @param {Array.} left Array of objects supporting `isEqual`. - * @param {Array.} right Array of objects supporting `isEqual`. - * @return {boolean} True if arrays are equal. - */ -function isArrayEqual(left, right) { - if (left.length !== right.length) { - return false; - } - for (let i = 0; i < left.length; ++i) { - if (!left[i].isEqual(right[i])) { - return false; - } - } - return true; -} diff --git a/functions/node_modules/@google-cloud/firestore/build/src/serializer.js b/functions/node_modules/@google-cloud/firestore/build/src/serializer.js deleted file mode 100644 index d4942477..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/serializer.js +++ /dev/null @@ -1,228 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __importDefault(require("is")); -const firestore_proto_api_1 = require("../protos/firestore_proto_api"); -const timestamp_1 = require("./timestamp"); -const field_value_1 = require("./field-value"); -const validate_1 = require("./validate"); -const path_1 = require("./path"); -const convert_1 = require("./convert"); -const geo_point_1 = require("./geo-point"); -/** - * Serializer that is used to convert between JavaScripts types and their - * Firestore Protobuf representation. - * - * @private - */ -class Serializer { - constructor(firestore, timestampsInSnapshotsEnabled) { - this.timestampsInSnapshotsEnabled = timestampsInSnapshotsEnabled; - // Instead of storing the `firestore` object, we store just a reference to - // its `.doc()` method. This avoid a circular reference, which breaks - // JSON.stringify(). - this.createReference = path => firestore.doc(path); - } - /** - * Encodes a JavaScrip object into the Firestore 'Fields' representation. - * - * @private - * @param obj The object to encode. - * @returns The Firestore 'Fields' representation - */ - encodeFields(obj) { - const fields = {}; - for (const prop in obj) { - if (obj.hasOwnProperty(prop)) { - const val = this.encodeValue(obj[prop]); - if (val) { - fields[prop] = val; - } - } - } - return fields; - } - /** - * Encodes a JavaScript value into the Firestore 'Value' representation. - * - * @private - * @param val The object to encode - * @returns The Firestore Proto or null if we are deleting a field. - */ - encodeValue(val) { - if (val instanceof field_value_1.FieldTransform) { - return null; - } - if (is_1.default.string(val)) { - return { - stringValue: val, - }; - } - if (is_1.default.bool(val)) { - return { - booleanValue: val, - }; - } - if (is_1.default.integer(val)) { - return { - integerValue: val, - }; - } - // Integers are handled above, the remaining numbers are treated as doubles - if (is_1.default.number(val)) { - return { - doubleValue: val, - }; - } - if (is_1.default.date(val)) { - const timestamp = timestamp_1.Timestamp.fromDate(val); - return { - timestampValue: { - seconds: timestamp.seconds, - nanos: timestamp.nanoseconds, - }, - }; - } - if (val === null) { - return { - nullValue: firestore_proto_api_1.google.protobuf.NullValue.NULL_VALUE, - }; - } - if (val instanceof Buffer || val instanceof Uint8Array) { - return { - bytesValue: val, - }; - } - if (typeof val === 'object' && 'toProto' in val && - typeof val.toProto === 'function') { - return val.toProto(); - } - if (val instanceof Array) { - const array = { - arrayValue: {}, - }; - if (val.length > 0) { - array.arrayValue.values = []; - for (let i = 0; i < val.length; ++i) { - const enc = this.encodeValue(val[i]); - if (enc) { - array.arrayValue.values.push(enc); - } - } - } - return array; - } - if (typeof val === 'object' && isPlainObject(val)) { - const map = { - mapValue: {}, - }; - // If we encounter an empty object, we always need to send it to make sure - // the server creates a map entry. - if (!is_1.default.empty(val)) { - map.mapValue.fields = this.encodeFields(val); - if (is_1.default.empty(map.mapValue.fields)) { - return null; - } - } - return map; - } - throw validate_1.customObjectError(val); - } - /** - * Decodes a single Firestore 'Value' Protobuf. - * - * @private - * @param proto - A Firestore 'Value' Protobuf. - * @returns The converted JS type. - */ - decodeValue(proto) { - const valueType = convert_1.detectValueType(proto); - switch (valueType) { - case 'stringValue': { - return proto.stringValue; - } - case 'booleanValue': { - return proto.booleanValue; - } - case 'integerValue': { - return Number(proto.integerValue); - } - case 'doubleValue': { - return Number(proto.doubleValue); - } - case 'timestampValue': { - const timestamp = timestamp_1.Timestamp.fromProto(proto.timestampValue); - return this.timestampsInSnapshotsEnabled ? timestamp : - timestamp.toDate(); - } - case 'referenceValue': { - const resourcePath = path_1.ResourcePath.fromSlashSeparatedString(proto.referenceValue); - return this.createReference(resourcePath.relativeName); - } - case 'arrayValue': { - const array = []; - if (is_1.default.array(proto.arrayValue.values)) { - for (const value of proto.arrayValue.values) { - array.push(this.decodeValue(value)); - } - } - return array; - } - case 'nullValue': { - return null; - } - case 'mapValue': { - const obj = {}; - const fields = proto.mapValue.fields; - for (const prop in fields) { - if (fields.hasOwnProperty(prop)) { - obj[prop] = this.decodeValue(fields[prop]); - } - } - return obj; - } - case 'geoPointValue': { - return geo_point_1.GeoPoint.fromProto(proto.geoPointValue); - } - case 'bytesValue': { - return proto.bytesValue; - } - default: { - throw new Error('Cannot decode type from Firestore Value: ' + - JSON.stringify(proto)); - } - } - } -} -exports.Serializer = Serializer; -/** - * Verifies that 'obj' is a plain JavaScript object that can be encoded as a - * 'Map' in Firestore. - * - * @private - * @param input - The argument to verify. - * @returns 'true' if the input can be a treated as a plain object. - */ -function isPlainObject(input) { - return (typeof input === 'object' && input !== null && - (Object.getPrototypeOf(input) === Object.prototype || - Object.getPrototypeOf(input) === null)); -} -exports.isPlainObject = isPlainObject; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/timestamp.js b/functions/node_modules/@google-cloud/firestore/build/src/timestamp.js deleted file mode 100644 index 32cd7ab3..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/timestamp.js +++ /dev/null @@ -1,225 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __importDefault(require("is")); -const validate_1 = require("./validate"); -const validate = validate_1.createValidator(); -/*! - * Number of nanoseconds in a millisecond. - * - * @type {number} - */ -const MS_TO_NANOS = 1000000; -/** - * A Timestamp represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian - * Calendar which extends the Gregorian calendar backwards to year one. It is - * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are - * "smeared" so that no leap second table is needed for interpretation. Range is - * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * - * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto - */ -class Timestamp { - /** - * Creates a new timestamp with the current date, with millisecond precision. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({ updateTime:Firestore.Timestamp.now() }); - * - * @return {Timestamp} A new `Timestamp` representing the current date. - */ - static now() { - return Timestamp.fromMillis(Date.now()); - } - /** - * Creates a new timestamp from the given date. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * let date = Date.parse('01 Jan 2000 00:00:00 GMT'); - * documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) }); - * - * @param {Date} date The date to initialize the `Timestamp` from. - * @return {Timestamp} A new `Timestamp` representing the same point in time - * as the given date. - */ - static fromDate(date) { - return Timestamp.fromMillis(date.getTime()); - } - /** - * Creates a new timestamp from the given number of milliseconds. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) }); - * - * @param {number} milliseconds Number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - * @return {Timestamp} A new `Timestamp` representing the same point in time - * as the given number of milliseconds. - */ - static fromMillis(milliseconds) { - const seconds = Math.floor(milliseconds / 1000); - const nanos = (milliseconds - seconds * 1000) * MS_TO_NANOS; - return new Timestamp(seconds, nanos); - } - /** - * Generates a `Timestamp` object from a Timestamp proto. - * - * @private - * @param {Object} timestamp The `Timestamp` Protobuf object. - */ - static fromProto(timestamp) { - return new Timestamp(Number(timestamp.seconds || 0), Number(timestamp.nanos || 0)); - } - /** - * Creates a new timestamp. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({ startTime:new Firestore.Timestamp(42, 0) }); - * - * @param {number} seconds The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * @param {number} nanoseconds The non-negative fractions of a second at - * nanosecond resolution. Negative second values with fractions must still - * have non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive. - */ - constructor(seconds, nanoseconds) { - validate.isInteger('seconds', seconds); - validate.isInteger('nanoseconds', nanoseconds, 0, 999999999); - this._seconds = seconds; - this._nanoseconds = nanoseconds; - } - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(snap => { - * let updatedAt = snap.updateTime; - * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); - * }); - * - * @type {number} - */ - get seconds() { - return this._seconds; - } - /** - * The non-negative fractions of a second at nanosecond resolution. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(snap => { - * let updated = snap.updateTime; - * console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`); - * }); - * - * @type {number} - */ - get nanoseconds() { - return this._nanoseconds; - } - /** - * Returns a new `Date` corresponding to this timestamp. This may lose - * precision. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(snap => { - * console.log(`Document updated at: ${snap.updateTime.toDate()}`); - * }); - * - * @return {Date} JavaScript `Date` object representing the same point in time - * as this `Timestamp`, with millisecond precision. - */ - toDate() { - return new Date(this._seconds * 1000 + Math.round(this._nanoseconds / MS_TO_NANOS)); - } - /** - * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(snap => { - * let startTime = snap.get('startTime'); - * let endTime = snap.get('endTime'); - * console.log(`Duration: ${endTime - startTime}`); - * }); - * - * @return {number} The point in time corresponding to this timestamp, - * represented as the number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - */ - toMillis() { - return this._seconds * 1000 + Math.floor(this._nanoseconds / MS_TO_NANOS); - } - /** - * Returns 'true' if this `Timestamp` is equal to the provided one. - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(snap => { - * if (snap.createTime.isEqual(snap.updateTime)) { - * console.log('Document is in its initial state.'); - * } - * }); - * - * @param {any} other The `Timestamp` to compare against. - * @return {boolean} 'true' if this `Timestamp` is equal to the provided one. - */ - isEqual(other) { - return (this === other || - (is_1.default.instanceof(other, Timestamp) && this._seconds === other.seconds && - this._nanoseconds === other.nanoseconds)); - } - /** - * Generates the Protobuf `Timestamp` object for this timestamp. - * - * @private - * @returns {Object} The `Timestamp` Protobuf object. - */ - toProto() { - const timestamp = {}; - if (this.seconds) { - timestamp.seconds = this.seconds; - } - if (this.nanoseconds) { - timestamp.nanos = this.nanoseconds; - } - return { timestampValue: timestamp }; - } -} -exports.Timestamp = Timestamp; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/transaction.js b/functions/node_modules/@google-cloud/firestore/build/src/transaction.js deleted file mode 100644 index 6e5cd8f9..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/transaction.js +++ /dev/null @@ -1,311 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is_1 = __importDefault(require("is")); -const reference_1 = require("./reference"); -const util_1 = require("./util"); -/*! - * Error message for transactional reads that were executed after performing - * writes. - */ -const READ_AFTER_WRITE_ERROR_MSG = 'Firestore transactions require all reads to be executed before all writes.'; -/*! - * Transactions can be retried if the initial stream opening errors out. - */ -const ALLOW_RETRIES = true; -/** - * A reference to a transaction. - * - * The Transaction object passed to a transaction's updateFunction provides - * the methods to read and write data within the transaction context. See - * [runTransaction()]{@link Firestore#runTransaction}. - * - * @class - */ -class Transaction { - /** - * @private - * @hideconstructor - * - * @param {Firestore} firestore - The Firestore Database client. - * @param {Transaction=} previousTransaction - If - * available, the failed transaction that is being retried. - */ - constructor(firestore, previousTransaction) { - this._firestore = firestore; - this._validator = firestore._validator; - this._previousTransaction = previousTransaction; - this._writeBatch = firestore.batch(); - this._requestTag = - previousTransaction ? previousTransaction.requestTag : util_1.requestTag(); - } - /** - * Retrieve a document or a query result from the database. Holds a - * pessimistic lock on all returned documents. - * - * @param {DocumentReference|Query} refOrQuery - The - * document or query to return. - * @returns {Promise} A Promise that resolves with a DocumentSnapshot or - * QuerySnapshot for the returned documents. - * - * @example - * firestore.runTransaction(transaction => { - * let documentRef = firestore.doc('col/doc'); - * return transaction.get(documentRef).then(doc => { - * if (doc.exists) { - * transaction.update(documentRef, { count: doc.get('count') + 1 }); - * } else { - * transaction.create(documentRef, { count: 1 }); - * } - * }); - * }); - */ - get(refOrQuery) { - if (!this._writeBatch.isEmpty) { - throw new Error(READ_AFTER_WRITE_ERROR_MSG); - } - if (is_1.default.instance(refOrQuery, reference_1.DocumentReference)) { - return this._firestore - .getAll_([refOrQuery], this._requestTag, this._transactionId) - .then(res => { - return Promise.resolve(res[0]); - }); - } - if (is_1.default.instance(refOrQuery, reference_1.Query)) { - return refOrQuery._get({ transactionId: this._transactionId }); - } - throw new Error('Argument "refOrQuery" must be a DocumentRef or a Query.'); - } - /** - * Retrieves multiple documents from Firestore. Holds a pessimistic lock on - * all returned documents. - * - * @param {...DocumentReference} documents - The document references - * to receive. - * @returns {Promise>} A Promise that - * contains an array with the resulting document snapshots. - * - * @example - * let firstDoc = firestore.doc('col/doc1'); - * let secondDoc = firestore.doc('col/doc2'); - * let resultDoc = firestore.doc('col/doc3'); - * - * firestore.runTransaction(transaction => { - * return transaction.getAll(firstDoc, secondDoc).then(docs => { - * transaction.set(resultDoc, { - * sum: docs[1].get('count') + docs[2].get('count') - * }); - * }); - * }); - */ - getAll(documents) { - if (!this._writeBatch.isEmpty) { - throw new Error(READ_AFTER_WRITE_ERROR_MSG); - } - documents = is_1.default.array(arguments[0]) ? arguments[0].slice() : - Array.prototype.slice.call(arguments); - for (let i = 0; i < documents.length; ++i) { - this._validator.isDocumentReference(i, documents[i]); - } - return this._firestore.getAll_(documents, this._requestTag, this._transactionId); - } - /** - * Create the document referred to by the provided - * [DocumentReference]{@link DocumentReference}. The operation will - * fail the transaction if a document exists at the specified location. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be created. - * @param {DocumentData} data - The object data to serialize as the document. - * @returns {Transaction} This Transaction instance. Used for - * chaining method calls. - * - * @example - * firestore.runTransaction(transaction => { - * let documentRef = firestore.doc('col/doc'); - * return transaction.get(documentRef).then(doc => { - * if (!doc.exists) { - * transaction.create(documentRef, { foo: 'bar' }); - * } - * }); - * }); - */ - create(documentRef, data) { - this._writeBatch.create(documentRef, data); - return this; - } - /** - * Writes to the document referred to by the provided - * [DocumentReference]{@link DocumentReference}. If the document - * does not exist yet, it will be created. If you pass - * [SetOptions]{@link SetOptions}, the provided data can be merged into the - * existing document. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be set. - * @param {DocumentData} data - The object to serialize as the document. - * @param {SetOptions=} options - An object to configure the set behavior. - * @param {boolean=} options.merge - If true, set() merges the values - * specified in its data argument. Fields omitted from this set() call - * remain untouched. - * @param {Array.=} options.mergeFields - If provided, - * set() only replaces the specified field paths. Any field path that is not - * specified is ignored and remains untouched. - * @returns {Transaction} This Transaction instance. Used for - * chaining method calls. - * - * @example - * firestore.runTransaction(transaction => { - * let documentRef = firestore.doc('col/doc'); - * transaction.set(documentRef, { foo: 'bar' }); - * return Promise.resolve(); - * }); - */ - set(documentRef, data, options) { - this._writeBatch.set(documentRef, data, options); - return this; - } - /** - * Updates fields in the document referred to by the provided - * [DocumentReference]{@link DocumentReference}. The update will - * fail if applied to a document that does not exist. - * - * The update() method accepts either an object with field paths encoded as - * keys and field values encoded as values, or a variable number of arguments - * that alternate between field paths and field values. Nested fields can be - * updated by providing dot-separated field path strings or by providing - * FieldPath objects. - * - * A Precondition restricting this update can be specified as the last - * argument. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be updated. - * @param {UpdateData|string|FieldPath} dataOrField - An object - * containing the fields and values with which to update the document - * or the path of the first field to update. - * @param { - * ...(Precondition|*|string|FieldPath)} preconditionOrValues - - * An alternating list of field paths and values to update or a Precondition - * to to enforce on this update. - * @returns {Transaction} This Transaction instance. Used for - * chaining method calls. - * - * @example - * firestore.runTransaction(transaction => { - * let documentRef = firestore.doc('col/doc'); - * return transaction.get(documentRef).then(doc => { - * if (doc.exists) { - * transaction.update(documentRef, { count: doc.get('count') + 1 }); - * } else { - * transaction.create(documentRef, { count: 1 }); - * } - * }); - * }); - */ - update(documentRef, dataOrField, preconditionOrValues) { - this._validator.minNumberOfArguments('update', arguments, 2); - preconditionOrValues = Array.prototype.slice.call(arguments, 2); - this._writeBatch.update.apply(this._writeBatch, [documentRef, dataOrField].concat(preconditionOrValues)); - return this; - } - /** - * Deletes the document referred to by the provided [DocumentReference] - * {@link DocumentReference}. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be deleted. - * @param {Precondition=} precondition - A precondition to enforce for this - * delete. - * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the - * document was last updated at lastUpdateTime. Fails the transaction if the - * document doesn't exist or was last updated at a different time. - * @returns {Transaction} This Transaction instance. Used for - * chaining method calls. - * - * @example - * firestore.runTransaction(transaction => { - * let documentRef = firestore.doc('col/doc'); - * transaction.delete(documentRef); - * return Promise.resolve(); - * }); - */ - delete(documentRef, precondition) { - this._writeBatch.delete(documentRef, precondition); - return this; - } - /** - * Starts a transaction and obtains the transaction id from the server. - * - * @private - * @returns {Promise} An empty Promise. - */ - begin() { - let request = { - database: this._firestore.formattedName, - }; - if (this._previousTransaction) { - request.options = { - readWrite: { - retryTransaction: this._previousTransaction._transactionId, - }, - }; - } - return this._firestore - .request('beginTransaction', request, this._requestTag, ALLOW_RETRIES) - .then(resp => { - this._transactionId = resp.transaction; - }); - } - /** - * Commits all queued-up changes in this transaction and releases all locks. - * - * @private - * @returns {Promise} An empty Promise. - */ - commit() { - return this._writeBatch.commit_({ - transactionId: this._transactionId, - requestTag: this._requestTag, - }); - } - /** - * Releases all locks and rolls back this transaction. - * - * @private - * @returns {Promise} An empty Promise. - */ - rollback() { - let request = { - database: this._firestore.formattedName, - transaction: this._transactionId, - }; - return this._firestore.request('rollback', request, this._requestTag); - } - /** - * Returns the tag to use with with all request for this Transaction. - * @private - * @return {string} A unique client-generated identifier for this transaction. - */ - get requestTag() { - return this._requestTag; - } -} -exports.Transaction = Transaction; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/types.js b/functions/node_modules/@google-cloud/firestore/build/src/types.js deleted file mode 100644 index 2e63de2a..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/types.js +++ /dev/null @@ -1,17 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/functions/node_modules/@google-cloud/firestore/build/src/util.js b/functions/node_modules/@google-cloud/firestore/build/src/util.js deleted file mode 100644 index e4b5052c..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/util.js +++ /dev/null @@ -1,46 +0,0 @@ -/*! - * Copyright 2018 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Generate a unique client-side identifier. - * - * Used for the creation of new documents. - * - * @private - * @returns {string} A unique 20-character wide identifier. - */ -function autoId() { - const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - let autoId = ''; - for (let i = 0; i < 20; i++) { - autoId += chars.charAt(Math.floor(Math.random() * chars.length)); - } - return autoId; -} -exports.autoId = autoId; -/** - * Generate a short and semi-random client-side identifier. - * - * Used for the creation of request tags. - * - * @private - * @returns {string} A random 5-character wide identifier. - */ -function requestTag() { - return autoId().substr(0, 5); -} -exports.requestTag = requestTag; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_common.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_common.js deleted file mode 100644 index 2d2d760e..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_common.js +++ /dev/null @@ -1,107 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * A set of field paths on a document. - * Used to restrict a get or update operation on a document to a subset of its - * fields. - * This is different from standard field masks, as this is always scoped to a - * Document, and takes in account the dynamic nature of Value. - * - * @property {string[]} fieldPaths - * The list of field paths in the mask. See Document.fields for a field - * path syntax reference. - * - * @typedef DocumentMask - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DocumentMask definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto} - */ -var DocumentMask = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A precondition on a document, used for conditional operations. - * - * @property {boolean} exists - * When set to `true`, the target document must exist. - * When set to `false`, the target document must not exist. - * - * @property {Object} updateTime - * When set, the target document must exist and have been last updated at - * that time. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef Precondition - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Precondition definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto} - */ -var Precondition = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Options for creating a new transaction. - * - * @property {Object} readOnly - * The transaction can only be used for read operations. - * - * This object should have the same structure as [ReadOnly]{@link - * google.firestore.v1beta1.ReadOnly} - * - * @property {Object} readWrite - * The transaction can be used for both read and write operations. - * - * This object should have the same structure as [ReadWrite]{@link - * google.firestore.v1beta1.ReadWrite} - * - * @typedef TransactionOptions - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.TransactionOptions definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto} - */ -var TransactionOptions = { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * Options for a transaction that can be used to read and write documents. - * - * @property {string} retryTransaction - * An optional transaction to retry. - * - * @typedef ReadWrite - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.TransactionOptions.ReadWrite definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto} - */ - ReadWrite: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * Options for a transaction that can only be used to read documents. - * - * @property {Object} readTime - * Reads documents at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef ReadOnly - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.TransactionOptions.ReadOnly definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto} - */ - ReadOnly: { - // This is for documentation. Actual contents will be loaded by gRPC. - } -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_document.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_document.js deleted file mode 100644 index 2a9cde76..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_document.js +++ /dev/null @@ -1,183 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * A Firestore document. - * - * Must not exceed 1 MiB - 4 bytes. - * - * @property {string} name - * The resource name of the document, for example - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * @property {Object.} fields - * The document's fields. - * - * The map keys represent field names. - * - * A simple field name contains only characters `a` to `z`, `A` to `Z`, - * `0` to `9`, or `_`, and must not start with `0` to `9` or `_`. For example, - * `foo_bar_17`. - * - * Field names matching the regular expression `__.*__` are reserved. Reserved - * field names are forbidden except in certain documented contexts. The map - * keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be - * empty. - * - * Field paths may be used in other contexts to refer to structured fields - * defined here. For `map_value`, the field path is represented by the simple - * or quoted field names of the containing fields, delimited by `.`. For - * example, the structured field - * `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be - * represented by the field path `foo.x&y`. - * - * Within a field path, a quoted field name starts and ends with `` ` `` and - * may contain any character. Some characters, including `` ` ``, must be - * escaped using a `\`. For example, `` `x&y` `` represents `x&y` and - * `` `bak\`tik` `` represents `` bak`tik ``. - * - * @property {Object} createTime - * Output only. The time at which the document was created. - * - * This value increases monotonically when a document is deleted then - * recreated. It can also be compared to values from other documents and - * the `read_time` of a query. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @property {Object} updateTime - * Output only. The time at which the document was last changed. - * - * This value is initally set to the `create_time` then increases - * monotonically with each change to the document. It can also be - * compared to values from other documents and the `read_time` of a query. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef Document - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Document definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto} - */ -var Document = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A message that can hold any of the supported value types. - * - * @property {number} nullValue - * A null value. - * - * The number should be among the values of [NullValue]{@link - * google.protobuf.NullValue} - * - * @property {boolean} booleanValue - * A boolean value. - * - * @property {number} integerValue - * An integer value. - * - * @property {number} doubleValue - * A double value. - * - * @property {Object} timestampValue - * A timestamp value. - * - * Precise only to microseconds. When stored, any additional precision is - * rounded down. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @property {string} stringValue - * A string value. - * - * The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. - * Only the first 1,500 bytes of the UTF-8 representation are considered by - * queries. - * - * @property {string} bytesValue - * A bytes value. - * - * Must not exceed 1 MiB - 89 bytes. - * Only the first 1,500 bytes are considered by queries. - * - * @property {string} referenceValue - * A reference to a document. For example: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * @property {Object} geoPointValue - * A geo point value representing a point on the surface of Earth. - * - * This object should have the same structure as [LatLng]{@link - * google.type.LatLng} - * - * @property {Object} arrayValue - * An array value. - * - * Cannot contain another array value. - * - * This object should have the same structure as [ArrayValue]{@link - * google.firestore.v1beta1.ArrayValue} - * - * @property {Object} mapValue - * A map value. - * - * This object should have the same structure as [MapValue]{@link - * google.firestore.v1beta1.MapValue} - * - * @typedef Value - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Value definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto} - */ -var Value = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * An array value. - * - * @property {Object[]} values - * Values in the array. - * - * This object should have the same structure as [Value]{@link - * google.firestore.v1beta1.Value} - * - * @typedef ArrayValue - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ArrayValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto} - */ -var ArrayValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A map value. - * - * @property {Object.} fields - * The map's fields. - * - * The map keys represent field names. Field names matching the regular - * expression `__.*__` are reserved. Reserved field names are forbidden except - * in certain documented contexts. The map keys, represented as UTF-8, must - * not exceed 1,500 bytes and cannot be empty. - * - * @typedef MapValue - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.MapValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto} - */ -var MapValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_firestore.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_firestore.js deleted file mode 100644 index 6e8a5010..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_firestore.js +++ /dev/null @@ -1,881 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * The request for Firestore.GetDocument. - * - * @property {string} name - * The resource name of the Document to get. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * @property {Object} mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @property {string} transaction - * Reads the document in a transaction. - * - * @property {Object} readTime - * Reads the version of the document at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef GetDocumentRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.GetDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var GetDocumentRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.ListDocuments. - * - * @property {string} parent - * The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * - * @property {string} collectionId - * The collection ID, relative to `parent`, to list. For example: `chatrooms` - * or `messages`. - * - * @property {number} pageSize - * The maximum number of documents to return. - * - * @property {string} pageToken - * The `next_page_token` value returned from a previous List request, if any. - * - * @property {string} orderBy - * The order to sort results by. For example: `priority desc, name`. - * - * @property {Object} mask - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @property {string} transaction - * Reads documents in a transaction. - * - * @property {Object} readTime - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @property {boolean} showMissing - * If the list should show missing documents. A missing document is a - * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, Document.create_time, - * or Document.update_time set. - * - * Requests with `show_missing` may not specify `where` or - * `order_by`. - * - * @typedef ListDocumentsRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ListDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var ListDocumentsRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response for Firestore.ListDocuments. - * - * @property {Object[]} documents - * The Documents found. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {string} nextPageToken - * The next page token. - * - * @typedef ListDocumentsResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ListDocumentsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var ListDocumentsResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.CreateDocument. - * - * @property {string} parent - * The parent resource. For example: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` - * - * @property {string} collectionId - * The collection ID, relative to `parent`, to list. For example: `chatrooms`. - * - * @property {string} documentId - * The client-assigned document ID to use for this document. - * - * Optional. If not specified, an ID will be assigned by the service. - * - * @property {Object} document - * The document to create. `name` must not be set. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {Object} mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @typedef CreateDocumentRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.CreateDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var CreateDocumentRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.UpdateDocument. - * - * @property {Object} document - * The updated document. - * Creates the document if it does not already exist. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {Object} updateMask - * The fields to update. - * None of the field paths in the mask may contain a reserved name. - * - * If the document exists on the server and has fields not referenced in the - * mask, they are left unchanged. - * Fields referenced in the mask, but not present in the input document, are - * deleted from the document on the server. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @property {Object} mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @property {Object} currentDocument - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * - * This object should have the same structure as [Precondition]{@link - * google.firestore.v1beta1.Precondition} - * - * @typedef UpdateDocumentRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.UpdateDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var UpdateDocumentRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.DeleteDocument. - * - * @property {string} name - * The resource name of the Document to delete. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * @property {Object} currentDocument - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * - * This object should have the same structure as [Precondition]{@link - * google.firestore.v1beta1.Precondition} - * - * @typedef DeleteDocumentRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DeleteDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var DeleteDocumentRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.BatchGetDocuments. - * - * @property {string} database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * - * @property {string[]} documents - * The names of the documents to retrieve. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * The request will fail if any of the document is not a child resource of the - * given `database`. Duplicate names will be elided. - * - * @property {Object} mask - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field will - * not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @property {string} transaction - * Reads documents in a transaction. - * - * @property {Object} newTransaction - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * - * This object should have the same structure as [TransactionOptions]{@link - * google.firestore.v1beta1.TransactionOptions} - * - * @property {Object} readTime - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef BatchGetDocumentsRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.BatchGetDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var BatchGetDocumentsRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The streamed response for Firestore.BatchGetDocuments. - * - * @property {Object} found - * A document that was requested. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {string} missing - * A document name that was requested but does not exist. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * @property {string} transaction - * The transaction that was started as part of this request. - * Will only be set in the first response, and only if - * BatchGetDocumentsRequest.new_transaction was set in the request. - * - * @property {Object} readTime - * The time at which the document was read. - * This may be monotically increasing, in this case the previous documents in - * the result stream are guaranteed not to have changed between their - * read_time and this one. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef BatchGetDocumentsResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.BatchGetDocumentsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var BatchGetDocumentsResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.BeginTransaction. - * - * @property {string} database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * - * @property {Object} options - * The options for the transaction. - * Defaults to a read-write transaction. - * - * This object should have the same structure as [TransactionOptions]{@link - * google.firestore.v1beta1.TransactionOptions} - * - * @typedef BeginTransactionRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.BeginTransactionRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var BeginTransactionRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response for Firestore.BeginTransaction. - * - * @property {string} transaction - * The transaction that was started. - * - * @typedef BeginTransactionResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.BeginTransactionResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var BeginTransactionResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.Commit. - * - * @property {string} database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * - * @property {Object[]} writes - * The writes to apply. - * - * Always executed atomically and in order. - * - * This object should have the same structure as [Write]{@link - * google.firestore.v1beta1.Write} - * - * @property {string} transaction - * If set, applies all writes in this transaction, and commits it. - * - * @typedef CommitRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.CommitRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var CommitRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response for Firestore.Commit. - * - * @property {Object[]} writeResults - * The result of applying the writes. - * - * This i-th write result corresponds to the i-th write in the - * request. - * - * This object should have the same structure as [WriteResult]{@link - * google.firestore.v1beta1.WriteResult} - * - * @property {Object} commitTime - * The time at which the commit occurred. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef CommitResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.CommitResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var CommitResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.Rollback. - * - * @property {string} database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * - * @property {string} transaction - * The transaction to roll back. - * - * @typedef RollbackRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.RollbackRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var RollbackRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.RunQuery. - * - * @property {string} parent - * The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * - * @property {Object} structuredQuery - * A structured query. - * - * This object should have the same structure as [StructuredQuery]{@link - * google.firestore.v1beta1.StructuredQuery} - * - * @property {string} transaction - * Reads documents in a transaction. - * - * @property {Object} newTransaction - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * - * This object should have the same structure as [TransactionOptions]{@link - * google.firestore.v1beta1.TransactionOptions} - * - * @property {Object} readTime - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef RunQueryRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.RunQueryRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var RunQueryRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response for Firestore.RunQuery. - * - * @property {string} transaction - * The transaction that was started as part of this request. - * Can only be set in the first response, and only if - * RunQueryRequest.new_transaction was set in the request. - * If set, no other fields will be set in this response. - * - * @property {Object} document - * A query result. - * Not set when reporting partial progress. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {Object} readTime - * The time at which the document was read. This may be monotonically - * increasing; in this case, the previous documents in the result stream are - * guaranteed not to have changed between their `read_time` and this one. - * - * If the query returns no results, a response with `read_time` and no - * `document` will be sent, and this represents the time at which the query - * was run. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @property {number} skippedResults - * The number of results that have been skipped due to an offset between - * the last response and the current response. - * - * @typedef RunQueryResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.RunQueryResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var RunQueryResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The request for Firestore.Write. - * - * The first request creates a stream, or resumes an existing one from a token. - * - * When creating a new stream, the server replies with a response containing - * only an ID and a token, to use in the next request. - * - * When resuming a stream, the server first streams any responses later than the - * given token, then a response containing only an up-to-date token, to use in - * the next request. - * - * @property {string} database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * This is only required in the first message. - * - * @property {string} streamId - * The ID of the write stream to resume. - * This may only be set in the first message. When left empty, a new write - * stream will be created. - * - * @property {Object[]} writes - * The writes to apply. - * - * Always executed atomically and in order. - * This must be empty on the first request. - * This may be empty on the last request. - * This must not be empty on all other requests. - * - * This object should have the same structure as [Write]{@link - * google.firestore.v1beta1.Write} - * - * @property {string} streamToken - * A stream token that was previously sent by the server. - * - * The client should set this field to the token from the most recent - * WriteResponse it has received. This acknowledges that the client has - * received responses up to this token. After sending this token, earlier - * tokens may not be used anymore. - * - * The server may close the stream if there are too many unacknowledged - * responses. - * - * Leave this field unset when creating a new stream. To resume a stream at - * a specific point, set this field and the `stream_id` field. - * - * Leave this field unset when creating a new stream. - * - * @property {Object.} labels - * Labels associated with this write request. - * - * @typedef WriteRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.WriteRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var WriteRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response for Firestore.Write. - * - * @property {string} streamId - * The ID of the stream. - * Only set on the first message, when a new stream was created. - * - * @property {string} streamToken - * A token that represents the position of this response in the stream. - * This can be used by a client to resume the stream at this point. - * - * This field is always set. - * - * @property {Object[]} writeResults - * The result of applying the writes. - * - * This i-th write result corresponds to the i-th write in the - * request. - * - * This object should have the same structure as [WriteResult]{@link - * google.firestore.v1beta1.WriteResult} - * - * @property {Object} commitTime - * The time at which the commit occurred. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef WriteResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.WriteResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var WriteResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A request for Firestore.Listen - * - * @property {string} database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * - * @property {Object} addTarget - * A target to add to this stream. - * - * This object should have the same structure as [Target]{@link - * google.firestore.v1beta1.Target} - * - * @property {number} removeTarget - * The ID of a target to remove from this stream. - * - * @property {Object.} labels - * Labels associated with this target change. - * - * @typedef ListenRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ListenRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var ListenRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response for Firestore.Listen. - * - * @property {Object} targetChange - * Targets have changed. - * - * This object should have the same structure as [TargetChange]{@link - * google.firestore.v1beta1.TargetChange} - * - * @property {Object} documentChange - * A Document has changed. - * - * This object should have the same structure as [DocumentChange]{@link - * google.firestore.v1beta1.DocumentChange} - * - * @property {Object} documentDelete - * A Document has been deleted. - * - * This object should have the same structure as [DocumentDelete]{@link - * google.firestore.v1beta1.DocumentDelete} - * - * @property {Object} documentRemove - * A Document has been removed from a target (because it is no longer - * relevant to that target). - * - * This object should have the same structure as [DocumentRemove]{@link - * google.firestore.v1beta1.DocumentRemove} - * - * @property {Object} filter - * A filter to apply to the set of documents previously returned for the - * given target. - * - * Returned when documents may have been removed from the given target, but - * the exact documents are unknown. - * - * This object should have the same structure as [ExistenceFilter]{@link - * google.firestore.v1beta1.ExistenceFilter} - * - * @typedef ListenResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ListenResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var ListenResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A specification of a set of documents to listen to. - * - * @property {Object} query - * A target specified by a query. - * - * This object should have the same structure as [QueryTarget]{@link - * google.firestore.v1beta1.QueryTarget} - * - * @property {Object} documents - * A target specified by a set of document names. - * - * This object should have the same structure as [DocumentsTarget]{@link - * google.firestore.v1beta1.DocumentsTarget} - * - * @property {string} resumeToken - * A resume token from a prior TargetChange for an identical target. - * - * Using a resume token with a different target is unsupported and may fail. - * - * @property {Object} readTime - * Start listening after a specific `read_time`. - * - * The client must know the state of matching documents at this time. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @property {number} targetId - * A client provided target ID. - * - * If not set, the server will assign an ID for the target. - * - * Used for resuming a target without changing IDs. The IDs can either be - * client-assigned or be server-assigned in a previous stream. All targets - * with client provided IDs must be added before adding a target that needs - * a server-assigned id. - * - * @property {boolean} once - * If the target should be removed once it is current and consistent. - * - * @typedef Target - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Target definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var Target = { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A target specified by a set of documents names. - * - * @property {string[]} documents - * The names of the documents to retrieve. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * The request will fail if any of the document is not a child resource of - * the given `database`. Duplicate names will be elided. - * - * @typedef DocumentsTarget - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Target.DocumentsTarget definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ - DocumentsTarget: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * A target specified by a query. - * - * @property {string} parent - * The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * - * @property {Object} structuredQuery - * A structured query. - * - * This object should have the same structure as [StructuredQuery]{@link - * google.firestore.v1beta1.StructuredQuery} - * - * @typedef QueryTarget - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Target.QueryTarget definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ - QueryTarget: { - // This is for documentation. Actual contents will be loaded by gRPC. - } -}; -/** - * Targets being watched have changed. - * - * @property {number} targetChangeType - * The type of change that occurred. - * - * The number should be among the values of [TargetChangeType]{@link - * google.firestore.v1beta1.TargetChangeType} - * - * @property {number[]} targetIds - * The target IDs of targets that have changed. - * - * If empty, the change applies to all targets. - * - * For `target_change_type=ADD`, the order of the target IDs matches the order - * of the requests to add the targets. This allows clients to unambiguously - * associate server-assigned target IDs with added targets. - * - * For other states, the order of the target IDs is not defined. - * - * @property {Object} cause - * The error that resulted in this change, if applicable. - * - * This object should have the same structure as [Status]{@link - * google.rpc.Status} - * - * @property {string} resumeToken - * A token that can be used to resume the stream for the given `target_ids`, - * or all targets if `target_ids` is empty. - * - * Not set on every target change. - * - * @property {Object} readTime - * The consistent `read_time` for the given `target_ids` (omitted when the - * target_ids are not at a consistent snapshot). - * - * The stream is guaranteed to send a `read_time` with `target_ids` empty - * whenever the entire stream reaches a new consistent snapshot. ADD, - * CURRENT, and RESET messages are guaranteed to (eventually) result in a - * new consistent snapshot (while NO_CHANGE and REMOVE messages are not). - * - * For a given stream, `read_time` is guaranteed to be monotonically - * increasing. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef TargetChange - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.TargetChange definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var TargetChange = { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * The type of change. - * - * @enum {number} - * @memberof google.firestore.v1beta1 - */ - TargetChangeType: { - /** - * No change has occurred. Used only to send an updated `resume_token`. - */ - NO_CHANGE: 0, - /** - * The targets have been added. - */ - ADD: 1, - /** - * The targets have been removed. - */ - REMOVE: 2, - /** - * The targets reflect all changes committed before the targets were added - * to the stream. - * - * This will be sent after or with a `read_time` that is greater than or - * equal to the time at which the targets were added. - * - * Listeners can wait for this change if read-after-write semantics - * are desired. - */ - CURRENT: 3, - /** - * The targets have been reset, and a new initial state for the targets - * will be returned in subsequent changes. - * - * After the initial state is complete, `CURRENT` will be returned even - * if the target was previously indicated to be `CURRENT`. - */ - RESET: 4 - } -}; -/** - * The request for Firestore.ListCollectionIds. - * - * @property {string} parent - * The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * - * @property {number} pageSize - * The maximum number of results to return. - * - * @property {string} pageToken - * A page token. Must be a value from - * ListCollectionIdsResponse. - * - * @typedef ListCollectionIdsRequest - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ListCollectionIdsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var ListCollectionIdsRequest = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * The response from Firestore.ListCollectionIds. - * - * @property {string[]} collectionIds - * The collection ids. - * - * @property {string} nextPageToken - * A page token that may be used to continue the list. - * - * @typedef ListCollectionIdsResponse - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ListCollectionIdsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto} - */ -var ListCollectionIdsResponse = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_query.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_query.js deleted file mode 100644 index 881adcad..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_query.js +++ /dev/null @@ -1,379 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * A Firestore query. - * - * @property {Object} select - * The projection to return. - * - * This object should have the same structure as [Projection]{@link - * google.firestore.v1beta1.Projection} - * - * @property {Object[]} from - * The collections to query. - * - * This object should have the same structure as [CollectionSelector]{@link - * google.firestore.v1beta1.CollectionSelector} - * - * @property {Object} where - * The filter to apply. - * - * This object should have the same structure as [Filter]{@link - * google.firestore.v1beta1.Filter} - * - * @property {Object[]} orderBy - * The order to apply to the query results. - * - * Firestore guarantees a stable ordering through the following rules: - * - * * Any field required to appear in `order_by`, that is not already - * specified in `order_by`, is appended to the order in field name order - * by default. - * * If an order on `__name__` is not specified, it is appended by default. - * - * Fields are appended with the same sort direction as the last order - * specified, or 'ASCENDING' if no order was specified. For example: - * - * * `SELECT * FROM Foo ORDER BY A` becomes - * `SELECT * FROM Foo ORDER BY A, __name__` - * * `SELECT * FROM Foo ORDER BY A DESC` becomes - * `SELECT * FROM Foo ORDER BY A DESC, __name__ DESC` - * * `SELECT * FROM Foo WHERE A > 1` becomes - * `SELECT * FROM Foo WHERE A > 1 ORDER BY A, __name__` - * - * This object should have the same structure as [Order]{@link - * google.firestore.v1beta1.Order} - * - * @property {Object} startAt - * A starting point for the query results. - * - * This object should have the same structure as [Cursor]{@link - * google.firestore.v1beta1.Cursor} - * - * @property {Object} endAt - * A end point for the query results. - * - * This object should have the same structure as [Cursor]{@link - * google.firestore.v1beta1.Cursor} - * - * @property {number} offset - * The number of results to skip. - * - * Applies before limit, but after all other constraints. Must be >= 0 if - * specified. - * - * @property {Object} limit - * The maximum number of results to return. - * - * Applies after all other constraints. - * Must be >= 0 if specified. - * - * This object should have the same structure as [Int32Value]{@link - * google.protobuf.Int32Value} - * - * @typedef StructuredQuery - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ -var StructuredQuery = { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A selection of a collection, such as `messages as m1`. - * - * @property {string} collectionId - * The collection ID. - * When set, selects only collections with this ID. - * - * @property {boolean} allDescendants - * When false, selects only collections that are immediate children of - * the `parent` specified in the containing `RunQueryRequest`. - * When true, selects all descendant collections. - * - * @typedef CollectionSelector - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.CollectionSelector definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - CollectionSelector: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * A filter. - * - * @property {Object} compositeFilter - * A composite filter. - * - * This object should have the same structure as [CompositeFilter]{@link - * google.firestore.v1beta1.CompositeFilter} - * - * @property {Object} fieldFilter - * A filter on a document field. - * - * This object should have the same structure as [FieldFilter]{@link - * google.firestore.v1beta1.FieldFilter} - * - * @property {Object} unaryFilter - * A filter that takes exactly one argument. - * - * This object should have the same structure as [UnaryFilter]{@link - * google.firestore.v1beta1.UnaryFilter} - * - * @typedef Filter - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.Filter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - Filter: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * A filter that merges multiple other filters using the given operator. - * - * @property {number} op - * The operator for combining multiple filters. - * - * The number should be among the values of [Operator]{@link - * google.firestore.v1beta1.Operator} - * - * @property {Object[]} filters - * The list of filters to combine. - * Must contain at least one filter. - * - * This object should have the same structure as [Filter]{@link - * google.firestore.v1beta1.Filter} - * - * @typedef CompositeFilter - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.CompositeFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - CompositeFilter: { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A composite filter operator. - * - * @enum {number} - * @memberof google.firestore.v1beta1 - */ - Operator: { - /** - * Unspecified. This value must not be used. - */ - OPERATOR_UNSPECIFIED: 0, - /** - * The results are required to satisfy each of the combined filters. - */ - AND: 1 - } - }, - /** - * A filter on a specific field. - * - * @property {Object} field - * The field to filter by. - * - * This object should have the same structure as [FieldReference]{@link - * google.firestore.v1beta1.FieldReference} - * - * @property {number} op - * The operator to filter by. - * - * The number should be among the values of [Operator]{@link - * google.firestore.v1beta1.Operator} - * - * @property {Object} value - * The value to compare to. - * - * This object should have the same structure as [Value]{@link - * google.firestore.v1beta1.Value} - * - * @typedef FieldFilter - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.FieldFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - FieldFilter: { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A field filter operator. - * - * @enum {number} - * @memberof google.firestore.v1beta1 - */ - Operator: { - /** - * Unspecified. This value must not be used. - */ - OPERATOR_UNSPECIFIED: 0, - /** - * Less than. Requires that the field come first in `order_by`. - */ - LESS_THAN: 1, - /** - * Less than or equal. Requires that the field come first in `order_by`. - */ - LESS_THAN_OR_EQUAL: 2, - /** - * Greater than. Requires that the field come first in `order_by`. - */ - GREATER_THAN: 3, - /** - * Greater than or equal. Requires that the field come first in - * `order_by`. - */ - GREATER_THAN_OR_EQUAL: 4, - /** - * Equal. - */ - EQUAL: 5 - } - }, - /** - * A filter with a single operand. - * - * @property {number} op - * The unary operator to apply. - * - * The number should be among the values of [Operator]{@link - * google.firestore.v1beta1.Operator} - * - * @property {Object} field - * The field to which to apply the operator. - * - * This object should have the same structure as [FieldReference]{@link - * google.firestore.v1beta1.FieldReference} - * - * @typedef UnaryFilter - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.UnaryFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - UnaryFilter: { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A unary operator. - * - * @enum {number} - * @memberof google.firestore.v1beta1 - */ - Operator: { - /** - * Unspecified. This value must not be used. - */ - OPERATOR_UNSPECIFIED: 0, - /** - * Test if a field is equal to NaN. - */ - IS_NAN: 2, - /** - * Test if an exprestion evaluates to Null. - */ - IS_NULL: 3 - } - }, - /** - * An order on a field. - * - * @property {Object} field - * The field to order by. - * - * This object should have the same structure as [FieldReference]{@link - * google.firestore.v1beta1.FieldReference} - * - * @property {number} direction - * The direction to order by. Defaults to `ASCENDING`. - * - * The number should be among the values of [Direction]{@link - * google.firestore.v1beta1.Direction} - * - * @typedef Order - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.Order definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - Order: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * A reference to a field, such as `max(messages.time) as max_time`. - * - * @property {string} fieldPath - * - * @typedef FieldReference - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.FieldReference definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - FieldReference: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * The projection of document's fields to return. - * - * @property {Object[]} fields - * The fields to return. - * - * If empty, all fields are returned. To only return the name - * of the document, use `['__name__']`. - * - * This object should have the same structure as [FieldReference]{@link - * google.firestore.v1beta1.FieldReference} - * - * @typedef Projection - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.StructuredQuery.Projection definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ - Projection: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - /** - * A sort direction. - * - * @enum {number} - * @memberof google.firestore.v1beta1 - */ - Direction: { - /** - * Unspecified. - */ - DIRECTION_UNSPECIFIED: 0, - /** - * Ascending. - */ - ASCENDING: 1, - /** - * Descending. - */ - DESCENDING: 2 - } -}; -/** - * A position in a query result set. - * - * @property {Object[]} values - * The values that represent a position, in the order they appear in - * the order by clause of a query. - * - * Can contain fewer values than specified in the order by clause. - * - * This object should have the same structure as [Value]{@link - * google.firestore.v1beta1.Value} - * - * @property {boolean} before - * If the position is just before or just after the given values, relative - * to the sort order defined by the query. - * - * @typedef Cursor - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Cursor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto} - */ -var Cursor = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_write.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_write.js deleted file mode 100644 index a7c85a1e..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/firestore/v1beta1/doc_write.js +++ /dev/null @@ -1,262 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * A write on a document. - * - * @property {Object} update - * A document to write. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {string} delete - * A document name to delete. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * @property {Object} transform - * Applies a tranformation to a document. - * At most one `transform` per document is allowed in a given request. - * An `update` cannot follow a `transform` on the same document in a given - * request. - * - * This object should have the same structure as [DocumentTransform]{@link - * google.firestore.v1beta1.DocumentTransform} - * - * @property {Object} updateMask - * The fields to update in this write. - * - * This field can be set only when the operation is `update`. - * None of the field paths in the mask may contain a reserved name. - * If the document exists on the server and has fields not referenced in the - * mask, they are left unchanged. - * Fields referenced in the mask, but not present in the input document, are - * deleted from the document on the server. - * The field paths in this mask must not contain a reserved field name. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * - * @property {Object} currentDocument - * An optional precondition on the document. - * - * The write will fail if this is set and not met by the target document. - * - * This object should have the same structure as [Precondition]{@link - * google.firestore.v1beta1.Precondition} - * - * @typedef Write - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.Write definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var Write = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A transformation of a document. - * - * @property {string} document - * The name of the document to transform. - * - * @property {Object[]} fieldTransforms - * The list of transformations to apply to the fields of the document, in - * order. - * This must not be empty. - * - * This object should have the same structure as [FieldTransform]{@link - * google.firestore.v1beta1.FieldTransform} - * - * @typedef DocumentTransform - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DocumentTransform definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var DocumentTransform = { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A transformation of a field of the document. - * - * @property {string} fieldPath - * The path of the field. See Document.fields for the field path syntax - * reference. - * - * @property {number} setToServerValue - * Sets the field to the given server value. - * - * The number should be among the values of [ServerValue]{@link - * google.firestore.v1beta1.ServerValue} - * - * @typedef FieldTransform - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DocumentTransform.FieldTransform definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ - FieldTransform: { - // This is for documentation. Actual contents will be loaded by gRPC. - /** - * A value that is calculated by the server. - * - * @enum {number} - * @memberof google.firestore.v1beta1 - */ - ServerValue: { - /** - * Unspecified. This value must not be used. - */ - SERVER_VALUE_UNSPECIFIED: 0, - /** - * The time at which the server processed the request, with millisecond - * precision. - */ - REQUEST_TIME: 1 - } - } -}; -/** - * The result of applying a write. - * - * @property {Object} updateTime - * The last update time of the document after applying the write. Not set - * after a `delete`. - * - * If the write did not actually change the document, this will be the - * previous update_time. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @property {Object[]} transformResults - * The results of applying each DocumentTransform.FieldTransform, in the - * same order. - * - * This object should have the same structure as [Value]{@link - * google.firestore.v1beta1.Value} - * - * @typedef WriteResult - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.WriteResult definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var WriteResult = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A Document has changed. - * - * May be the result of multiple writes, including deletes, that - * ultimately resulted in a new value for the Document. - * - * Multiple DocumentChange messages may be returned for the same logical - * change, if multiple targets are affected. - * - * @property {Object} document - * The new state of the Document. - * - * If `mask` is set, contains only fields that were updated or added. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * - * @property {number[]} targetIds - * A set of target IDs of targets that match this document. - * - * @property {number[]} removedTargetIds - * A set of target IDs for targets that no longer match this document. - * - * @typedef DocumentChange - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DocumentChange definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var DocumentChange = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A Document has been deleted. - * - * May be the result of multiple writes, including updates, the - * last of which deleted the Document. - * - * Multiple DocumentDelete messages may be returned for the same logical - * delete, if multiple targets are affected. - * - * @property {string} document - * The resource name of the Document that was deleted. - * - * @property {number[]} removedTargetIds - * A set of target IDs for targets that previously matched this entity. - * - * @property {Object} readTime - * The read timestamp at which the delete was observed. - * - * Greater or equal to the `commit_time` of the delete. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef DocumentDelete - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DocumentDelete definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var DocumentDelete = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A Document has been removed from the view of the targets. - * - * Sent if the document is no longer relevant to a target and is out of view. - * Can be sent instead of a DocumentDelete or a DocumentChange if the server - * can not send the new value of the document. - * - * Multiple DocumentRemove messages may be returned for the same logical - * write or delete, if multiple targets are affected. - * - * @property {string} document - * The resource name of the Document that has gone out of view. - * - * @property {number[]} removedTargetIds - * A set of target IDs for targets that previously matched this document. - * - * @property {Object} readTime - * The read timestamp at which the remove was observed. - * - * Greater or equal to the `commit_time` of the change/delete/remove. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * - * @typedef DocumentRemove - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.DocumentRemove definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var DocumentRemove = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * A digest of all the documents that match a given target. - * - * @property {number} targetId - * The target ID to which this filter applies. - * - * @property {number} count - * The total count of documents that match target_id. - * - * If different from the count of documents in the client that match, the - * client must manually determine which documents no longer match the target. - * - * @typedef ExistenceFilter - * @memberof google.firestore.v1beta1 - * @see [google.firestore.v1beta1.ExistenceFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto} - */ -var ExistenceFilter = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_any.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_any.js deleted file mode 100644 index 6c1af084..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_any.js +++ /dev/null @@ -1,130 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * `Any` contains an arbitrary serialized protocol buffer message along with a - * URL that describes the type of the serialized message. - * - * Protobuf library provides support to pack/unpack Any values in the form - * of utility functions or additional generated methods of the Any type. - * - * Example 1: Pack and unpack a message in C++. - * - * Foo foo = ...; - * Any any; - * any.PackFrom(foo); - * ... - * if (any.UnpackTo(&foo)) { - * ... - * } - * - * Example 2: Pack and unpack a message in Java. - * - * Foo foo = ...; - * Any any = Any.pack(foo); - * ... - * if (any.is(Foo.class)) { - * foo = any.unpack(Foo.class); - * } - * - * Example 3: Pack and unpack a message in Python. - * - * foo = Foo(...) - * any = Any() - * any.Pack(foo) - * ... - * if any.Is(Foo.DESCRIPTOR): - * any.Unpack(foo) - * ... - * - * Example 4: Pack and unpack a message in Go - * - * foo := &pb.Foo{...} - * any, err := ptypes.MarshalAny(foo) - * ... - * foo := &pb.Foo{} - * if err := ptypes.UnmarshalAny(any, foo); err != nil { - * ... - * } - * - * The pack methods provided by protobuf library will by default use - * 'type.googleapis.com/full.type.name' as the type URL and the unpack - * methods only use the fully qualified type name after the last '/' - * in the type URL, for example "foo.bar.com/x/y.z" will yield type - * name "y.z". - * - * - * # JSON - * - * The JSON representation of an `Any` value uses the regular - * representation of the deserialized, embedded message, with an - * additional field `@type` which contains the type URL. Example: - * - * package google.profile; - * message Person { - * string first_name = 1; - * string last_name = 2; - * } - * - * { - * "@type": "type.googleapis.com/google.profile.Person", - * "firstName": , - * "lastName": - * } - * - * If the embedded message type is well-known and has a custom JSON - * representation, that representation will be embedded adding a field - * `value` which holds the custom JSON in addition to the `@type` - * field. Example (for message google.protobuf.Duration): - * - * { - * "@type": "type.googleapis.com/google.protobuf.Duration", - * "value": "1.212s" - * } - * - * @property {string} typeUrl - * A URL/resource name whose content describes the type of the - * serialized protocol buffer message. - * - * For URLs which use the scheme `http`, `https`, or no scheme, the - * following restrictions and interpretations apply: - * - * * If no scheme is provided, `https` is assumed. - * * The last segment of the URL's path must represent the fully - * qualified name of the type (as in `path/google.protobuf.Duration`). - * The name should be in a canonical form (e.g., leading "." is - * not accepted). - * * An HTTP GET on the URL must yield a google.protobuf.Type - * value in binary format, or produce an error. - * * Applications are allowed to cache lookup results based on the - * URL, or have them precompiled into a binary to avoid any - * lookup. Therefore, binary compatibility needs to be preserved - * on changes to types. (Use versioned type names to manage - * breaking changes.) - * - * Schemes other than `http`, `https` (or the empty scheme) might be - * used with implementation specific semantics. - * - * @property {string} value - * Must be a valid serialized protocol buffer of the above specified type. - * - * @typedef Any - * @memberof google.protobuf - * @see [google.protobuf.Any definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto} - */ -var Any = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_empty.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_empty.js deleted file mode 100644 index 0e293775..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_empty.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * A generic empty message that you can re-use to avoid defining duplicated - * empty messages in your APIs. A typical example is to use it as the request - * or the response type of an API method. For instance: - * - * service Foo { - * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); - * } - * - * The JSON representation for `Empty` is empty JSON object `{}`. - * @typedef Empty - * @memberof google.protobuf - * @see [google.protobuf.Empty definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/empty.proto} - */ -var Empty = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_timestamp.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_timestamp.js deleted file mode 100644 index ec7a9559..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_timestamp.js +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * A Timestamp represents a point in time independent of any time zone - * or calendar, represented as seconds and fractions of seconds at - * nanosecond resolution in UTC Epoch time. It is encoded using the - * Proleptic Gregorian Calendar which extends the Gregorian calendar - * backwards to year one. It is encoded assuming all minutes are 60 - * seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from - * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * By restricting to that range, we ensure that we can convert to - * and from RFC 3339 date strings. - * See - * [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). - * - * # Examples - * - * Example 1: Compute Timestamp from POSIX `time()`. - * - * Timestamp timestamp; - * timestamp.set_seconds(time(NULL)); - * timestamp.set_nanos(0); - * - * Example 2: Compute Timestamp from POSIX `gettimeofday()`. - * - * struct timeval tv; - * gettimeofday(&tv, NULL); - * - * Timestamp timestamp; - * timestamp.set_seconds(tv.tv_sec); - * timestamp.set_nanos(tv.tv_usec * 1000); - * - * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. - * - * FILETIME ft; - * GetSystemTimeAsFileTime(&ft); - * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; - * - * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z - * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. - * Timestamp timestamp; - * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); - * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); - * - * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. - * - * long millis = System.currentTimeMillis(); - * - * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) - * .setNanos((int) ((millis % 1000) * 1000000)).build(); - * - * - * Example 5: Compute Timestamp from current time in Python. - * - * timestamp = Timestamp() - * timestamp.GetCurrentTime() - * - * # JSON Mapping - * - * In JSON format, the Timestamp type is encoded as a string in the - * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the - * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" - * where {year} is always expressed using four digits while {month}, {day}, - * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional - * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), - * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone - * is required, though only UTC (as indicated by "Z") is presently supported. - * - * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past - * 01:30 UTC on January 15, 2017. - * - * In JavaScript, one can convert a Date object to this format using the - * standard - * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] - * method. In Python, a standard `datetime.datetime` object can be converted - * to this format using - * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with - * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use - * the Joda Time's [`ISODateTimeFormat.dateTime()`](https://cloud.google.com - * http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) - * to obtain a formatter capable of generating timestamps in this format. - * - * @property {number} seconds - * Represents seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * - * @property {number} nanos - * Non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions must still have non-negative nanos values - * that count forward in time. Must be from 0 to 999,999,999 - * inclusive. - * - * @typedef Timestamp - * @memberof google.protobuf - * @see [google.protobuf.Timestamp definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto} - */ -var Timestamp = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_wrappers.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_wrappers.js deleted file mode 100644 index a9125aa7..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/protobuf/doc_wrappers.js +++ /dev/null @@ -1,151 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * Wrapper message for `double`. - * - * The JSON representation for `DoubleValue` is JSON number. - * - * @property {number} value - * The double value. - * - * @typedef DoubleValue - * @memberof google.protobuf - * @see [google.protobuf.DoubleValue definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var DoubleValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `float`. - * - * The JSON representation for `FloatValue` is JSON number. - * - * @property {number} value - * The float value. - * - * @typedef FloatValue - * @memberof google.protobuf - * @see [google.protobuf.FloatValue definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var FloatValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `int64`. - * - * The JSON representation for `Int64Value` is JSON string. - * - * @property {number} value - * The int64 value. - * - * @typedef Int64Value - * @memberof google.protobuf - * @see [google.protobuf.Int64Value definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var Int64Value = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `uint64`. - * - * The JSON representation for `UInt64Value` is JSON string. - * - * @property {number} value - * The uint64 value. - * - * @typedef UInt64Value - * @memberof google.protobuf - * @see [google.protobuf.UInt64Value definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var UInt64Value = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `int32`. - * - * The JSON representation for `Int32Value` is JSON number. - * - * @property {number} value - * The int32 value. - * - * @typedef Int32Value - * @memberof google.protobuf - * @see [google.protobuf.Int32Value definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var Int32Value = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `uint32`. - * - * The JSON representation for `UInt32Value` is JSON number. - * - * @property {number} value - * The uint32 value. - * - * @typedef UInt32Value - * @memberof google.protobuf - * @see [google.protobuf.UInt32Value definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var UInt32Value = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `bool`. - * - * The JSON representation for `BoolValue` is JSON `true` and `false`. - * - * @property {boolean} value - * The bool value. - * - * @typedef BoolValue - * @memberof google.protobuf - * @see [google.protobuf.BoolValue definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var BoolValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `string`. - * - * The JSON representation for `StringValue` is JSON string. - * - * @property {string} value - * The string value. - * - * @typedef StringValue - * @memberof google.protobuf - * @see [google.protobuf.StringValue definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var StringValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; -/** - * Wrapper message for `bytes`. - * - * The JSON representation for `BytesValue` is JSON string. - * - * @property {string} value - * The bytes value. - * - * @typedef BytesValue - * @memberof google.protobuf - * @see [google.protobuf.BytesValue definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto} - */ -var BytesValue = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/rpc/doc_status.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/rpc/doc_status.js deleted file mode 100644 index 239d7b77..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/doc/google/rpc/doc_status.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. -/** - * The `Status` type defines a logical error model that is suitable for - * different programming environments, including REST APIs and RPC APIs. It is - * used by [gRPC](https://github.com/grpc). The error model is designed to be: - * - * - Simple to use and understand for most users - * - Flexible enough to meet unexpected needs - * - * # Overview - * - * The `Status` message contains three pieces of data: error code, error - * message, and error details. The error code should be an enum value of - * google.rpc.Code, but it may accept additional error codes if needed. The - * error message should be a developer-facing English message that helps - * developers *understand* and *resolve* the error. If a localized user-facing - * error message is needed, put the localized message in the error details or - * localize it in the client. The optional error details may contain arbitrary - * information about the error. There is a predefined set of error detail types - * in the package `google.rpc` that can be used for common error conditions. - * - * # Language mapping - * - * The `Status` message is the logical representation of the error model, but it - * is not necessarily the actual wire format. When the `Status` message is - * exposed in different client libraries and different wire protocols, it can be - * mapped differently. For example, it will likely be mapped to some exceptions - * in Java, but more likely mapped to some error codes in C. - * - * # Other uses - * - * The error model and the `Status` message can be used in a variety of - * environments, either with or without APIs, to provide a - * consistent developer experience across different environments. - * - * Example uses of this error model include: - * - * - Partial errors. If a service needs to return partial errors to the client, - * it may embed the `Status` in the normal response to indicate the partial - * errors. - * - * - Workflow errors. A typical workflow has multiple steps. Each step may - * have a `Status` message for error reporting. - * - * - Batch operations. If a client uses batch request and batch response, the - * `Status` message should be used directly inside batch response, one for - * each error sub-response. - * - * - Asynchronous operations. If an API call embeds asynchronous operation - * results in its response, the status of those operations should be - * represented directly using the `Status` message. - * - * - Logging. If some API errors are stored in logs, the message `Status` could - * be used directly after any stripping needed for security/privacy reasons. - * - * @property {number} code - * The status code, which should be an enum value of google.rpc.Code. - * - * @property {string} message - * A developer-facing error message, which should be in English. Any - * user-facing error message should be localized and sent in the - * google.rpc.Status.details field, or localized by the client. - * - * @property {Object[]} details - * A list of messages that carry the error details. There is a common set of - * message types for APIs to use. - * - * This object should have the same structure as [Any]{@link - * google.protobuf.Any} - * - * @typedef Status - * @memberof google.rpc - * @see [google.rpc.Status definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto} - */ -var Status = { -// This is for documentation. Actual contents will be loaded by gRPC. -}; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js deleted file mode 100644 index 8d869406..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client.js +++ /dev/null @@ -1,1398 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -'use strict'; -const gapicConfig = require('./firestore_client_config'); -const gax = require('google-gax'); -const merge = require('lodash.merge'); -const path = require('path'); -const VERSION = require('../../../package.json').version; -/** - * The Cloud Firestore service. - * - * This service exposes several types of comparable timestamps: - * - * * `create_time` - The time at which a document was created. Changes only - * when a document is deleted, then re-created. Increases in a strict - * monotonic fashion. - * * `update_time` - The time at which a document was last updated. Changes - * every time a document is modified. Does not change when a write results - * in no modifications. Increases in a strict monotonic fashion. - * * `read_time` - The time at which a particular state was observed. Used - * to denote a consistent snapshot of the database or the time at which a - * Document was observed to not exist. - * * `commit_time` - The time at which the writes in a transaction were - * committed. Any read with an equal or greater `read_time` is guaranteed - * to see the effects of the transaction. - * - * @class - * @memberof v1beta1 - */ -class FirestoreClient { - /** - * Construct an instance of FirestoreClient. - * - * @param {object} [options] - The configuration object. See the subsequent - * parameters for more details. - * @param {object} [options.credentials] - Credentials object. - * @param {string} [options.credentials.client_email] - * @param {string} [options.credentials.private_key] - * @param {string} [options.email] - Account email address. Required when - * using a .pem or .p12 keyFilename. - * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or - * .p12 key downloaded from the Google Developers Console. If you provide - * a path to a JSON file, the projectId option below is not necessary. - * NOTE: .pem and .p12 require you to specify options.email as well. - * @param {number} [options.port] - The port on which to connect to - * the remote host. - * @param {string} [options.projectId] - The project ID from the Google - * Developer's Console, e.g. 'grape-spaceship-123'. We will also check - * the environment variable GCLOUD_PROJECT for your project ID. If your - * app is running in an environment which supports - * {@link - * https://developers.google.com/identity/protocols/application-default-credentials - * Application Default Credentials}, your project ID will be detected - * automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. - * @param {string} [options.servicePath] - The domain name of the - * API remote host. - */ - constructor(opts) { - this._descriptors = {}; - // Ensure that options include the service address and port. - opts = Object.assign({ - clientConfig: {}, - port: this.constructor.port, - servicePath: this.constructor.servicePath, - }, opts); - // Create a `gaxGrpc` object, with any grpc-specific options - // sent to the client. - opts.scopes = this.constructor.scopes; - var gaxGrpc = new gax.GrpcClient(opts); - // Save the auth object to the client, for use by other methods. - this.auth = gaxGrpc.auth; - // Determine the client header string. - var clientHeader = [ - `gl-node/${process.version}`, - `grpc/${gaxGrpc.grpcVersion}`, - `gax/${gax.version}`, - `gapic/${VERSION}`, - ]; - if (opts.libName && opts.libVersion) { - clientHeader.push(`${opts.libName}/${opts.libVersion}`); - } - // Load the applicable protos. - var protos = merge({}, gaxGrpc.loadProto(path.join(__dirname, '..', '..', 'protos'), 'google/firestore/v1beta1/firestore.proto')); - // This API contains "path templates"; forward-slash-separated - // identifiers to uniquely identify resources within the API. - // Create useful helper objects for these. - this._pathTemplates = { - databaseRootPathTemplate: new gax.PathTemplate('projects/{project}/databases/{database}'), - documentRootPathTemplate: new gax.PathTemplate('projects/{project}/databases/{database}/documents'), - documentPathPathTemplate: new gax.PathTemplate('projects/{project}/databases/{database}/documents/{document_path=**}'), - anyPathPathTemplate: new gax.PathTemplate('projects/{project}/databases/{database}/documents/{document}/{any_path=**}'), - }; - // Some of the methods on this service return "paged" results, - // (e.g. 50 results at a time, with tokens to get subsequent - // pages). Denote the keys used for pagination and results. - this._descriptors.page = { - listDocuments: new gax.PageDescriptor('pageToken', 'nextPageToken', 'documents'), - listCollectionIds: new gax.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds'), - }; - // Some of the methods on this service provide streaming responses. - // Provide descriptors for these. - this._descriptors.stream = { - batchGetDocuments: new gax.StreamDescriptor(gax.StreamType.SERVER_STREAMING), - runQuery: new gax.StreamDescriptor(gax.StreamType.SERVER_STREAMING), - write: new gax.StreamDescriptor(gax.StreamType.BIDI_STREAMING), - listen: new gax.StreamDescriptor(gax.StreamType.BIDI_STREAMING), - }; - // Put together the default options sent with requests. - var defaults = gaxGrpc.constructSettings('google.firestore.v1beta1.Firestore', gapicConfig, opts.clientConfig, { 'x-goog-api-client': clientHeader.join(' ') }); - // Set up a dictionary of "inner API calls"; the core implementation - // of calling the API is handled in `google-gax`, with this code - // merely providing the destination and request information. - this._innerApiCalls = {}; - // Put together the "service stub" for - // google.firestore.v1beta1.Firestore. - var firestoreStub = gaxGrpc.createStub(protos.google.firestore.v1beta1.Firestore, opts); - // Iterate over each of the methods that the service provides - // and create an API call method for each. - var firestoreStubMethods = [ - 'getDocument', - 'listDocuments', - 'createDocument', - 'updateDocument', - 'deleteDocument', - 'batchGetDocuments', - 'beginTransaction', - 'commit', - 'rollback', - 'runQuery', - 'write', - 'listen', - 'listCollectionIds', - ]; - for (let methodName of firestoreStubMethods) { - this._innerApiCalls[methodName] = gax.createApiCall(firestoreStub.then(stub => function () { - var args = Array.prototype.slice.call(arguments, 0); - return stub[methodName].apply(stub, args); - }), defaults[methodName], this._descriptors.page[methodName] || - this._descriptors.stream[methodName]); - } - } - /** - * The DNS address for this API service. - */ - static get servicePath() { - return 'firestore.googleapis.com'; - } - /** - * The port for this API service. - */ - static get port() { - return 443; - } - /** - * The scopes needed to make gRPC calls for every method defined - * in this service. - */ - static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/datastore', - ]; - } - /** - * Return the project ID used by this class. - * @param {function(Error, string)} callback - the callback to - * be called with the current project Id. - */ - getProjectId(callback) { - return this.auth.getProjectId(callback); - } - // ------------------- - // -- Service calls -- - // ------------------- - /** - * Gets a single document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the Document to get. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * @param {Object} [request.mask] - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {string} [request.transaction] - * Reads the document in a transaction. - * @param {Object} [request.readTime] - * Reads the version of the document at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing - * [Document]{@link google.firestore.v1beta1.Document}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link - * google.firestore.v1beta1.Document}. The promise has a method named "cancel" - * which cancels the ongoing API call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedName = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); client.getDocument({name: formattedName}) - * .then(responses => { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); - */ - getDocument(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.getDocument(request, options, callback); - } - /** - * Lists documents. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} request.collectionId - * The collection ID, relative to `parent`, to list. For example: - * `chatrooms` or `messages`. - * @param {number} [request.pageSize] - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {string} [request.orderBy] - * The order to sort results by. For example: `priority desc, name`. - * @param {Object} [request.mask] - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {string} [request.transaction] - * Reads documents in a transaction. - * @param {Object} [request.readTime] - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * @param {boolean} [request.showMissing] - * If the list should show missing documents. A missing document is a - * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, Document.create_time, - * or Document.update_time set. - * - * Requests with `show_missing` may not specify `where` or - * `order_by`. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Array, ?Object, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [Document]{@link - * google.firestore.v1beta1.Document}. - * - * When autoPaginate: false is specified through options, it contains the - * result in a single response. If the response indicates the next page - * exists, the third parameter is set to be used for the next request object. - * The fourth parameter keeps the raw response object of an object - * representing [ListDocumentsResponse]{@link - * google.firestore.v1beta1.ListDocumentsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Document]{@link - * google.firestore.v1beta1.Document}. - * - * When autoPaginate: false is specified through options, the array has - * three elements. The first element is Array of [Document]{@link - * google.firestore.v1beta1.Document} in a single response. The second element - * is the next request object if the response indicates the next page exists, - * or null. The third element is an object representing - * [ListDocumentsResponse]{@link - * google.firestore.v1beta1.ListDocumentsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API - * call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); var collectionId = ''; var request = { parent: - * formattedParent, collectionId: collectionId, - * }; - * - * client.listDocuments(request) - * .then(responses => { - * var resources = responses[0]; - * for (let i = 0; i < resources.length; i += 1) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(err => { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); var collectionId = ''; var request = { parent: - * formattedParent, collectionId: collectionId, - * }; - * - * - * var options = {autoPaginate: false}; - * var callback = responses => { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows that there are more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (let i = 0; i < resources.length; i += 1) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listDocuments(nextRequest, options).then(callback); - * } - * } - * client.listDocuments(request, options) - * .then(callback) - * .catch(err => { - * console.error(err); - * }); - */ - listDocuments(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.listDocuments(request, options, callback); - } - /** - * Equivalent to {@link listDocuments}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listDocuments} continuously - * and invokes the callback registered for 'data' event for each element in - * the responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} request.collectionId - * The collection ID, relative to `parent`, to list. For example: - * `chatrooms` or `messages`. - * @param {number} [request.pageSize] - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {string} [request.orderBy] - * The order to sort results by. For example: `priority desc, name`. - * @param {Object} [request.mask] - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {string} [request.transaction] - * Reads documents in a transaction. - * @param {Object} [request.readTime] - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * @param {boolean} [request.showMissing] - * If the list should show missing documents. A missing document is a - * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, Document.create_time, - * or Document.update_time set. - * - * Requests with `show_missing` may not specify `where` or - * `order_by`. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @returns {Stream} - * An object stream which emits an object representing [Document]{@link - * google.firestore.v1beta1.Document} on 'data' event. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); var collectionId = ''; var request = { parent: - * formattedParent, collectionId: collectionId, - * }; - * client.listDocumentsStream(request) - * .on('data', element => { - * // doThingsWith(element) - * }).on('error', err => { - * console.log(err); - * }); - */ - listDocumentsStream(request, options) { - options = options || {}; - return this._descriptors.page.listDocuments.createStream(this._innerApiCalls.listDocuments, request, options); - } - /** - * Creates a new document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource. For example: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` - * @param {string} request.collectionId - * The collection ID, relative to `parent`, to list. For example: - * `chatrooms`. - * @param {string} request.documentId - * The client-assigned document ID to use for this document. - * - * Optional. If not specified, an ID will be assigned by the service. - * @param {Object} request.document - * The document to create. `name` must not be set. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * @param {Object} [request.mask] - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing - * [Document]{@link google.firestore.v1beta1.Document}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link - * google.firestore.v1beta1.Document}. The promise has a method named "cancel" - * which cancels the ongoing API call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); var collectionId = ''; var documentId = ''; - * var document = {}; - * var request = { - * parent: formattedParent, - * collectionId: collectionId, - * documentId: documentId, - * document: document, - * }; - * client.createDocument(request) - * .then(responses => { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); - */ - createDocument(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.createDocument(request, options, callback); - } - /** - * Updates or inserts a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {Object} request.document - * The updated document. - * Creates the document if it does not already exist. - * - * This object should have the same structure as [Document]{@link - * google.firestore.v1beta1.Document} - * @param {Object} request.updateMask - * The fields to update. - * None of the field paths in the mask may contain a reserved name. - * - * If the document exists on the server and has fields not referenced in the - * mask, they are left unchanged. - * Fields referenced in the mask, but not present in the input document, are - * deleted from the document on the server. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {Object} [request.mask] - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {Object} [request.currentDocument] - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * - * This object should have the same structure as [Precondition]{@link - * google.firestore.v1beta1.Precondition} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing - * [Document]{@link google.firestore.v1beta1.Document}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link - * google.firestore.v1beta1.Document}. The promise has a method named "cancel" - * which cancels the ongoing API call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var document = {}; - * var updateMask = {}; - * var request = { - * document: document, - * updateMask: updateMask, - * }; - * client.updateDocument(request) - * .then(responses => { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); - */ - updateDocument(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.updateDocument(request, options, callback); - } - /** - * Deletes a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The resource name of the Document to delete. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * @param {Object} [request.currentDocument] - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * - * This object should have the same structure as [Precondition]{@link - * google.firestore.v1beta1.Precondition} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error)} [callback] - * The function which will be called with the result of the API call. - * @returns {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API - * call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedName = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); client.deleteDocument({name: - * formattedName}).catch(err => { console.error(err); - * }); - */ - deleteDocument(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.deleteDocument(request, options, callback); - } - /** - * Gets multiple documents. - * - * Documents returned by this method are not guaranteed to be returned in the - * same order that they were requested. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.documents - * The names of the documents to retrieve. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * The request will fail if any of the document is not a child resource of - * the given `database`. Duplicate names will be elided. - * @param {Object} [request.mask] - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * - * This object should have the same structure as [DocumentMask]{@link - * google.firestore.v1beta1.DocumentMask} - * @param {string} [request.transaction] - * Reads documents in a transaction. - * @param {Object} [request.newTransaction] - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * - * This object should have the same structure as [TransactionOptions]{@link - * google.firestore.v1beta1.TransactionOptions} - * @param {Object} [request.readTime] - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @returns {Stream} - * An object stream which emits [BatchGetDocumentsResponse]{@link - * google.firestore.v1beta1.BatchGetDocumentsResponse} on 'data' event. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedDatabase = client.databaseRootPath('[PROJECT]', '[DATABASE]'); - * var documents = []; - * var request = { - * database: formattedDatabase, - * documents: documents, - * }; - * client.batchGetDocuments(request).on('data', response => { - * // doThingsWith(response) - * }); - */ - batchGetDocuments(request, options) { - options = options || {}; - return this._innerApiCalls.batchGetDocuments(request, options); - } - /** - * Starts a new transaction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {Object} [request.options] - * The options for the transaction. - * Defaults to a read-write transaction. - * - * This object should have the same structure as [TransactionOptions]{@link - * google.firestore.v1beta1.TransactionOptions} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing - * [BeginTransactionResponse]{@link - * google.firestore.v1beta1.BeginTransactionResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * [BeginTransactionResponse]{@link - * google.firestore.v1beta1.BeginTransactionResponse}. The promise has a - * method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedDatabase = client.databaseRootPath('[PROJECT]', '[DATABASE]'); - * client.beginTransaction({database: formattedDatabase}) - * .then(responses => { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); - */ - beginTransaction(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.beginTransaction(request, options, callback); - } - /** - * Commits a transaction, while optionally updating documents. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {Object[]} request.writes - * The writes to apply. - * - * Always executed atomically and in order. - * - * This object should have the same structure as [Write]{@link - * google.firestore.v1beta1.Write} - * @param {string} [request.transaction] - * If set, applies all writes in this transaction, and commits it. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing - * [CommitResponse]{@link google.firestore.v1beta1.CommitResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * [CommitResponse]{@link google.firestore.v1beta1.CommitResponse}. The - * promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedDatabase = client.databaseRootPath('[PROJECT]', '[DATABASE]'); - * var writes = []; - * var request = { - * database: formattedDatabase, - * writes: writes, - * }; - * client.commit(request) - * .then(responses => { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); - */ - commit(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.commit(request, options, callback); - } - /** - * Rolls back a transaction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {string} request.transaction - * The transaction to roll back. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error)} [callback] - * The function which will be called with the result of the API call. - * @returns {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API - * call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedDatabase = client.databaseRootPath('[PROJECT]', '[DATABASE]'); - * var transaction = ''; - * var request = { - * database: formattedDatabase, - * transaction: transaction, - * }; - * client.rollback(request).catch(err => { - * console.error(err); - * }); - */ - rollback(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.rollback(request, options, callback); - } - /** - * Runs a query. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {Object} [request.structuredQuery] - * A structured query. - * - * This object should have the same structure as [StructuredQuery]{@link - * google.firestore.v1beta1.StructuredQuery} - * @param {string} [request.transaction] - * Reads documents in a transaction. - * @param {Object} [request.newTransaction] - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * - * This object should have the same structure as [TransactionOptions]{@link - * google.firestore.v1beta1.TransactionOptions} - * @param {Object} [request.readTime] - * Reads documents as they were at the given time. - * This may not be older than 60 seconds. - * - * This object should have the same structure as [Timestamp]{@link - * google.protobuf.Timestamp} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @returns {Stream} - * An object stream which emits [RunQueryResponse]{@link - * google.firestore.v1beta1.RunQueryResponse} on 'data' event. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); client.runQuery({parent: - * formattedParent}).on('data', response => { - * // doThingsWith(response) - * }); - */ - runQuery(request, options) { - options = options || {}; - return this._innerApiCalls.runQuery(request, options); - } - /** - * Streams batches of document updates and deletes, in order. - * - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing [WriteRequest]{@link google.firestore.v1beta1.WriteRequest} - * for write() method, and will emit objects representing - * [WriteResponse]{@link google.firestore.v1beta1.WriteResponse} on 'data' - * event asynchronously. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var stream = client.write().on('data', response => { - * // doThingsWith(response) - * }); - * var formattedDatabase = client.databaseRootPath('[PROJECT]', '[DATABASE]'); - * var request = { - * database: formattedDatabase, - * }; - * // Write request objects. - * stream.write(request); - */ - write(options) { - options = options || {}; - return this._innerApiCalls.write(options); - } - /** - * Listens to changes. - * - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing [ListenRequest]{@link - * google.firestore.v1beta1.ListenRequest} for write() method, and will emit - * objects representing [ListenResponse]{@link - * google.firestore.v1beta1.ListenResponse} on 'data' event asynchronously. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var stream = client.listen().on('data', response => { - * // doThingsWith(response) - * }); - * var formattedDatabase = client.databaseRootPath('[PROJECT]', '[DATABASE]'); - * var request = { - * database: formattedDatabase, - * }; - * // Write request objects. - * stream.write(request); - */ - listen(options) { - options = options || {}; - return this._innerApiCalls.listen(options); - } - /** - * Lists all the collection IDs underneath a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} [request.pageSize] - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @param {function(?Error, ?Array, ?Object, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of string. - * - * When autoPaginate: false is specified through options, it contains the - * result in a single response. If the response indicates the next page - * exists, the third parameter is set to be used for the next request object. - * The fourth parameter keeps the raw response object of an object - * representing [ListCollectionIdsResponse]{@link - * google.firestore.v1beta1.ListCollectionIdsResponse}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of string. - * - * When autoPaginate: false is specified through options, the array has - * three elements. The first element is Array of string in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListCollectionIdsResponse]{@link - * google.firestore.v1beta1.ListCollectionIdsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API - * call. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); - * - * client.listCollectionIds({parent: formattedParent}) - * .then(responses => { - * var resources = responses[0]; - * for (let i = 0; i < resources.length; i += 1) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(err => { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); - * - * - * var options = {autoPaginate: false}; - * var callback = responses => { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows that there are more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (let i = 0; i < resources.length; i += 1) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listCollectionIds(nextRequest, options).then(callback); - * } - * } - * client.listCollectionIds({parent: formattedParent}, options) - * .then(callback) - * .catch(err => { - * console.error(err); - * }); - */ - listCollectionIds(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.listCollectionIds(request, options, callback); - } - /** - * Equivalent to {@link listCollectionIds}, but returns a NodeJS Stream - * object. - * - * This fetches the paged responses for {@link listCollectionIds} continuously - * and invokes the callback registered for 'data' event for each element in - * the responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} [request.pageSize] - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, - * e.g, timeout, retries, paginations, etc. See [gax.CallOptions]{@link - * https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the - * details. - * @returns {Stream} - * An object stream which emits a string on 'data' event. - * - * @example - * - * const firestore = require('firestore.v1beta1'); - * - * var client = new firestore.v1beta1.FirestoreClient({ - * // optional auth parameters. - * }); - * - * var formattedParent = client.anyPathPath('[PROJECT]', '[DATABASE]', - * '[DOCUMENT]', '[ANY_PATH]'); client.listCollectionIdsStream({parent: - * formattedParent}) .on('data', element => { - * // doThingsWith(element) - * }).on('error', err => { - * console.log(err); - * }); - */ - listCollectionIdsStream(request, options) { - options = options || {}; - return this._descriptors.page.listCollectionIds.createStream(this._innerApiCalls.listCollectionIds, request, options); - } - // -------------------- - // -- Path templates -- - // -------------------- - /** - * Return a fully-qualified database_root resource name string. - * - * @param {String} project - * @param {String} database - * @returns {String} - */ - databaseRootPath(project, database) { - return this._pathTemplates.databaseRootPathTemplate.render({ - project: project, - database: database, - }); - } - /** - * Return a fully-qualified document_root resource name string. - * - * @param {String} project - * @param {String} database - * @returns {String} - */ - documentRootPath(project, database) { - return this._pathTemplates.documentRootPathTemplate.render({ - project: project, - database: database, - }); - } - /** - * Return a fully-qualified document_path resource name string. - * - * @param {String} project - * @param {String} database - * @param {String} documentPath - * @returns {String} - */ - documentPathPath(project, database, documentPath) { - return this._pathTemplates.documentPathPathTemplate.render({ - project: project, - database: database, - document_path: documentPath, - }); - } - /** - * Return a fully-qualified any_path resource name string. - * - * @param {String} project - * @param {String} database - * @param {String} document - * @param {String} anyPath - * @returns {String} - */ - anyPathPath(project, database, document, anyPath) { - return this._pathTemplates.anyPathPathTemplate.render({ - project: project, - database: database, - document: document, - any_path: anyPath, - }); - } - /** - * Parse the databaseRootName from a database_root resource. - * - * @param {String} databaseRootName - * A fully-qualified path representing a database_root resources. - * @returns {String} - A string representing the project. - */ - matchProjectFromDatabaseRootName(databaseRootName) { - return this._pathTemplates.databaseRootPathTemplate.match(databaseRootName) - .project; - } - /** - * Parse the databaseRootName from a database_root resource. - * - * @param {String} databaseRootName - * A fully-qualified path representing a database_root resources. - * @returns {String} - A string representing the database. - */ - matchDatabaseFromDatabaseRootName(databaseRootName) { - return this._pathTemplates.databaseRootPathTemplate.match(databaseRootName) - .database; - } - /** - * Parse the documentRootName from a document_root resource. - * - * @param {String} documentRootName - * A fully-qualified path representing a document_root resources. - * @returns {String} - A string representing the project. - */ - matchProjectFromDocumentRootName(documentRootName) { - return this._pathTemplates.documentRootPathTemplate.match(documentRootName) - .project; - } - /** - * Parse the documentRootName from a document_root resource. - * - * @param {String} documentRootName - * A fully-qualified path representing a document_root resources. - * @returns {String} - A string representing the database. - */ - matchDatabaseFromDocumentRootName(documentRootName) { - return this._pathTemplates.documentRootPathTemplate.match(documentRootName) - .database; - } - /** - * Parse the documentPathName from a document_path resource. - * - * @param {String} documentPathName - * A fully-qualified path representing a document_path resources. - * @returns {String} - A string representing the project. - */ - matchProjectFromDocumentPathName(documentPathName) { - return this._pathTemplates.documentPathPathTemplate.match(documentPathName) - .project; - } - /** - * Parse the documentPathName from a document_path resource. - * - * @param {String} documentPathName - * A fully-qualified path representing a document_path resources. - * @returns {String} - A string representing the database. - */ - matchDatabaseFromDocumentPathName(documentPathName) { - return this._pathTemplates.documentPathPathTemplate.match(documentPathName) - .database; - } - /** - * Parse the documentPathName from a document_path resource. - * - * @param {String} documentPathName - * A fully-qualified path representing a document_path resources. - * @returns {String} - A string representing the document_path. - */ - matchDocumentPathFromDocumentPathName(documentPathName) { - return this._pathTemplates.documentPathPathTemplate.match(documentPathName) - .document_path; - } - /** - * Parse the anyPathName from a any_path resource. - * - * @param {String} anyPathName - * A fully-qualified path representing a any_path resources. - * @returns {String} - A string representing the project. - */ - matchProjectFromAnyPathName(anyPathName) { - return this._pathTemplates.anyPathPathTemplate.match(anyPathName).project; - } - /** - * Parse the anyPathName from a any_path resource. - * - * @param {String} anyPathName - * A fully-qualified path representing a any_path resources. - * @returns {String} - A string representing the database. - */ - matchDatabaseFromAnyPathName(anyPathName) { - return this._pathTemplates.anyPathPathTemplate.match(anyPathName).database; - } - /** - * Parse the anyPathName from a any_path resource. - * - * @param {String} anyPathName - * A fully-qualified path representing a any_path resources. - * @returns {String} - A string representing the document. - */ - matchDocumentFromAnyPathName(anyPathName) { - return this._pathTemplates.anyPathPathTemplate.match(anyPathName).document; - } - /** - * Parse the anyPathName from a any_path resource. - * - * @param {String} anyPathName - * A fully-qualified path representing a any_path resources. - * @returns {String} - A string representing the any_path. - */ - matchAnyPathFromAnyPathName(anyPathName) { - return this._pathTemplates.anyPathPathTemplate.match(anyPathName).any_path; - } -} -module.exports = FirestoreClient; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json deleted file mode 100644 index 53a379c2..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/firestore_client_config.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "interfaces": { - "google.firestore.v1beta1.Firestore": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000 - }, - "streaming": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 300000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 86400000, - "total_timeout_millis": 86400000 - } - }, - "methods": { - "GetDocument": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListDocuments": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateDocument": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "UpdateDocument": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "DeleteDocument": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "BatchGetDocuments": { - "timeout_millis": 86400000, - "retry_codes_name": "idempotent", - "retry_params_name": "streaming" - }, - "BeginTransaction": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "Commit": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "Rollback": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "RunQuery": { - "timeout_millis": 86400000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "Write": { - "timeout_millis": 300000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "streaming" - }, - "Listen": { - "timeout_millis": 86400000, - "retry_codes_name": "idempotent", - "retry_params_name": "streaming" - }, - "ListCollectionIds": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js b/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js deleted file mode 100644 index b79e5885..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/v1beta1/index.js +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var firestoreClient = require('./firestore_client'); -var gax = require('google-gax'); -var extend = require('extend'); -function v1beta1(options) { - options = extend({ - scopes: v1beta1.ALL_SCOPES, - }, options); - var gaxGrpc = new gax.GrpcClient(options); - return new firestoreClient(gaxGrpc); -} -v1beta1.SERVICE_ADDRESS = firestoreClient.SERVICE_ADDRESS; -v1beta1.ALL_SCOPES = firestoreClient.ALL_SCOPES; -module.exports = v1beta1; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/validate.js b/functions/node_modules/@google-cloud/firestore/build/src/validate.js deleted file mode 100644 index 97af36ee..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/validate.js +++ /dev/null @@ -1,184 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const is = __importStar(require("is")); -/** - * Formats the given word as plural conditionally given the preceding number. - * - * @private - */ -function formatPlural(num, str) { - return `${num} ${str}` + (num === 1 ? '' : 's'); -} -/** - * Provides argument validation for the Firestore Public API. Exposes validators - * for strings, integers, numbers, objects and functions by default and can be - * extended to provide custom validators. - * - * The exported validation functions follow the naming convention is{Type} and - * isOptional{Type}, such as "isString" and "isOptionalString". - * - * To register custom validators, invoke the constructor with with a mapping - * from type names to validation functions. Validation functions return 'true' - * for valid inputs and may throw errors with custom validation messages for - * easier diagnosis. - * - * @private - */ -class Validator { - /** - * Create a new Validator, optionally registering the custom validators as - * provided. - * - * @param customValidators A list of custom validators to register. - */ - constructor(customValidators) { - const validators = Object.assign({ - function: is.function, - integer: (value, min, max) => { - min = is.defined(min) ? min : -Infinity; - max = is.defined(max) ? max : Infinity; - if (!is.integer(value)) { - return false; - } - if (value < min || value > max) { - throw new Error(`Value must be within [${min}, ${max}] inclusive, but was: ${value}`); - } - return true; - }, - number: (value, min, max) => { - min = is.defined(min) ? min : -Infinity; - max = is.defined(max) ? max : Infinity; - if (!is.number(value) || is.nan(value)) { - return false; - } - if (value < min || value > max) { - throw new Error(`Value must be within [${min}, ${max}] inclusive, but was: ${value}`); - } - return true; - }, - object: is.object, - string: is.string, - boolean: is.boolean - }, customValidators); - const register = type => { - const camelCase = type.substring(0, 1).toUpperCase() + type.substring(1); - this[`is${camelCase}`] = (argumentName, ...values) => { - let valid = false; - let message = is.number(argumentName) ? - `Argument at index ${argumentName} is not a valid ${type}.` : - `Argument "${argumentName}" is not a valid ${type}.`; - try { - valid = validators[type].call(null, ...values); - } - catch (err) { - message += ` ${err.message}`; - } - if (valid !== true) { - throw new Error(message); - } - }; - this[`isOptional${camelCase}`] = function (argumentName, value) { - if (is.defined(value)) { - this[`is${camelCase}`].apply(null, arguments); - } - }; - }; - for (const type in validators) { - if (validators.hasOwnProperty(type)) { - register(type); - } - } - } - /** - * Verifies that 'args' has at least 'minSize' elements. - * - * @param {string} funcName - The function name to use in the error message. - * @param {Array.<*>} args - The array (or array-like structure) to verify. - * @param {number} minSize - The minimum number of elements to enforce. - * @throws if the expectation is not met. - * @returns {boolean} 'true' when the minimum number of elements is available. - */ - minNumberOfArguments(funcName, args, minSize) { - if (args.length < minSize) { - throw new Error(`Function '${funcName}()' requires at least ` + - `${formatPlural(minSize, 'argument')}.`); - } - return true; - } - /** - * Verifies that 'args' has at most 'maxSize' elements. - * - * @param {string} funcName - The function name to use in the error message. - * @param {Array.<*>} args - The array (or array-like structure) to verify. - * @param {number} maxSize - The maximum number of elements to enforce. - * @throws if the expectation is not met. - * @returns {boolean} 'true' when only the maximum number of elements is - * specified. - */ - maxNumberOfArguments(funcName, args, maxSize) { - if (args.length > maxSize) { - throw new Error(`Function '${funcName}()' accepts at most ` + - `${formatPlural(maxSize, 'argument')}.`); - } - return true; - } -} -exports.Validator = Validator; -function customObjectError(val) { - if (is.object(val) && val.constructor.name !== 'Object') { - const typeName = val.constructor.name; - switch (typeName) { - case 'DocumentReference': - case 'FieldPath': - case 'FieldValue': - case 'GeoPoint': - case 'Timestamp': - return new Error(`Detected an object of type "${typeName}" that doesn't match the ` + - 'expected instance. Please ensure that the Firestore types you ' + - 'are using are from the same NPM package.'); - default: - return new Error(`Couldn't serialize object of type "${typeName}". Firestore ` + - 'doesn\'t support JavaScript objects with custom prototypes ' + - '(i.e. objects that were created via the \'new\' operator).'); - } - } - else { - return new Error(`Invalid use of type "${typeof val}" as a Firestore argument.`); - } -} -exports.customObjectError = customObjectError; -/** - * Create a new Validator, optionally registering the custom validators as - * provided. - * - * @private - * @param customValidators A list of custom validators to register. - */ -function createValidator(customValidators) { - // This function exists to change the type of `Validator` to `any` so that - // consumers can call the custom validator functions. - return new Validator(customValidators); -} -exports.createValidator = createValidator; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/watch.js b/functions/node_modules/@google-cloud/firestore/build/src/watch.js deleted file mode 100644 index df243861..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/watch.js +++ /dev/null @@ -1,664 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -const functional_red_black_tree_1 = __importDefault(require("functional-red-black-tree")); -const through2_1 = __importDefault(require("through2")); -const logger_1 = require("./logger"); -const backoff_1 = require("./backoff"); -const timestamp_1 = require("./timestamp"); -const path_1 = require("./path"); -const util_1 = require("./util"); -const document_1 = require("./document"); -const document_change_1 = require("./document-change"); -/*! - * Target ID used by watch. Watch uses a fixed target id since we only support - * one target per stream. - * - * @private - * @type {number} - */ -const WATCH_TARGET_ID = 0x1; -/*! - * The change type for document change events. - */ -const ChangeType = { - added: 'added', - modified: 'modified', - removed: 'removed', -}; -/*! - * List of GRPC Error Codes. - * - * This corresponds to - * {@link https://github.com/grpc/grpc/blob/master/doc/statuscodes.md}. - */ -const GRPC_STATUS_CODE = { - // Not an error; returned on success. - OK: 0, - // The operation was cancelled (typically by the caller). - CANCELLED: 1, - // Unknown error. An example of where this error may be returned is if a - // Status value received from another address space belongs to an error-space - // that is not known in this address space. Also errors raised by APIs that - // do not return enough error information may be converted to this error. - UNKNOWN: 2, - // Client specified an invalid argument. Note that this differs from - // FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are - // problematic regardless of the state of the system (e.g., a malformed file - // name). - INVALID_ARGUMENT: 3, - // Deadline expired before operation could complete. For operations that - // change the state of the system, this error may be returned even if the - // operation has completed successfully. For example, a successful response - // from a server could have been delayed long enough for the deadline to - // expire. - DEADLINE_EXCEEDED: 4, - // Some requested entity (e.g., file or directory) was not found. - NOT_FOUND: 5, - // Some entity that we attempted to create (e.g., file or directory) already - // exists. - ALREADY_EXISTS: 6, - // The caller does not have permission to execute the specified operation. - // PERMISSION_DENIED must not be used for rejections caused by exhausting - // some resource (use RESOURCE_EXHAUSTED instead for those errors). - // PERMISSION_DENIED must not be used if the caller can not be identified - // (use UNAUTHENTICATED instead for those errors). - PERMISSION_DENIED: 7, - // The request does not have valid authentication credentials for the - // operation. - UNAUTHENTICATED: 16, - // Some resource has been exhausted, perhaps a per-user quota, or perhaps the - // entire file system is out of space. - RESOURCE_EXHAUSTED: 8, - // Operation was rejected because the system is not in a state required for - // the operation's execution. For example, directory to be deleted may be - // non-empty, an rmdir operation is applied to a non-directory, etc. - // - // A litmus test that may help a service implementor in deciding - // between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: - // (a) Use UNAVAILABLE if the client can retry just the failing call. - // (b) Use ABORTED if the client should retry at a higher-level - // (e.g., restarting a read-modify-write sequence). - // (c) Use FAILED_PRECONDITION if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, FAILED_PRECONDITION - // should be returned since the client should not retry unless - // they have first fixed up the directory by deleting files from it. - // (d) Use FAILED_PRECONDITION if the client performs conditional - // REST Get/Update/Delete on a resource and the resource on the - // server does not match the condition. E.g., conflicting - // read-modify-write on the same resource. - FAILED_PRECONDITION: 9, - // The operation was aborted, typically due to a concurrency issue like - // sequencer check failures, transaction aborts, etc. - // - // See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, - // and UNAVAILABLE. - ABORTED: 10, - // Operation was attempted past the valid range. E.g., seeking or reading - // past end of file. - // - // Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed - // if the system state changes. For example, a 32-bit file system will - // generate INVALID_ARGUMENT if asked to read at an offset that is not in the - // range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from - // an offset past the current file size. - // - // There is a fair bit of overlap between FAILED_PRECONDITION and - // OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) - // when it applies so that callers who are iterating through a space can - // easily look for an OUT_OF_RANGE error to detect when they are done. - OUT_OF_RANGE: 11, - // Operation is not implemented or not supported/enabled in this service. - UNIMPLEMENTED: 12, - // Internal errors. Means some invariants expected by underlying System has - // been broken. If you see one of these errors, Something is very broken. - INTERNAL: 13, - // The service is currently unavailable. This is a most likely a transient - // condition and may be corrected by retrying with a backoff. - // - // See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, - // and UNAVAILABLE. - UNAVAILABLE: 14, - // Unrecoverable data loss or corruption. - DATA_LOSS: 15, - // Force users to include a default branch: - DO_NOT_USE: -1, -}; -/*! - * The comparator used for document watches (which should always get called with - * the same document). - */ -const DOCUMENT_WATCH_COMPARATOR = (doc1, doc2) => { - assert_1.default(doc1 === doc2, 'Document watches only support one document.'); - return 0; -}; -/** - * @private - * @callback docsCallback - * @returns {Array.} An ordered list of documents. - */ -/** - * @private - * @callback changeCallback - * @returns {Array.} An ordered list of document - * changes. - */ -/** - * onSnapshot() callback that receives the updated query state. - * - * @private - * @callback watchSnapshotCallback - * - * @param {Timestamp} readTime - The time at which this snapshot was obtained. - * @param {number} size - The number of documents in the result set. - * @param {docsCallback} docs - A callback that returns the ordered list of - * documents stored in this snapshot. - * @param {changeCallback} changes - A callback that returns the list of - * changed documents since the last snapshot delivered for this watch. - */ -/** - * Watch provides listen functionality and exposes the 'onSnapshot' observer. It - * can be used with a valid Firestore Listen target. - * - * @class - * @private - */ -class Watch { - /** - * @private - * @hideconstructor - * - * @param {Firestore} firestore The Firestore Database client. - * @param {Object} target - A Firestore 'Target' proto denoting the target to - * listen on. - * @param {function} comparator - A comparator for QueryDocumentSnapshots that - * is used to order the document snapshots returned by this watch. - */ - constructor(firestore, target, comparator) { - this._firestore = firestore; - this._targets = target; - this._comparator = comparator; - this._backoff = new backoff_1.ExponentialBackoff(); - this._requestTag = util_1.requestTag(); - } - /** - * Creates a new Watch instance to listen on DocumentReferences. - * - * @private - * @param {DocumentReference} documentRef - The document - * reference for this watch. - * @returns {Watch} A newly created Watch instance. - */ - static forDocument(documentRef) { - return new Watch(documentRef.firestore, { - documents: { - documents: [documentRef.formattedName], - }, - targetId: WATCH_TARGET_ID, - }, DOCUMENT_WATCH_COMPARATOR); - } - /** - * Creates a new Watch instance to listen on Queries. - * - * @private - * @param {Query} query - The query used for this watch. - * @returns {Watch} A newly created Watch instance. - */ - static forQuery(query) { - return new Watch(query.firestore, { - query: query.toProto(), - targetId: WATCH_TARGET_ID, - }, query.comparator()); - } - /** - * Determines whether an error is considered permanent and should not be - * retried. Errors that don't provide a GRPC error code are always considered - * transient in this context. - * - * @private - * @param {Error} error An error object. - * @return {boolean} Whether the error is permanent. - */ - isPermanentError(error) { - if (error.code === undefined) { - logger_1.logger('Watch.onSnapshot', this._requestTag, 'Unable to determine error code: ', error); - return false; - } - switch (error.code) { - case GRPC_STATUS_CODE.CANCELLED: - case GRPC_STATUS_CODE.UNKNOWN: - case GRPC_STATUS_CODE.DEADLINE_EXCEEDED: - case GRPC_STATUS_CODE.RESOURCE_EXHAUSTED: - case GRPC_STATUS_CODE.INTERNAL: - case GRPC_STATUS_CODE.UNAVAILABLE: - case GRPC_STATUS_CODE.UNAUTHENTICATED: - return false; - default: - return true; - } - } - /** - * Determines whether we need to initiate a longer backoff due to system - * overload. - * - * @private - * @param {Error} error A GRPC Error object that exposes an error code. - * @return {boolean} Whether we need to back off our retries. - */ - isResourceExhaustedError(error) { - return error.code === GRPC_STATUS_CODE.RESOURCE_EXHAUSTED; - } - /** - * Starts a watch and attaches a listener for document change events. - * - * @private - * @param {watchSnapshotCallback} onNext - A callback to be called every time - * a new snapshot is available. - * @param {function(Error)} onError - A callback to be called if the listen - * fails or is cancelled. No further callbacks will occur. - * - * @returns {function()} An unsubscribe function that can be called to cancel - * the snapshot listener. - */ - onSnapshot(onNext, onError) { - let self = this; - // The sorted tree of QueryDocumentSnapshots as sent in the last snapshot. - // We only look at the keys. - let docTree = functional_red_black_tree_1.default(this._comparator); - // A map of document names to QueryDocumentSnapshots for the last sent - // snapshot. - let docMap = new Map(); - // The accumulates map of document changes (keyed by document name) for the - // current snapshot. - let changeMap = new Map(); - // The current state of the query results. - let current = false; - // We need this to track whether we've pushed an initial set of changes, - // since we should push those even when there are no changes, if there \ - // aren't docs. - let hasPushed = false; - // The server assigns and updates the resume token. - let resumeToken = undefined; - // Indicates whether we are interested in data from the stream. Set to false - // in the 'unsubscribe()' callback. - let isActive = true; - // Sentinel value for a document remove. - const REMOVED = {}; - const request = { - database: this._firestore.formattedName, - addTarget: this._targets, - }; - // We may need to replace the underlying stream on reset events. - // This is the one that will be returned and proxy the current one. - const stream = through2_1.default.obj(); - // The current stream to the backend. - let currentStream = null; - /** Helper to clear the docs on RESET or filter mismatch. */ - const resetDocs = function () { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Resetting documents'); - changeMap.clear(); - resumeToken = undefined; - docTree.forEach(snapshot => { - // Mark each document as deleted. If documents are not deleted, they - // will be send again by the server. - changeMap.set(snapshot.ref.formattedName, REMOVED); - }); - current = false; - }; - /** Closes the stream and calls onError() if the stream is still active. */ - const closeStream = function (err) { - if (currentStream) { - currentStream.unpipe(stream); - currentStream.end(); - currentStream = null; - } - stream.end(); - if (isActive) { - isActive = false; - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Invoking onError: ', err); - onError(err); - } - }; - /** - * Re-opens the stream unless the specified error is considered permanent. - * Clears the change map. - */ - const maybeReopenStream = function (err) { - if (isActive && !self.isPermanentError(err)) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Stream ended, re-opening after retryable error: ', err); - request.addTarget.resumeToken = resumeToken; - changeMap.clear(); - if (self.isResourceExhaustedError(err)) { - self._backoff.resetToMax(); - } - resetStream(); - } - else { - closeStream(err); - } - }; - /** Helper to restart the outgoing stream to the backend. */ - const resetStream = function () { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Opening new stream'); - if (currentStream) { - currentStream.unpipe(stream); - currentStream.end(); - currentStream = null; - initStream(); - } - }; - /** - * Initializes a new stream to the backend with backoff. - */ - const initStream = function () { - self._backoff.backoffAndWait().then(() => { - if (!isActive) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Not initializing inactive stream'); - return; - } - // Note that we need to call the internal _listen API to pass additional - // header values in readWriteStream. - self._firestore - .readWriteStream('listen', request, self._requestTag, true) - .then(backendStream => { - if (!isActive) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Closing inactive stream'); - backendStream.end(); - return; - } - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Opened new stream'); - currentStream = backendStream; - currentStream.on('error', err => { - maybeReopenStream(err); - }); - currentStream.on('end', () => { - const err = new Error('Stream ended unexpectedly'); - err.code = GRPC_STATUS_CODE.UNKNOWN; - maybeReopenStream(err); - }); - currentStream.pipe(stream); - currentStream.resume(); - }) - .catch(closeStream); - }); - }; - /** - * Checks if the current target id is included in the list of target ids. - * If no targetIds are provided, returns true. - */ - const affectsTarget = function (targetIds, currentId) { - if (targetIds === undefined || targetIds.length === 0) { - return true; - } - for (let targetId of targetIds) { - if (targetId === currentId) { - return true; - } - } - return false; - }; - /** Splits up document changes into removals, additions, and updates. */ - const extractChanges = function (docMap, changes, readTime) { - let deletes = []; - let adds = []; - let updates = []; - changes.forEach((value, name) => { - if (value === REMOVED) { - if (docMap.has(name)) { - deletes.push(name); - } - } - else if (docMap.has(name)) { - value.readTime = readTime; - updates.push(value.build()); - } - else { - value.readTime = readTime; - adds.push(value.build()); - } - }); - return { deletes, adds, updates }; - }; - /** - * Applies the mutations in changeMap to both the document tree and the - * document lookup map. Modified docMap in-place and returns the updated - * state. - */ - const computeSnapshot = function (docTree, docMap, changes) { - let updatedTree = docTree; - let updatedMap = docMap; - assert_1.default(docTree.length === docMap.size, 'The document tree and document ' + - 'map should have the same number of entries.'); - /** - * Applies a document delete to the document tree and the document map. - * Returns the corresponding DocumentChange event. - */ - const deleteDoc = function (name) { - assert_1.default(updatedMap.has(name), 'Document to delete does not exist'); - let oldDocument = updatedMap.get(name); - let existing = updatedTree.find(oldDocument); - let oldIndex = existing.index; - updatedTree = existing.remove(); - updatedMap.delete(name); - return new document_change_1.DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1); - }; - /** - * Applies a document add to the document tree and the document map. - * Returns the corresponding DocumentChange event. - */ - const addDoc = function (newDocument) { - let name = newDocument.ref.formattedName; - assert_1.default(!updatedMap.has(name), 'Document to add already exists'); - updatedTree = updatedTree.insert(newDocument, null); - let newIndex = updatedTree.find(newDocument).index; - updatedMap.set(name, newDocument); - return new document_change_1.DocumentChange(ChangeType.added, newDocument, -1, newIndex); - }; - /** - * Applies a document modification to the document tree and the document - * map. Returns the DocumentChange event for successful modifications. - */ - const modifyDoc = function (newDocument) { - let name = newDocument.ref.formattedName; - assert_1.default(updatedMap.has(name), 'Document to modify does not exist'); - let oldDocument = updatedMap.get(name); - if (!oldDocument.updateTime.isEqual(newDocument.updateTime)) { - let removeChange = deleteDoc(name); - let addChange = addDoc(newDocument); - return new document_change_1.DocumentChange(ChangeType.modified, newDocument, removeChange.oldIndex, addChange.newIndex); - } - return null; - }; - // Process the sorted changes in the order that is expected by our - // clients (removals, additions, and then modifications). We also need to - // sort the individual changes to assure that oldIndex/newIndex keep - // incrementing. - let appliedChanges = []; - changes.deletes.sort((name1, name2) => { - // Deletes are sorted based on the order of the existing document. - return self._comparator(updatedMap.get(name1), updatedMap.get(name2)); - }); - changes.deletes.forEach(name => { - let change = deleteDoc(name); - if (change) { - appliedChanges.push(change); - } - }); - changes.adds.sort(self._comparator); - changes.adds.forEach(snapshot => { - let change = addDoc(snapshot); - if (change) { - appliedChanges.push(change); - } - }); - changes.updates.sort(self._comparator); - changes.updates.forEach(snapshot => { - let change = modifyDoc(snapshot); - if (change) { - appliedChanges.push(change); - } - }); - assert_1.default(updatedTree.length === updatedMap.size, 'The update document ' + - 'tree and document map should have the same number of entries.'); - return { updatedTree, updatedMap, appliedChanges }; - }; - /** - * Assembles a new snapshot from the current set of changes and invokes the - * user's callback. Clears the current changes on completion. - */ - const push = function (readTime, nextResumeToken) { - let changes = extractChanges(docMap, changeMap, readTime); - let diff = computeSnapshot(docTree, docMap, changes); - if (!hasPushed || diff.appliedChanges.length > 0) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Sending snapshot with %d changes and %d documents', diff.appliedChanges.length, diff.updatedTree.length); - onNext(readTime, diff.updatedTree.length, () => diff.updatedTree.keys, () => diff.appliedChanges); - hasPushed = true; - } - docTree = diff.updatedTree; - docMap = diff.updatedMap; - changeMap.clear(); - resumeToken = nextResumeToken; - }; - /** - * Returns the current count of all documents, including the changes from - * the current changeMap. - */ - const currentSize = function () { - let changes = extractChanges(docMap, changeMap); - return docMap.size + changes.adds.length - changes.deletes.length; - }; - initStream(); - stream - .on('data', proto => { - if (proto.targetChange) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Processing target change'); - const change = proto.targetChange; - const noTargetIds = !change.targetIds || change.targetIds.length === 0; - if (change.targetChangeType === 'NO_CHANGE') { - if (noTargetIds && change.readTime && current) { - // This means everything is up-to-date, so emit the current - // set of docs as a snapshot, if there were changes. - push(timestamp_1.Timestamp.fromProto(change.readTime), change.resumeToken); - } - } - else if (change.targetChangeType === 'ADD') { - if (WATCH_TARGET_ID !== change.targetIds[0]) { - closeStream(Error('Unexpected target ID sent by server')); - } - } - else if (change.targetChangeType === 'REMOVE') { - let code = 13; - let message = 'internal error'; - if (change.cause) { - code = change.cause.code; - message = change.cause.message; - } - // @todo: Surface a .code property on the exception. - closeStream(new Error('Error ' + code + ': ' + message)); - } - else if (change.targetChangeType === 'RESET') { - // Whatever changes have happened so far no longer matter. - resetDocs(); - } - else if (change.targetChangeType === 'CURRENT') { - current = true; - } - else { - closeStream(new Error('Unknown target change type: ' + JSON.stringify(change))); - } - if (change.resumeToken && - affectsTarget(change.targetIds, WATCH_TARGET_ID)) { - this._backoff.reset(); - } - } - else if (proto.documentChange) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Processing change event'); - // No other targetIds can show up here, but we still need to see - // if the targetId was in the added list or removed list. - const targetIds = proto.documentChange.targetIds || []; - const removedTargetIds = proto.documentChange.removedTargetIds || []; - let changed = false; - let removed = false; - for (let i = 0; i < targetIds.length; i++) { - if (targetIds[i] === WATCH_TARGET_ID) { - changed = true; - } - } - for (let i = 0; i < removedTargetIds.length; i++) { - if (removedTargetIds[i] === WATCH_TARGET_ID) { - removed = true; - } - } - const document = proto.documentChange.document; - const name = document.name; - if (changed) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Received document change'); - const snapshot = new document_1.DocumentSnapshot.Builder(); - snapshot.ref = self._firestore.doc(path_1.ResourcePath.fromSlashSeparatedString(name).relativeName); - snapshot.fieldsProto = document.fields || {}; - snapshot.createTime = - timestamp_1.Timestamp.fromProto(document.createTime); - snapshot.updateTime = - timestamp_1.Timestamp.fromProto(document.updateTime); - changeMap.set(name, snapshot); - } - else if (removed) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Received document remove'); - changeMap.set(name, REMOVED); - } - } - else if (proto.documentDelete || proto.documentRemove) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Processing remove event'); - const name = (proto.documentDelete || proto.documentRemove).document; - changeMap.set(name, REMOVED); - } - else if (proto.filter) { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Processing filter update'); - if (proto.filter.count !== currentSize()) { - // We need to remove all the current results. - resetDocs(); - // The filter didn't match, so re-issue the query. - resetStream(); - } - } - else { - closeStream(new Error('Unknown listen response type: ' + JSON.stringify(proto))); - } - }) - .on('end', () => { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Processing stream end'); - if (currentStream) { - // Pass the event on to the underlying stream. - currentStream.end(); - } - }); - return () => { - logger_1.logger('Watch.onSnapshot', self._requestTag, 'Ending stream'); - // Prevent further callbacks. - isActive = false; - onNext = () => { }; - onError = () => { }; - stream.end(); - }; - } -} -exports.Watch = Watch; diff --git a/functions/node_modules/@google-cloud/firestore/build/src/write-batch.js b/functions/node_modules/@google-cloud/firestore/build/src/write-batch.js deleted file mode 100644 index f738e718..00000000 --- a/functions/node_modules/@google-cloud/firestore/build/src/write-batch.js +++ /dev/null @@ -1,510 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -const is_1 = __importDefault(require("is")); -const logger_1 = require("./logger"); -const document_1 = require("./document"); -const path_1 = require("./path"); -const timestamp_1 = require("./timestamp"); -const util_1 = require("./util"); -/*! - * Google Cloud Functions terminates idle connections after two minutes. After - * longer periods of idleness, we issue transactional commits to allow for - * retries. - * - * @type {number} - */ -const GCF_IDLE_TIMEOUT_MS = 110 * 1000; -/** - * A WriteResult wraps the write time set by the Firestore servers on sets(), - * updates(), and creates(). - * - * @class - */ -class WriteResult { - /** - * @private - * @hideconstructor - * - * @param {Timestamp} writeTime - The time of the corresponding document - * write. - */ - constructor(writeTime) { - this._writeTime = writeTime; - } - /** - * The write time as set by the Firestore servers. - * - * @type {Timestamp} - * @name WriteResult#writeTime - * @readonly - * - * @example - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.set({foo: 'bar'}).then(writeResult => { - * console.log(`Document written at: ${writeResult.toDate()}`); - * }); - */ - get writeTime() { - return this._writeTime; - } - /** - * Returns true if this `WriteResult` is equal to the provided value. - * - * @param {*} other The value to compare against. - * @return true if this `WriteResult` is equal to the provided value. - */ - isEqual(other) { - return (this === other || - (is_1.default.instanceof(other, WriteResult) && - this._writeTime.isEqual(other._writeTime))); - } -} -exports.WriteResult = WriteResult; -/** - * A Firestore WriteBatch that can be used to atomically commit multiple write - * operations at once. - * - * @class - */ -class WriteBatch { - /** - * @private - * @hideconstructor - * - * @param {Firestore} firestore - The Firestore Database client. - */ - constructor(firestore) { - this._firestore = firestore; - this._validator = firestore._validator; - this._serializer = firestore._serializer; - this._writes = []; - this._committed = false; - } - /** - * Checks if this write batch has any pending operations. - * - * @private - * @returns {boolean} - */ - get isEmpty() { - return this._writes.length === 0; - } - /** - * Throws an error if this batch has already been committed. - * - * @private - */ - verifyNotCommitted() { - if (this._committed) { - throw new Error('Cannot modify a WriteBatch that has been committed.'); - } - } - /** - * Create a document with the provided object values. This will fail the batch - * if a document exists at its location. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be created. - * @param {DocumentData} data - The object to serialize as the document. - * @returns {WriteBatch} This WriteBatch instance. Used for chaining - * method calls. - * - * @example - * let writeBatch = firestore.batch(); - * let documentRef = firestore.collection('col').doc(); - * - * writeBatch.create(documentRef, {foo: 'bar'}); - * - * writeBatch.commit().then(() => { - * console.log('Successfully executed batch.'); - * }); - */ - create(documentRef, data) { - this._validator.isDocumentReference('documentRef', documentRef); - this._validator.isDocument('data', data, { - allowEmpty: true, - allowDeletes: 'none', - allowTransforms: true, - }); - this.verifyNotCommitted(); - const document = document_1.DocumentSnapshot.fromObject(documentRef, data); - const precondition = new document_1.Precondition({ exists: false }); - const transform = document_1.DocumentTransform.fromObject(documentRef, data); - transform.validate(); - this._writes.push({ - write: !document.isEmpty || transform.isEmpty ? document.toProto() : null, - transform: transform.toProto(this._serializer), - precondition: precondition.toProto(), - }); - return this; - } - /** - * Deletes a document from the database. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be deleted. - * @param {Precondition=} precondition - A precondition to enforce for this - * delete. - * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the - * document was last updated at lastUpdateTime. Fails the batch if the - * document doesn't exist or was last updated at a different time. - * @returns {WriteBatch} This WriteBatch instance. Used for chaining - * method calls. - * - * @example - * let writeBatch = firestore.batch(); - * let documentRef = firestore.doc('col/doc'); - * - * writeBatch.delete(documentRef); - * - * writeBatch.commit().then(() => { - * console.log('Successfully executed batch.'); - * }); - */ - delete(documentRef, precondition) { - this._validator.isDocumentReference('documentRef', documentRef); - this._validator.isOptionalDeletePrecondition('precondition', precondition); - this.verifyNotCommitted(); - const conditions = new document_1.Precondition(precondition); - this._writes.push({ - write: { - delete: documentRef.formattedName, - }, - precondition: conditions.toProto(), - }); - return this; - } - /** - * Write to the document referred to by the provided - * [DocumentReference]{@link DocumentReference}. - * If the document does not exist yet, it will be created. If you pass - * [SetOptions]{@link SetOptions}., the provided data can be merged - * into the existing document. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be set. - * @param {DocumentData} data - The object to serialize as the document. - * @param {SetOptions=} options - An object to configure the set behavior. - * @param {boolean=} options.merge - If true, set() merges the values - * specified in its data argument. Fields omitted from this set() call - * remain untouched. - * @param {Array.=} options.mergeFields - If provided, - * set() only replaces the specified field paths. Any field path that is not - * specified is ignored and remains untouched. - * @returns {WriteBatch} This WriteBatch instance. Used for chaining - * method calls. - * - * @example - * let writeBatch = firestore.batch(); - * let documentRef = firestore.doc('col/doc'); - * - * writeBatch.set(documentRef, {foo: 'bar'}); - * - * writeBatch.commit().then(() => { - * console.log('Successfully executed batch.'); - * }); - */ - set(documentRef, data, options) { - this._validator.isOptionalSetOptions('options', options); - const mergeLeaves = options && options.merge === true; - const mergePaths = options && options.mergeFields; - this._validator.isDocumentReference('documentRef', documentRef); - this._validator.isDocument('data', data, { - allowEmpty: true, - allowDeletes: mergePaths || mergeLeaves ? 'all' : 'none', - allowTransforms: true, - }); - this.verifyNotCommitted(); - let documentMask; - if (mergePaths) { - documentMask = document_1.DocumentMask.fromFieldMask(options.mergeFields); - data = documentMask.applyTo(data); - } - const transform = document_1.DocumentTransform.fromObject(documentRef, data); - transform.validate(); - const document = document_1.DocumentSnapshot.fromObject(documentRef, data); - if (mergePaths) { - documentMask.removeFields(transform.fields); - } - else { - documentMask = document_1.DocumentMask.fromObject(data); - } - const hasDocumentData = !document.isEmpty || !documentMask.isEmpty; - let write; - if (!mergePaths && !mergeLeaves) { - write = document.toProto(); - } - else if (hasDocumentData || transform.isEmpty) { - write = document.toProto(); - write.updateMask = documentMask.toProto(this._serializer); - } - this._writes.push({ - write, - transform: transform.toProto(this._serializer), - }); - return this; - } - /** - * Update fields of the document referred to by the provided - * [DocumentReference]{@link DocumentReference}. If the document - * doesn't yet exist, the update fails and the entire batch will be rejected. - * - * The update() method accepts either an object with field paths encoded as - * keys and field values encoded as values, or a variable number of arguments - * that alternate between field paths and field values. Nested fields can be - * updated by providing dot-separated field path strings or by providing - * FieldPath objects. - * - * A Precondition restricting this update can be specified as the last - * argument. - * - * @param {DocumentReference} documentRef - A reference to the - * document to be updated. - * @param {UpdateData|string|FieldPath} dataOrField - An object - * containing the fields and values with which to update the document - * or the path of the first field to update. - * @param { - * ...(Precondition|*|string|FieldPath)} preconditionOrValues - - * An alternating list of field paths and values to update or a Precondition - * to restrict this update. - * @returns {WriteBatch} This WriteBatch instance. Used for chaining - * method calls. - * - * @example - * let writeBatch = firestore.batch(); - * let documentRef = firestore.doc('col/doc'); - * - * writeBatch.update(documentRef, {foo: 'bar'}); - * - * writeBatch.commit().then(() => { - * console.log('Successfully executed batch.'); - * }); - */ - update(documentRef, dataOrField, preconditionOrValues) { - this._validator.minNumberOfArguments('update', arguments, 2); - this._validator.isDocumentReference('documentRef', documentRef); - this.verifyNotCommitted(); - const updateMap = new Map(); - let precondition = new document_1.Precondition({ exists: true }); - const argumentError = 'Update() requires either a single JavaScript ' + - 'object or an alternating list of field/value pairs that can be ' + - 'followed by an optional precondition.'; - let usesVarargs = is_1.default.string(dataOrField) || is_1.default.instance(dataOrField, path_1.FieldPath); - if (usesVarargs) { - try { - for (let i = 1; i < arguments.length; i += 2) { - if (i === arguments.length - 1) { - this._validator.isUpdatePrecondition(i, arguments[i]); - precondition = new document_1.Precondition(arguments[i]); - } - else { - this._validator.isFieldPath(i, arguments[i]); - this._validator.minNumberOfArguments('update', arguments, i + 1); - this._validator.isFieldValue(i, arguments[i + 1], { - allowDeletes: 'root', - allowTransforms: true, - }); - updateMap.set(path_1.FieldPath.fromArgument(arguments[i]), arguments[i + 1]); - } - } - } - catch (err) { - logger_1.logger('WriteBatch.update', null, 'Varargs validation failed:', err); - // We catch the validation error here and re-throw to provide a better - // error message. - throw new Error(`${argumentError} ${err.message}`); - } - } - else { - try { - this._validator.isDocument('dataOrField', dataOrField, { - allowEmpty: false, - allowDeletes: 'root', - allowTransforms: true, - }); - this._validator.maxNumberOfArguments('update', arguments, 3); - Object.keys(dataOrField).forEach(key => { - this._validator.isFieldPath(key, key); - updateMap.set(path_1.FieldPath.fromArgument(key), dataOrField[key]); - }); - if (is_1.default.defined(preconditionOrValues)) { - this._validator.isUpdatePrecondition('preconditionOrValues', preconditionOrValues); - precondition = new document_1.Precondition(preconditionOrValues); - } - } - catch (err) { - logger_1.logger('WriteBatch.update', null, 'Non-varargs validation failed:', err); - // We catch the validation error here and prefix the error with a custom - // message to describe the usage of update() better. - throw new Error(`${argumentError} ${err.message}`); - } - } - this._validator.isUpdateMap('dataOrField', updateMap); - let document = document_1.DocumentSnapshot.fromUpdateMap(documentRef, updateMap); - let documentMask = document_1.DocumentMask.fromUpdateMap(updateMap); - let write = null; - if (!document.isEmpty || !documentMask.isEmpty) { - write = document.toProto(); - write.updateMask = documentMask.toProto(); - } - let transform = document_1.DocumentTransform.fromUpdateMap(documentRef, updateMap); - transform.validate(); - this._writes.push({ - write: write, - transform: transform.toProto(this._serializer), - precondition: precondition.toProto(), - }); - return this; - } - /** - * Atomically commits all pending operations to the database and verifies all - * preconditions. Fails the entire write if any precondition is not met. - * - * @returns {Promise.>} A Promise that resolves - * when this batch completes. - * - * @example - * let writeBatch = firestore.batch(); - * let documentRef = firestore.doc('col/doc'); - * - * writeBatch.set(documentRef, {foo: 'bar'}); - * - * writeBatch.commit().then(() => { - * console.log('Successfully executed batch.'); - * }); - */ - commit() { - return this.commit_(); - } - /** - * Commit method that takes an optional transaction ID. - * - * @private - * @param {object=} commitOptions Options to use for this commit. - * @param {bytes=} commitOptions.transactionId The transaction ID of this - * commit. - * @param {string=} commitOptions.requestTag A unique client-assigned - * identifier for this request. - * @returns {Promise.>} A Promise that resolves - * when this batch completes. - */ - commit_(commitOptions) { - // Note: We don't call `verifyNotCommitted()` to allow for retries. - let explicitTransaction = commitOptions && commitOptions.transactionId; - let tag = (commitOptions && commitOptions.requestTag) || util_1.requestTag(); - let request = { - database: this._firestore.formattedName, - }; - // On GCF, we periodically force transactional commits to allow for - // request retries in case GCF closes our backend connection. - if (!explicitTransaction && this._shouldCreateTransaction()) { - logger_1.logger('WriteBatch.commit', tag, 'Using transaction for commit'); - return this._firestore.request('beginTransaction', request, tag, true) - .then(resp => { - return this.commit_({ transactionId: resp.transaction }); - }); - } - request.writes = []; - for (let req of this._writes) { - assert_1.default(req.write || req.transform, 'Either a write or transform must be set'); - if (req.precondition) { - (req.write || req.transform).currentDocument = req.precondition; - } - if (req.write) { - request.writes.push(req.write); - } - if (req.transform) { - request.writes.push(req.transform); - } - } - logger_1.logger('WriteBatch.commit', tag, 'Sending %d writes', request.writes.length); - if (explicitTransaction) { - request.transaction = explicitTransaction; - } - this._committed = true; - return this._firestore.request('commit', request, tag).then(resp => { - const writeResults = []; - if (request.writes.length > 0) { - assert_1.default(resp.writeResults instanceof Array && - request.writes.length === resp.writeResults.length, `Expected one write result per operation, but got ${resp.writeResults.length} results for ${request.writes.length} operations.`); - const commitTime = timestamp_1.Timestamp.fromProto(resp.commitTime); - let offset = 0; - for (let i = 0; i < this._writes.length; ++i) { - let writeRequest = this._writes[i]; - // Don't return two write results for a write that contains a - // transform, as the fact that we have to split one write operation - // into two distinct write requests is an implementation detail. - if (writeRequest.write && writeRequest.transform) { - // The document transform is always sent last and produces the - // latest update time. - ++offset; - } - let writeResult = resp.writeResults[i + offset]; - writeResults.push(new WriteResult(writeResult.updateTime ? - timestamp_1.Timestamp.fromProto(writeResult.updateTime) : - commitTime)); - } - } - return writeResults; - }); - } - /** - * Determines whether we should issue a transactional commit. On GCF, this - * happens after two minutes of idleness. - * - * @private - * @returns {boolean} Whether to use a transaction. - */ - _shouldCreateTransaction() { - if (!this._firestore._preferTransactions) { - return false; - } - if (this._firestore._lastSuccessfulRequest) { - let now = new Date().getTime(); - return now - this._firestore._lastSuccessfulRequest > GCF_IDLE_TIMEOUT_MS; - } - return true; - } -} -exports.WriteBatch = WriteBatch; -/*! - * Validates that the update data does not contain any ambiguous field - * definitions (such as 'a.b' and 'a'). - * - * @param {Map.} data - An update map with field/value pairs. - * @returns {boolean} 'true' if the input is a valid update map. - */ -function validateUpdateMap(data) { - const fields = []; - data.forEach((value, key) => { - fields.push(key); - }); - fields.sort((left, right) => left.compareTo(right)); - for (let i = 1; i < fields.length; ++i) { - if (fields[i - 1].isPrefixOf(fields[i])) { - throw new Error(`Field "${fields[i - 1]}" was specified multiple times.`); - } - } - return true; -} -exports.validateUpdateMap = validateUpdateMap; diff --git a/functions/node_modules/@google-cloud/firestore/package.json b/functions/node_modules/@google-cloud/firestore/package.json deleted file mode 100644 index 6e495d55..00000000 --- a/functions/node_modules/@google-cloud/firestore/package.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "_from": "@google-cloud/firestore@^0.16.0", - "_id": "@google-cloud/firestore@0.16.1", - "_inBundle": false, - "_integrity": "sha512-xHb4OdRb0OP0x/8w58WJERtCi9Pr+CsloiUlVAq6fFjSyEcmxgL0V+swE8A/2rI5NGQGwtrN57xwDcis5UM/cQ==", - "_location": "/@google-cloud/firestore", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@google-cloud/firestore@^0.16.0", - "name": "@google-cloud/firestore", - "escapedName": "@google-cloud%2ffirestore", - "scope": "@google-cloud", - "rawSpec": "^0.16.0", - "saveSpec": null, - "fetchSpec": "^0.16.0" - }, - "_requiredBy": [ - "/firebase-admin" - ], - "_resolved": "https://registry.npmjs.org/@google-cloud/firestore/-/firestore-0.16.1.tgz", - "_shasum": "aedba92d428cc78f8a6e3eb6ab59e3c8d906f814", - "_spec": "@google-cloud/firestore@^0.16.0", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\firebase-admin", - "author": { - "name": "Google Inc." - }, - "bugs": { - "url": "https://github.com/googleapis/nodejs-firestore/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Alexander Fenster", - "email": "github@fenster.name" - }, - { - "name": "Bond", - "email": "bondz@users.noreply.github.com" - }, - { - "name": "Jason Dobry", - "email": "jdobry@google.com" - }, - { - "name": "Luke Sneeringer", - "email": "lukesneeringer@google.com" - }, - { - "name": "Sebastian Schmidt", - "email": "mrschmidt@google.com" - }, - { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - }, - { - "name": "greenkeeper[bot]", - "email": "greenkeeper[bot]@users.noreply.github.com" - } - ], - "dependencies": { - "@google-cloud/projectify": "^0.3.0", - "bun": "^0.0.12", - "deep-equal": "^1.0.1", - "extend": "^3.0.1", - "functional-red-black-tree": "^1.0.1", - "google-gax": "^0.18.0", - "google-proto-files": "^0.16.1", - "is": "^3.2.1", - "lodash.merge": "^4.6.1", - "protobufjs": "^6.8.6", - "through2": "^2.0.3" - }, - "deprecated": false, - "description": "Firestore Client Library for Node.js", - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "^2.3.0", - "@types/mocha": "^5.2.3", - "@types/node": "^10.3.5", - "chai": "^4.1.2", - "chai-as-promised": "^7.1.1", - "codecov": "^3.0.2", - "duplexify": "^3.6.0", - "gts": "^0.7.1", - "hard-rejection": "^1.0.0", - "ink-docstrap": "git+https://github.com/docstrap/docstrap.git", - "intelli-espower-loader": "^1.0.1", - "jsdoc": "^3.5.5", - "mocha": "^5.2.0", - "nyc": "^12.0.2", - "power-assert": "^1.6.0", - "proxyquire": "^2.0.1", - "source-map-support": "^0.5.6", - "ts-node": "^7.0.0", - "typescript": "^2.9.2" - }, - "engines": { - "node": ">=6.0.0" - }, - "files": [ - "build/protos", - "build/src", - "types" - ], - "homepage": "https://github.com/googleapis/nodejs-firestore#readme", - "keywords": [ - "google apis client", - "google api client", - "google apis", - "google api", - "google", - "google cloud platform", - "google cloud", - "cloud", - "firestore" - ], - "license": "Apache-2.0", - "main": "./build/src/index.js", - "name": "@google-cloud/firestore", - "repository": { - "type": "git", - "url": "git+https://github.com/googleapis/nodejs-firestore.git" - }, - "scripts": { - "check": "gts check", - "clean": "gts clean", - "codecov": "nyc report --reporter=json && codecov -f .coverage/*.json", - "compile": "tsc -p . && cp -r dev/protos build && cp -r dev/test/fake-certificate.json build/test/fake-certificate.json && cp dev/src/v1beta1/firestore_client_config.json build/src/v1beta1/ && cp dev/conformance/test-definition.proto build/conformance && cp dev/conformance/test-suite.binproto build/conformance", - "conformance": "mocha build/conformance", - "docs": "jsdoc -c .jsdoc.js", - "fix": "gts fix", - "generate-scaffolding": "repo-tools generate all", - "posttest": "npm run check", - "predocs": "npm run compile", - "prepare": "npm run compile", - "pretest-only": "npm run compile", - "system-test": "mocha build/system-test --timeout 600000", - "test": "npm run test-only", - "test-only": "nyc mocha build/test" - }, - "types": "./types/firestore.d.ts", - "version": "0.16.1" -} diff --git a/functions/node_modules/@google-cloud/firestore/types/firestore.d.ts b/functions/node_modules/@google-cloud/firestore/types/firestore.d.ts deleted file mode 100644 index a63baf09..00000000 --- a/functions/node_modules/@google-cloud/firestore/types/firestore.d.ts +++ /dev/null @@ -1,1244 +0,0 @@ -/** - * @fileoverview Firestore Server API. - * - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// tslint:disable - -// Declare a global (ambient) namespace -// (used when not using import statement, but just script include). -declare namespace FirebaseFirestore { - /** - * Document data (for use with `DocumentReference.set()`) consists of fields - * mapped to values. - */ - export type DocumentData = {[field: string]: any}; - - /** - * Update data (for use with `DocumentReference.update()`) consists of field - * paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots - * reference nested fields within the document. - */ - export type UpdateData = {[fieldPath: string]: any}; - - /** - * Sets the log function for all active Firestore instances. - */ - function setLogFunction(logger: (msg:string) => void): void; - - /** - * Settings used to directly configure a `Firestore` instance. - */ - export interface Settings { - /** - * The Firestore Project ID. Can be omitted in environments that support - * `Application Default Credentials` {@see https://cloud.google.com/docs/authentication} - */ - projectId?: string; - - /** - * Local file containing the Service Account credentials. Can be omitted - * in environments that support `Application Default Credentials` - * {@see https://cloud.google.com/docs/authentication} - */ - keyFilename?: string; - - /** - * Enables the use of `Timestamp`s for timestamp fields in - * `DocumentSnapshot`s. - * - * Currently, Firestore returns timestamp fields as `Date` but `Date` only - * supports millisecond precision, which leads to truncation and causes - * unexpected behavior when using a timestamp from a snapshot as a part - * of a subsequent query. - * - * Setting `timestampsInSnapshots` to true will cause Firestore to return - * `Timestamp` values instead of `Date` avoiding this kind of problem. To - * make this work you must also change any code that uses `Date` to use - * `Timestamp` instead. - * - * NOTE: in the future `timestampsInSnapshots: true` will become the - * default and this option will be removed so you should change your code to - * use `Timestamp` now and opt-in to this new behavior as soon as you can. - */ - timestampsInSnapshots?: boolean; - - [key: string]: any; // Accept other properties, such as GRPC settings. - } - - /** - * `Firestore` represents a Firestore Database and is the entry point for all - * Firestore operations. - */ - export class Firestore { - /** - * @param settings - Configuration object. See [Firestore Documentation] - * {@link https://firebase.google.com/docs/firestore/} - */ - public constructor(settings?: Settings); - - /** - * Specifies custom settings to be used to configure the `Firestore` - * instance. Can only be invoked once and before any other Firestore - * method. - * - * If settings are provided via both `settings()` and the `Firestore` - * constructor, both settings objects are merged and any settings provided - * via `settings()` take precedence. - * - * @param {object} settings The settings to use for all Firestore - * operations. - */ - settings(settings: Settings): void; - - /** - * Gets a `CollectionReference` instance that refers to the collection at - * the specified path. - * - * @param collectionPath A slash-separated path to a collection. - * @return The `CollectionReference` instance. - */ - collection(collectionPath: string): CollectionReference; - - /** - * Gets a `DocumentReference` instance that refers to the document at the - * specified path. - * - * @param documentPath A slash-separated path to a document. - * @return The `DocumentReference` instance. - */ - doc(documentPath: string): DocumentReference; - - /** - * Retrieves multiple documents from Firestore. - * - * @param documentRef The `DocumentReferences` to receive. - * @return A Promise that resolves with an array of resulting document - * snapshots. - */ - getAll(...documentRef: DocumentReference[]): Promise; - - /** - * Fetches the root collections that are associated with this Firestore - * database. - * - * @returns A Promise that resolves with an array of CollectionReferences. - */ - getCollections() : Promise; - - /** - * Executes the given updateFunction and commits the changes applied within - * the transaction. - * - * You can use the transaction object passed to 'updateFunction' to read and - * modify Firestore documents under lock. Transactions are committed once - * 'updateFunction' resolves and attempted up to five times on failure. - * - * @param updateFunction The function to execute within the transaction - * context. - * @return If the transaction completed successfully or was explicitly - * aborted (by the updateFunction returning a failed Promise), the Promise - * returned by the updateFunction will be returned here. Else if the - * transaction failed, a rejected Promise with the corresponding failure - * error will be returned. - */ - runTransaction( - updateFunction: (transaction: Transaction) => Promise - ): Promise; - - /** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. - */ - batch(): WriteBatch; - } - - /** - * An immutable object representing a geo point in Firestore. The geo point - * is represented as latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ - export class GeoPoint { - /** - * Creates a new immutable GeoPoint object with the provided latitude and - * longitude values. - * @param latitude The latitude as number between -90 and 90. - * @param longitude The longitude as number between -180 and 180. - */ - constructor(latitude: number, longitude: number); - - readonly latitude: number; - readonly longitude: number; - - /** - * Returns true if this `GeoPoint` is equal to the provided one. - * - * @param other The `GeoPoint` to compare against. - * @return true if this `GeoPoint` is equal to the provided one. - */ - isEqual(other: GeoPoint): boolean; - } - - /** - * A reference to a transaction. - * The `Transaction` object passed to a transaction's updateFunction provides - * the methods to read and write data within the transaction context. See - * `Firestore.runTransaction()`. - */ - export class Transaction { - private constructor(); - - - /** - * Retrieves a query result. Holds a pessimistic lock on all returned - * documents. - * - * @param query A query to execute. - * @return A QuerySnapshot for the retrieved data. - */ - get(query: Query): Promise; - - /** - * Reads the document referenced by the provided `DocumentReference.` - * Holds a pessimistic lock on the returned document. - * - * @param documentRef A reference to the document to be read. - * @return A DocumentSnapshot for the read data. - */ - get(documentRef: DocumentReference): Promise; - - /** - * Retrieves multiple documents from Firestore. Holds a pessimistic lock on - * all returned documents. - * - * @param documentRef The `DocumentReferences` to receive. - * @return A Promise that resolves with an array of resulting document - * snapshots. - */ - getAll(...documentRef: DocumentReference[]): Promise; - - /** - * Create the document referred to by the provided `DocumentReference`. - * The operation will fail the transaction if a document exists at the - * specified location. - * - * @param documentRef A reference to the document to be create. - * @param data The object data to serialize as the document. - * @return This `Transaction` instance. Used for chaining method calls. - */ - create(documentRef: DocumentReference, data: DocumentData): Transaction; - - /** - * Writes to the document referred to by the provided `DocumentReference`. - * If the document does not exist yet, it will be created. If you pass - * `SetOptions`, the provided data can be merged into the existing document. - * - * @param documentRef A reference to the document to be set. - * @param data An object of the fields and values for the document. - * @param options An object to configure the set behavior. - * @return This `Transaction` instance. Used for chaining method calls. - */ - set(documentRef: DocumentReference, data: DocumentData, - options?: SetOptions): Transaction; - - /** - * Updates fields in the document referred to by the provided - * `DocumentReference`. The update will fail if applied to a document that - * does not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings. - * - * @param documentRef A reference to the document to be updated. - * @param data An object containing the fields and values with which to - * update the document. - * @param precondition A Precondition to enforce on this update. - * @return This `Transaction` instance. Used for chaining method calls. - */ - update(documentRef: DocumentReference, data: UpdateData, - precondition?: Precondition): Transaction; - - /** - * Updates fields in the document referred to by the provided - * `DocumentReference`. The update will fail if applied to a document that - * does not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing FieldPath objects. - * - * A `Precondition` restricting this update can be specified as the last - * argument. - * - * @param documentRef A reference to the document to be updated. - * @param field The first field to update. - * @param value The first value - * @param fieldsOrPrecondition An alternating list of field paths and values - * to update, optionally followed by a `Precondition` to enforce on this - * update. - * @return This `Transaction` instance. Used for chaining method calls. - */ - update(documentRef: DocumentReference, field: string|FieldPath, value:any, - ...fieldsOrPrecondition: any[]): Transaction; - - /** - * Deletes the document referred to by the provided `DocumentReference`. - * - * @param documentRef A reference to the document to be deleted. - * @param precondition A Precondition to enforce for this delete. - * @return This `Transaction` instance. Used for chaining method calls. - */ - delete(documentRef: DocumentReference, - precondition?: Precondition): Transaction; - } - - /** - * A write batch, used to perform multiple writes as a single atomic unit. - * - * A `WriteBatch` object can be acquired by calling `Firestore.batch()`. It - * provides methods for adding writes to the write batch. None of the - * writes will be committed (or visible locally) until `WriteBatch.commit()` - * is called. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - */ - export class WriteBatch { - private constructor(); - - /** - * Create the document referred to by the provided `DocumentReference`. The - * operation will fail the batch if a document exists at the specified - * location. - * - * @param documentRef A reference to the document to be created. - * @param data The object data to serialize as the document. - * @return This `WriteBatch` instance. Used for chaining method calls. - */ - create(documentRef: DocumentReference, data: DocumentData): WriteBatch; - - /** - * Write to the document referred to by the provided `DocumentReference`. - * If the document does not exist yet, it will be created. If you pass - * `SetOptions`, the provided data can be merged into the existing document. - * - * @param documentRef A reference to the document to be set. - * @param data An object of the fields and values for the document. - * @param options An object to configure the set behavior. - * @return This `WriteBatch` instance. Used for chaining method calls. - */ - set(documentRef: DocumentReference, data: DocumentData, - options?: SetOptions): WriteBatch; - - /** - * Update fields of the document referred to by the provided - * `DocumentReference`. If the document doesn't yet exist, the update fails - * and the entire batch will be rejected. - * - * Nested fields can be updated by providing dot-separated field path - * strings. - * - * @param documentRef A reference to the document to be updated. - * @param data An object containing the fields and values with which to - * update the document. - * @param precondition A Precondition to enforce on this update. - * @return This `WriteBatch` instance. Used for chaining method calls. - */ - update(documentRef: DocumentReference, data: UpdateData, - precondition?: Precondition): WriteBatch; - - /** - * Updates fields in the document referred to by the provided - * `DocumentReference`. The update will fail if applied to a document that - * does not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing FieldPath objects. - * - * A `Precondition` restricting this update can be specified as the last - * argument. - * - * @param documentRef A reference to the document to be updated. - * @param field The first field to update. - * @param value The first value - * @param fieldsOrPrecondition An alternating list of field paths and values - * to update, optionally followed a `Precondition` to enforce on this update. - * @return This `WriteBatch` instance. Used for chaining method calls. - */ - update(documentRef: DocumentReference, field: string|FieldPath, value:any, - ...fieldsOrPrecondition: any[]): WriteBatch; - - /** - * Deletes the document referred to by the provided `DocumentReference`. - * - * @param documentRef A reference to the document to be deleted. - * @param precondition A Precondition to enforce for this delete. - * @return This `WriteBatch` instance. Used for chaining method calls. - */ - delete(documentRef: DocumentReference, - precondition?: Precondition): WriteBatch; - - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * @return A Promise resolved once all of the writes in the batch have been - * successfully written to the backend as an atomic unit. - */ - commit(): Promise; - } - - /** - * An options object that configures conditional behavior of `update()` and - * `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`. - * Using Preconditions, these calls can be restricted to only apply to - * documents that match the specified restrictions. - */ - export interface Precondition { - /** - * If set, the last update time to enforce. - */ - readonly lastUpdateTime?: Timestamp; - } - - /** - * An options object that configures the behavior of `set()` calls in - * `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be - * configured to perform granular merges instead of overwriting the target - * documents in their entirety. - */ - export interface SetOptions { - /** - * Changes the behavior of a set() call to only replace the values specified - * in its data argument. Fields omitted from the set() call remain - * untouched. - */ - readonly merge?: boolean; - - /** - * Changes the behavior of set() calls to only replace the specified field - * paths. Any field path that is not specified is ignored and remains - * untouched. - * - * It is an error to pass a SetOptions object to a set() call that is - * missing a value for any of the fields specified here. - */ - readonly mergeFields?: (string|FieldPath)[]; - } - - /** - * A WriteResult wraps the write time set by the Firestore servers on `sets()`, - * `updates()`, and `creates()`. - */ - export class WriteResult { - private constructor(); - - /** - * The write time as set by the Firestore servers. - */ - readonly writeTime: Timestamp; - - /** - * Returns true if this `WriteResult` is equal to the provided one. - * - * @param other The `WriteResult` to compare against. - * @return true if this `WriteResult` is equal to the provided one. - */ - isEqual(other: WriteResult): boolean; - } - - /** - * A `DocumentReference` refers to a document location in a Firestore database - * and can be used to write, read, or listen to the location. The document at - * the referenced location may or may not exist. A `DocumentReference` can - * also be used to create a `CollectionReference` to a subcollection. - */ - export class DocumentReference { - private constructor(); - - /** The identifier of the document within its collection. */ - readonly id: string; - - /** - * The `Firestore` for the Firestore database (useful for performing - * transactions, etc.). - */ - readonly firestore: Firestore; - - /** - * A reference to the Collection to which this DocumentReference belongs. - */ - readonly parent: CollectionReference; - - /** - * A string representing the path of the referenced document (relative - * to the root of the database). - */ - readonly path: string; - - /** - * Gets a `CollectionReference` instance that refers to the collection at - * the specified path. - * - * @param collectionPath A slash-separated path to a collection. - * @return The `CollectionReference` instance. - */ - collection(collectionPath: string): CollectionReference; - - /** - * Fetches the subcollections that are direct children of this document. - * - * @returns A Promise that resolves with an array of CollectionReferences. - */ - getCollections() : Promise; - - /** - * Creates a document referred to by this `DocumentReference` with the - * provided object values. The write fails if the document already exists - * - * @param data The object data to serialize as the document. - * @return A Promise resolved with the write time of this create. - */ - create(data: DocumentData): Promise; - - /** - * Writes to the document referred to by this `DocumentReference`. If the - * document does not yet exist, it will be created. If you pass - * `SetOptions`, the provided data can be merged into an existing document. - * - * @param data A map of the fields and values for the document. - * @param options An object to configure the set behavior. - * @return A Promise resolved with the write time of this set. - */ - set(data: DocumentData, options?: SetOptions): Promise; - - /** - * Updates fields in the document referred to by this `DocumentReference`. - * The update will fail if applied to a document that does not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings. - * - * @param data An object containing the fields and values with which to - * update the document. - * @param precondition A Precondition to enforce on this update. - * @return A Promise resolved with the write time of this update. - */ - update(data: UpdateData, precondition?: Precondition): Promise; - - /** - * Updates fields in the document referred to by this `DocumentReference`. - * The update will fail if applied to a document that does not exist. - * - * Nested fields can be updated by providing dot-separated field path - * strings or by providing FieldPath objects. - * - * A `Precondition` restricting this update can be specified as the last - * argument. - * - * @param field The first field to update. - * @param value The first value. - * @param moreFieldsOrPrecondition An alternating list of field paths and - * values to update, optionally followed by a `Precondition` to enforce on - * this update. - * @return A Promise resolved with the write time of this update. - */ - update(field: string|FieldPath, value:any, - ...moreFieldsOrPrecondition: any[]): Promise; - - /** - * Deletes the document referred to by this `DocumentReference`. - * - * @param precondition A Precondition to enforce for this delete. - * @return A Promise resolved with the write time of this delete. - */ - delete(precondition?:Precondition): Promise; - - /** - * Reads the document referred to by this `DocumentReference`. - * - * @return A Promise resolved with a DocumentSnapshot containing the - * current document contents. - */ - get(): Promise; - - /** - * Attaches a listener for DocumentSnapshot events. - * - * @param onNext A callback to be called every time a new `DocumentSnapshot` - * is available. - * @param onError A callback to be called if the listen fails or is - * cancelled. No further callbacks will occur. - * @return An unsubscribe function that can be called to cancel - * the snapshot listener. - */ - onSnapshot(onNext: (snapshot: DocumentSnapshot) => void, - onError?: (error: Error) => void): () => void; - - /** - * Returns true if this `DocumentReference` is equal to the provided one. - * - * @param other The `DocumentReference` to compare against. - * @return true if this `DocumentReference` is equal to the provided one. - */ - isEqual(other: DocumentReference): boolean; - } - - /** - * A `DocumentSnapshot` contains data read from a document in your Firestore - * database. The data can be extracted with `.data()` or `.get()` to - * get a specific field. - * - * For a `DocumentSnapshot` that points to a non-existing document, any data - * access will return 'undefined'. You can use the `exists` property to - * explicitly verify a document's existence. - */ - export class DocumentSnapshot { - protected constructor(); - - /** True if the document exists. */ - readonly exists: boolean; - - /** A `DocumentReference` to the document location. */ - readonly ref: DocumentReference; - - /** - * The ID of the document for which this `DocumentSnapshot` contains data. - */ - readonly id: string; - - /** - * The time the document was created. Not set for documents that don't - * exist. - */ - readonly createTime?: Timestamp; - - /** - * The time the document was last updated (at the time the snapshot was - * generated). Not set for documents that don't exist. - */ - readonly updateTime?: Timestamp; - - /** - * The time this snapshot was read. - */ - readonly readTime: Timestamp; - - /** - * Retrieves all fields in the document as an Object. Returns 'undefined' if - * the document doesn't exist. - * - * @return An Object containing all fields in the document. - */ - data(): DocumentData | undefined; - - /** - * Retrieves the field specified by `fieldPath`. - * - * @param fieldPath The path (e.g. 'foo' or 'foo.bar') to a specific field. - * @return The data at the specified field location or undefined if no such - * field exists in the document. - */ - get(fieldPath: string|FieldPath): any; - - /** - * Returns true if the document's data and path in this `DocumentSnapshot` - * is equal to the provided one. - * - * @param other The `DocumentSnapshot` to compare against. - * @return true if this `DocumentSnapshot` is equal to the provided one. - */ - isEqual(other: DocumentSnapshot): boolean; - } - - /** - * A `QueryDocumentSnapshot` contains data read from a document in your - * Firestore database as part of a query. The document is guaranteed to exist - * and its data can be extracted with `.data()` or `.get()` to get a - * specific field. - * - * A `QueryDocumentSnapshot` offers the same API surface as a - * `DocumentSnapshot`. Since query results contain only existing documents, the - * `exists` property will always be true and `data()` will never return - * 'undefined'. - */ - export class QueryDocumentSnapshot extends DocumentSnapshot { - private constructor(); - - /** - * The time the document was created. - */ - readonly createTime: Timestamp; - - /** - * The time the document was last updated (at the time the snapshot was - * generated). - */ - readonly updateTime: Timestamp; - - /** - * Retrieves all fields in the document as an Object. - * - * @override - * @return An Object containing all fields in the document. - */ - data(): DocumentData; - } - - /** - * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' - * (descending or ascending). - */ - export type OrderByDirection = 'desc' | 'asc'; - - /** - * Filter conditions in a `Query.where()` clause are specified using the - * strings '<', '<=', '==', '>=', '>', and 'array-contains'. - */ - export type WhereFilterOp = '<' | '<=' | '==' | '>=' | '>' | 'array-contains'; - - /** - * A `Query` refers to a Query which you can read or listen to. You can also - * construct refined `Query` objects by adding filters and ordering. - */ - export class Query { - protected constructor(); - - /** - * The `Firestore` for the Firestore database (useful for performing - * transactions, etc.). - */ - readonly firestore: Firestore; - - /** - * Creates and returns a new Query with the additional filter that documents - * must contain the specified field and that its value should satisfy the - * relation constraint provided. - * - * This function returns a new (immutable) instance of the Query (rather - * than modify the existing instance) to impose the filter. - * - * @param fieldPath The path to compare - * @param opStr The operation string (e.g "<", "<=", "==", ">", ">="). - * @param value The value for comparison - * @return The created Query. - */ - where(fieldPath: string|FieldPath, opStr: WhereFilterOp, value: any): Query; - - /** - * Creates and returns a new Query that's additionally sorted by the - * specified field, optionally in descending order instead of ascending. - * - * This function returns a new (immutable) instance of the Query (rather - * than modify the existing instance) to impose the order. - * - * @param fieldPath The field to sort by. - * @param directionStr Optional direction to sort by ('asc' or 'desc'). If - * not specified, order will be ascending. - * @return The created Query. - */ - orderBy( - fieldPath: string|FieldPath, directionStr?: OrderByDirection - ): Query; - - /** - * Creates and returns a new Query that's additionally limited to only - * return up to the specified number of documents. - * - * This function returns a new (immutable) instance of the Query (rather - * than modify the existing instance) to impose the limit. - * - * @param limit The maximum number of items to return. - * @return The created Query. - */ - limit(limit: number): Query; - - /** - * Specifies the offset of the returned results. - * - * This function returns a new (immutable) instance of the Query (rather - * than modify the existing instance) to impose the offset. - * - * @param offset The offset to apply to the Query results. - * @return The created Query. - */ - offset(offset: number): Query; - - /** - * Creates and returns a new Query instance that applies a field mask to - * the result and returns only the specified subset of fields. You can - * specify a list of field paths to return, or use an empty list to only - * return the references of matching documents. - * - * This function returns a new (immutable) instance of the Query (rather - * than modify the existing instance) to impose the field mask. - * - * @param field The field paths to return. - * @return The created Query. - */ - select(...field: (string | FieldPath)[]): Query; - - /** - * Creates and returns a new Query that starts at the provided document - * (inclusive). The starting position is relative to the order of the query. - * The document must contain all of the fields provided in the orderBy of - * this query. - * - * @param snapshot The snapshot of the document to start after. - * @return The created Query. - */ - startAt(snapshot: DocumentSnapshot): Query; - - /** - * Creates and returns a new Query that starts at the provided fields - * relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param fieldValues The field values to start this query at, in order - * of the query's order by. - * @return The created Query. - */ - startAt(...fieldValues: any[]): Query; - - /** - * Creates and returns a new Query that starts after the provided document - * (exclusive). The starting position is relative to the order of the query. - * The document must contain all of the fields provided in the orderBy of - * this query. - * - * @param snapshot The snapshot of the document to start after. - * @return The created Query. - */ - startAfter(snapshot: DocumentSnapshot): Query; - - /** - * Creates and returns a new Query that starts after the provided fields - * relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param fieldValues The field values to start this query after, in order - * of the query's order by. - * @return The created Query. - */ - startAfter(...fieldValues: any[]): Query; - - /** - * Creates and returns a new Query that ends before the provided document - * (exclusive). The end position is relative to the order of the query. The - * document must contain all of the fields provided in the orderBy of this - * query. - * - * @param snapshot The snapshot of the document to end before. - * @return The created Query. - */ - endBefore(snapshot: DocumentSnapshot): Query; - - /** - * Creates and returns a new Query that ends before the provided fields - * relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param fieldValues The field values to end this query before, in order - * of the query's order by. - * @return The created Query. - */ - endBefore(...fieldValues: any[]): Query; - - /** - * Creates and returns a new Query that ends at the provided document - * (inclusive). The end position is relative to the order of the query. The - * document must contain all of the fields provided in the orderBy of this - * query. - * - * @param snapshot The snapshot of the document to end at. - * @return The created Query. - */ - endAt(snapshot: DocumentSnapshot): Query; - - /** - * Creates and returns a new Query that ends at the provided fields - * relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param fieldValues The field values to end this query at, in order - * of the query's order by. - * @return The created Query. - */ - endAt(...fieldValues: any[]): Query; - - /** - * Executes the query and returns the results as a `QuerySnapshot`. - * - * @return A Promise that will be resolved with the results of the Query. - */ - get(): Promise; - - /* - * Executes the query and returns the results as Node Stream. - * - * @return A stream of QueryDocumentSnapshot. - */ - stream(): NodeJS.ReadableStream; - - /** - * Attaches a listener for `QuerySnapshot `events. - * - * @param onNext A callback to be called every time a new `QuerySnapshot` - * is available. - * @param onError A callback to be called if the listen fails or is - * cancelled. No further callbacks will occur. - * @return An unsubscribe function that can be called to cancel - * the snapshot listener. - */ - onSnapshot(onNext: (snapshot: QuerySnapshot) => void, - onError?: (error: Error) => void) : () => void; - - /** - * Returns true if this `Query` is equal to the provided one. - * - * @param other The `Query` to compare against. - * @return true if this `Query` is equal to the provided one. - */ - isEqual(other: Query): boolean; - } - - /** - * A `QuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects - * representing the results of a query. The documents can be accessed as an - * array via the `docs` property or enumerated using the `forEach` method. The - * number of documents can be determined via the `empty` and `size` - * properties. - */ - export class QuerySnapshot { - private constructor(); - - /** - * The query on which you called `get` or `onSnapshot` in order to get this - * `QuerySnapshot`. - */ - readonly query: Query; - - /** - * An array of the documents that changed since the last snapshot. If this - * is the first snapshot, all documents will be in the list as added - * changes. - */ - readonly docChanges: DocumentChange[]; - - /** An array of all the documents in the QuerySnapshot. */ - readonly docs: QueryDocumentSnapshot[]; - - /** The number of documents in the QuerySnapshot. */ - readonly size: number; - - /** True if there are no documents in the QuerySnapshot. */ - readonly empty: boolean; - - /** The time this query snapshot was obtained. */ - readonly readTime: Timestamp; - - /** - * Enumerates all of the documents in the QuerySnapshot. - * - * @param callback A callback to be called with a `DocumentSnapshot` for - * each document in the snapshot. - * @param thisArg The `this` binding for the callback. - */ - forEach( - callback: (result: QueryDocumentSnapshot) => void, thisArg?: any - ): void; - - /** - * Returns true if the document data in this `QuerySnapshot` is equal to the - * provided one. - * - * @param other The `QuerySnapshot` to compare against. - * @return true if this `QuerySnapshot` is equal to the provided one. - */ - isEqual(other: QuerySnapshot): boolean; - } - - /** - * The type of of a `DocumentChange` may be 'added', 'removed', or 'modified'. - */ - export type DocumentChangeType = 'added' | 'removed' | 'modified'; - - /** - * A `DocumentChange` represents a change to the documents matching a query. - * It contains the document affected and the type of change that occurred. - */ - export interface DocumentChange { - /** The type of change ('added', 'modified', or 'removed'). */ - readonly type: DocumentChangeType; - - /** The document affected by this change. */ - readonly doc: QueryDocumentSnapshot; - - /** - * The index of the changed document in the result set immediately prior to - * this DocumentChange (i.e. supposing that all prior DocumentChange objects - * have been applied). Is -1 for 'added' events. - */ - readonly oldIndex: number; - - /** - * The index of the changed document in the result set immediately after - * this DocumentChange (i.e. supposing that all prior DocumentChange - * objects and the current DocumentChange object have been applied). - * Is -1 for 'removed' events. - */ - readonly newIndex: number; - - /** - * Returns true if the data in this `DocumentChange` is equal to the - * provided one. - * - * @param other The `DocumentChange` to compare against. - * @return true if this `DocumentChange` is equal to the provided one. - */ - isEqual(other: DocumentChange): boolean; - } - - /** - * A `CollectionReference` object can be used for adding documents, getting - * document references, and querying for documents (using the methods - * inherited from `Query`). - */ - export class CollectionReference extends Query { - private constructor(); - - /** The identifier of the collection. */ - readonly id: string; - - /** - * A reference to the containing Document if this is a subcollection, else - * null. - */ - readonly parent: DocumentReference|null; - - /** - * A string representing the path of the referenced collection (relative - * to the root of the database). - */ - readonly path: string; - - /** - * Get a `DocumentReference` for the document within the collection at the - * specified path. If no path is specified, an automatically-generated - * unique ID will be used for the returned DocumentReference. - * - * @param documentPath A slash-separated path to a document. - * @return The `DocumentReference` instance. - */ - doc(documentPath?: string): DocumentReference; - - /** - * Add a new document to this collection with the specified data, assigning - * it a document ID automatically. - * - * @param data An Object containing the data for the new document. - * @return A Promise resolved with a `DocumentReference` pointing to the - * newly created document after it has been written to the backend. - */ - add(data: DocumentData): Promise; - - /** - * Returns true if this `CollectionReference` is equal to the provided one. - * - * @param other The `CollectionReference` to compare against. - * @return true if this `CollectionReference` is equal to the provided one. - */ - isEqual(other: CollectionReference): boolean; - } - - /** - * Sentinel values that can be used when writing document fields with set(), - * create() or update(). - */ - export class FieldValue { - private constructor(); - - /** - * Returns a sentinel used with set(), create() or update() to include a - * server-generated timestamp in the written data. - * - * @return The FieldValue sentinel for use in a call to set(), create() or - * update(). - */ - static serverTimestamp(): FieldValue; - - /** - * Returns a sentinel for use with update() or set() with {merge:true} to - * mark a field for deletion. - * - * @return The FieldValue sentinel for use in a call to set() or update(). - */ - static delete(): FieldValue; - - /** - * Returns a special value that can be used with set(), create() or update() - * that tells the server to union the given elements with any array value - * that already exists on the server. Each specified element that doesn't - * already exist in the array will be added to the end. If the field being - * modified is not already an array it will be overwritten with an array - * containing exactly the specified elements. - * - * @param elements The elements to union into the array. - * @return The FieldValue sentinel for use in a call to set(), create() or - * update(). - */ - static arrayUnion(...elements: any[]): FieldValue; - - /** - * Returns a special value that can be used with set(), create() or update() - * that tells the server to remove the given elements from any array value - * that already exists on the server. All instances of each element - * specified will be removed from the array. If the field being modified is - * not already an array it will be overwritten with an empty array. - * - * @param elements The elements to remove from the array. - * @return The FieldValue sentinel for use in a call to set(), create() or - * update(). - */ - static arrayRemove(...elements: any[]): FieldValue; - - /** - * Returns true if this `FieldValue` is equal to the provided one. - * - * @param other The `FieldValue` to compare against. - * @return true if this `FieldValue` is equal to the provided one. - */ - isEqual(other: FieldValue): boolean; - } - - /** - * A FieldPath refers to a field in a document. The path may consist of a - * single field name (referring to a top-level field in the document), or a - * list of field names (referring to a nested field in the document). - */ - export class FieldPath { - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param fieldNames A list of field names. - */ - constructor(...fieldNames: string[]); - - /** - * Returns a special sentinel FieldPath to refer to the ID of a document. - * It can be used in queries to sort or filter by the document ID. - */ - static documentId(): FieldPath; - - /** - * Returns true if this `FieldPath` is equal to the provided one. - * - * @param other The `FieldPath` to compare against. - * @return true if this `FieldPath` is equal to the provided one. - */ - isEqual(other: FieldPath): boolean; - } - - /** - * A Timestamp represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian - * Calendar which extends the Gregorian calendar backwards to year one. It is - * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are - * "smeared" so that no leap second table is needed for interpretation. Range - * is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * - * @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto - */ - export class Timestamp { - /** - * Creates a new timestamp with the current date, with millisecond precision. - * - * @return A new `Timestamp` representing the current date. - */ - static now(): Timestamp; - - /** - * Creates a new timestamp from the given date. - * - * @param date The date to initialize the `Timestamp` from. - * @return A new `Timestamp` representing the same point in time as the - * given date. - */ - static fromDate(date: Date): Timestamp; - - /** - * Creates a new timestamp from the given number of milliseconds. - * - * @param milliseconds Number of milliseconds since Unix epoch - * 1970-01-01T00:00:00Z. - * @return A new `Timestamp` representing the same point in time as the - * given number of milliseconds. - */ - static fromMillis(milliseconds: number): Timestamp; - - /** - * Creates a new timestamp. - * - * @param seconds The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * @param nanoseconds The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be from - * 0 to 999,999,999 inclusive. - */ - constructor(seconds: number, nanoseconds: number); - - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - readonly seconds: number; - - /** The non-negative fractions of a second at nanosecond resolution. */ - readonly nanoseconds: number; - - /** - * Returns a new `Date` corresponding to this timestamp. This may lose - * precision. - * - * @return JavaScript `Date` object representing the same point in time as - * this `Timestamp`, with millisecond precision. - */ - toDate(): Date; - - /** - * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - * - * @return The point in time corresponding to this timestamp, represented as - * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. - */ - toMillis(): number; - - /** - * Returns true if this `Timestamp` is equal to the provided one. - * - * @param other The `Timestamp` to compare against. - * @return 'true' if this `Timestamp` is equal to the provided one. - */ - isEqual(other: Timestamp): boolean; - } -} - -declare module '@google-cloud/firestore' { - export = FirebaseFirestore; -} diff --git a/functions/node_modules/@google-cloud/projectify/CHANGELOG.md b/functions/node_modules/@google-cloud/projectify/CHANGELOG.md deleted file mode 100644 index e2d389f5..00000000 --- a/functions/node_modules/@google-cloud/projectify/CHANGELOG.md +++ /dev/null @@ -1,58 +0,0 @@ -# Changelog - -[npm history][1] - -[1]: https://www.npmjs.com/package/@google-cloud/projectify?activeTab=versions -## v0.3.2 - -### Bug fixes -- fix: do not replace projectId on stream objects ([#53](https://github.com/googleapis/nodejs-projectify/pull/53)) - -### Dependencies -- chore(deps): update dependency gts to ^0.9.0 ([#52](https://github.com/googleapis/nodejs-projectify/pull/52)) - -### Internal / Testing Changes -- chore: update eslintignore config ([#51](https://github.com/googleapis/nodejs-projectify/pull/51)) -- chore: use latest npm on Windows ([#50](https://github.com/googleapis/nodejs-projectify/pull/50)) -- chore: update CircleCI config ([#49](https://github.com/googleapis/nodejs-projectify/pull/49)) -- chore: include build in eslintignore ([#46](https://github.com/googleapis/nodejs-projectify/pull/46)) - -## v0.3.1 - -### Implementation Changes -- fix: replaceProjectId should not fail when passed a Buffer ([#43](https://github.com/googleapis/nodejs-projectify/pull/43)) - -### Dependencies -- chore(deps): update dependency nyc to v13 ([#13](https://github.com/googleapis/nodejs-projectify/pull/13)) -- chore(deps): lock file maintenance ([#11](https://github.com/googleapis/nodejs-projectify/pull/11)) -- chore(deps): lock file maintenance ([#8](https://github.com/googleapis/nodejs-projectify/pull/8)) -- chore(deps): update dependency typescript to v3 ([#7](https://github.com/googleapis/nodejs-projectify/pull/7)) -- chore(deps): update dependency gts to ^0.8.0 ([#2](https://github.com/googleapis/nodejs-projectify/pull/2)) -- chore(deps): lock file maintenance ([#4](https://github.com/googleapis/nodejs-projectify/pull/4)) -- chore(deps): lock file maintenance ([#3](https://github.com/googleapis/nodejs-projectify/pull/3)) - -### Internal / Testing Changes -- chore: update issue templates ([#40](https://github.com/googleapis/nodejs-projectify/pull/40)) -- chore: remove old issue template ([#38](https://github.com/googleapis/nodejs-projectify/pull/38)) -- build: run tests on node11 ([#37](https://github.com/googleapis/nodejs-projectify/pull/37)) -- chores(build): run codecov on continuous builds ([#34](https://github.com/googleapis/nodejs-projectify/pull/34)) -- chores(build): do not collect sponge.xml from windows builds ([#35](https://github.com/googleapis/nodejs-projectify/pull/35)) -- chore: update new issue template ([#33](https://github.com/googleapis/nodejs-projectify/pull/33)) -- build: fix codecov uploading on Kokoro ([#30](https://github.com/googleapis/nodejs-projectify/pull/30)) -- Update kokoro config ([#28](https://github.com/googleapis/nodejs-projectify/pull/28)) -- Update CI config ([#26](https://github.com/googleapis/nodejs-projectify/pull/26)) -- Don't publish sourcemaps ([#24](https://github.com/googleapis/nodejs-projectify/pull/24)) -- build: prevent system/sample-test from leaking credentials -- Update kokoro config ([#22](https://github.com/googleapis/nodejs-projectify/pull/22)) -- test: remove appveyor config ([#21](https://github.com/googleapis/nodejs-projectify/pull/21)) -- Update CI config ([#20](https://github.com/googleapis/nodejs-projectify/pull/20)) -- Enable prefer-const in the eslint config ([#19](https://github.com/googleapis/nodejs-projectify/pull/19)) -- Enable no-var in eslint ([#18](https://github.com/googleapis/nodejs-projectify/pull/18)) -- Update CI config ([#17](https://github.com/googleapis/nodejs-projectify/pull/17)) -- Add synth and update CI config ([#15](https://github.com/googleapis/nodejs-projectify/pull/15)) -- chore: ignore package-lock.json ([#12](https://github.com/googleapis/nodejs-projectify/pull/12)) -- chore: update renovate config ([#10](https://github.com/googleapis/nodejs-projectify/pull/10)) -- remove that whitespace ([#9](https://github.com/googleapis/nodejs-projectify/pull/9)) -- chore: assert.deelEqual => assert.deepStrictEqual ([#6](https://github.com/googleapis/nodejs-projectify/pull/6)) -- chore: move mocha options to mocha.opts ([#5](https://github.com/googleapis/nodejs-projectify/pull/5)) - diff --git a/functions/node_modules/@google-cloud/projectify/LICENSE b/functions/node_modules/@google-cloud/projectify/LICENSE deleted file mode 100644 index 7a4a3ea2..00000000 --- a/functions/node_modules/@google-cloud/projectify/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/functions/node_modules/@google-cloud/projectify/README.md b/functions/node_modules/@google-cloud/projectify/README.md deleted file mode 100644 index d87089ea..00000000 --- a/functions/node_modules/@google-cloud/projectify/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Google Cloud Platform logo - -# @google-cloud/projectify -> A simple utility for replacing the projectid token in objects. - -## Contributing - -Contributions welcome! See the [Contributing Guide](https://github.com/googlecloudplatform/google-cloud-node/blob/master/.github/CONTRIBUTING.md). - -## License - -Apache Version 2.0 - -See [LICENSE](https://github.com/googlecloudplatform/google-cloud-node/blob/master/LICENSE) - diff --git a/functions/node_modules/@google-cloud/projectify/build/src/index.d.ts b/functions/node_modules/@google-cloud/projectify/build/src/index.d.ts deleted file mode 100644 index a08837b2..00000000 --- a/functions/node_modules/@google-cloud/projectify/build/src/index.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2014 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Populate the `{{projectId}}` placeholder. - * - * @throws {Error} If a projectId is required, but one is not provided. - * - * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped. - * @param {string} projectId - A projectId. If not provided - * @return {*} - The original argument with all placeholders populated. - */ -export declare function replaceProjectIdToken(value: any, projectId: string): any; -/** - * Custom error type for missing project ID errors. - */ -export declare class MissingProjectIdError extends Error { - message: string; -} diff --git a/functions/node_modules/@google-cloud/projectify/build/src/index.js b/functions/node_modules/@google-cloud/projectify/build/src/index.js deleted file mode 100644 index 96aa4173..00000000 --- a/functions/node_modules/@google-cloud/projectify/build/src/index.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const stream_1 = require("stream"); -/** - * Copyright 2014 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Populate the `{{projectId}}` placeholder. - * - * @throws {Error} If a projectId is required, but one is not provided. - * - * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped. - * @param {string} projectId - A projectId. If not provided - * @return {*} - The original argument with all placeholders populated. - */ -// tslint:disable-next-line:no-any -function replaceProjectIdToken(value, projectId) { - if (Array.isArray(value)) { - value = value.map(v => replaceProjectIdToken(v, projectId)); - } - if (value !== null && typeof value === 'object' && - !(value instanceof Buffer) && !(value instanceof stream_1.Stream) && - typeof value.hasOwnProperty === 'function') { - for (const opt in value) { - if (value.hasOwnProperty(opt)) { - value[opt] = replaceProjectIdToken(value[opt], projectId); - } - } - } - if (typeof value === 'string' && - value.indexOf('{{projectId}}') > -1) { - if (!projectId || projectId === '{{projectId}}') { - throw new MissingProjectIdError(); - } - value = value.replace(/{{projectId}}/g, projectId); - } - return value; -} -exports.replaceProjectIdToken = replaceProjectIdToken; -/** - * Custom error type for missing project ID errors. - */ -class MissingProjectIdError extends Error { - constructor() { - super(...arguments); - this.message = `Sorry, we cannot connect to Cloud Services without a project - ID. You may specify one with an environment variable named - "GOOGLE_CLOUD_PROJECT".`.replace(/ +/g, ' '); - } -} -exports.MissingProjectIdError = MissingProjectIdError; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/functions/node_modules/@google-cloud/projectify/package.json b/functions/node_modules/@google-cloud/projectify/package.json deleted file mode 100644 index 4294998d..00000000 --- a/functions/node_modules/@google-cloud/projectify/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_from": "@google-cloud/projectify@^0.3.0", - "_id": "@google-cloud/projectify@0.3.2", - "_inBundle": false, - "_integrity": "sha512-t1bs5gE105IpgikX7zPCJZzVyXM5xZ/1kJomUPim2E2pNp4OUUFNyvKm/T2aM6GBP2F30o8abCD+/wbOhHWYYA==", - "_location": "/@google-cloud/projectify", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@google-cloud/projectify@^0.3.0", - "name": "@google-cloud/projectify", - "escapedName": "@google-cloud%2fprojectify", - "scope": "@google-cloud", - "rawSpec": "^0.3.0", - "saveSpec": null, - "fetchSpec": "^0.3.0" - }, - "_requiredBy": [ - "/@google-cloud/firestore" - ], - "_resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-0.3.2.tgz", - "_shasum": "ed54c98cae646dc03a742eac288184a13d33a4c2", - "_spec": "@google-cloud/projectify@^0.3.0", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@google-cloud\\firestore", - "author": { - "name": "Google Inc." - }, - "bugs": { - "url": "https://github.com/googleapis/nodejs-projectify/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "A simple utility for replacing the projectid token in objects.", - "devDependencies": { - "@types/mocha": "^5.2.4", - "@types/node": "^10.5.2", - "codecov": "^3.0.4", - "gts": "^0.9.0", - "hard-rejection": "^1.0.0", - "intelli-espower-loader": "^1.0.1", - "mocha": "^5.2.0", - "nyc": "^13.0.0", - "source-map-support": "^0.5.6", - "typescript": "^3.0.0" - }, - "files": [ - "build/src", - "!build/src/**/*.map" - ], - "homepage": "https://github.com/googleapis/nodejs-projectify#readme", - "keywords": [], - "license": "Apache-2.0", - "main": "build/src/index.js", - "name": "@google-cloud/projectify", - "nyc": { - "exclude": [ - "build/test" - ] - }, - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/googleapis/nodejs-projectify.git" - }, - "scripts": { - "clean": "gts clean", - "codecov": "nyc report --reporter=json && codecov -f coverage/*.json", - "compile": "tsc -p .", - "docs": "echo no docs 👻", - "fix": "gts fix", - "lint": "gts check", - "posttest": "npm run lint", - "prepare": "npm run compile", - "presystem-test": "npm run compile", - "pretest": "npm run compile", - "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", - "system-test": "mocha build/system-test", - "test": "npm run test-only", - "test-only": "nyc mocha build/test" - }, - "types": "build/src/index.d.ts", - "version": "0.3.2" -} diff --git a/functions/node_modules/@google-cloud/storage/CONTRIBUTORS b/functions/node_modules/@google-cloud/storage/CONTRIBUTORS deleted file mode 100644 index 883c5b4a..00000000 --- a/functions/node_modules/@google-cloud/storage/CONTRIBUTORS +++ /dev/null @@ -1,26 +0,0 @@ -# The names of individuals who have contributed to this project. -# -# Names are formatted as: -# name -# -Ace Nassri -Alexander Borovykh -Alexander Fenster -Calvin Metcalf -Colin Ihrig -Cristian Almstrand -Dave Gramlich -Dominic Valenciana -Eric Uldall -Ernest Landrito -Frank Natividad -Jason Dobry -Jason Dobry -Justin Sprigg -Luke Sneeringer -Stephen -Stephen Sawchuk -Stephen Sawchuk -Tyler Johnson -Zach Bjornson -greenkeeper[bot] diff --git a/functions/node_modules/@google-cloud/storage/LICENSE b/functions/node_modules/@google-cloud/storage/LICENSE deleted file mode 100644 index 7a4a3ea2..00000000 --- a/functions/node_modules/@google-cloud/storage/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/functions/node_modules/@google-cloud/storage/README.md b/functions/node_modules/@google-cloud/storage/README.md deleted file mode 100644 index 5728fc6d..00000000 --- a/functions/node_modules/@google-cloud/storage/README.md +++ /dev/null @@ -1,134 +0,0 @@ -Google Cloud Platform logo - -# [Google Cloud Storage: Node.js Client](https://github.com/googleapis/nodejs-storage) - -[![release level](https://img.shields.io/badge/release%20level-general%20availability%20%28GA%29-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) -[![CircleCI](https://img.shields.io/circleci/project/github/googleapis/nodejs-storage.svg?style=flat)](https://circleci.com/gh/googleapis/nodejs-storage) -[![AppVeyor](https://ci.appveyor.com/api/projects/status/github/googleapis/nodejs-storage?branch=master&svg=true)](https://ci.appveyor.com/project/googleapis/nodejs-storage) -[![codecov](https://img.shields.io/codecov/c/github/googleapis/nodejs-storage/master.svg?style=flat)](https://codecov.io/gh/googleapis/nodejs-storage) - -> Node.js idiomatic client for [Cloud Storage][product-docs]. - -[Cloud Storage](https://cloud.google.com/storage/docs) allows world-wide storage and retrieval of any amount of data at any time. You can use Google Cloud Storage for a range of scenarios including serving website content, storing data for archival and disaster recovery, or distributing large data objects to users via direct download. - - -* [Cloud Storage Node.js Client API Reference][client-docs] -* [github.com/googleapis/nodejs-storage](https://github.com/googleapis/nodejs-storage) -* [Cloud Storage Documentation][product-docs] - -Read more about the client libraries for Cloud APIs, including the older -Google APIs Client Libraries, in [Client Libraries Explained][explained]. - -[explained]: https://cloud.google.com/apis/docs/client-libraries-explained - -**Table of contents:** - -* [Quickstart](#quickstart) - * [Before you begin](#before-you-begin) - * [Installing the client library](#installing-the-client-library) - * [Using the client library](#using-the-client-library) -* [Samples](#samples) -* [Versioning](#versioning) -* [Contributing](#contributing) -* [License](#license) - -## Quickstart - -### Before you begin - -1. Select or create a Cloud Platform project. - - [Go to the projects page][projects] - -1. Enable billing for your project. - - [Enable billing][billing] - -1. Enable the Google Cloud Storage API. - - [Enable the API][enable_api] - -1. [Set up authentication with a service account][auth] so you can access the - API from your local workstation. - -[projects]: https://console.cloud.google.com/project -[billing]: https://support.google.com/cloud/answer/6293499#enable-billing -[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=storage-api.googleapis.com -[auth]: https://cloud.google.com/docs/authentication/getting-started - -### Installing the client library - - npm install --save @google-cloud/storage - -### Using the client library - -```javascript -// Imports the Google Cloud client library -const Storage = require('@google-cloud/storage'); - -// Your Google Cloud Platform project ID -const projectId = 'YOUR_PROJECT_ID'; - -// Creates a client -const storage = new Storage({ - projectId: projectId, -}); - -// The name for the new bucket -const bucketName = 'my-new-bucket'; - -// Creates the new bucket -storage - .createBucket(bucketName) - .then(() => { - console.log(`Bucket ${bucketName} created.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -``` - -## Samples - -Samples are in the [`samples/`](https://github.com/googleapis/nodejs-storage/tree/master/samples) directory. The samples' `README.md` -has instructions for running the samples. - -| Sample | Source Code | Try it | -| --------------------------- | --------------------------------- | ------ | -| ACL (Access Control Lists) | [source code](https://github.com/googleapis/nodejs-storage/blob/master/samples/acl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/acl.js,samples/README.md) | -| Buckets | [source code](https://github.com/googleapis/nodejs-storage/blob/master/samples/buckets.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/buckets.js,samples/README.md) | -| Encryption | [source code](https://github.com/googleapis/nodejs-storage/blob/master/samples/encryption.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/encryption.js,samples/README.md) | -| Files | [source code](https://github.com/googleapis/nodejs-storage/blob/master/samples/files.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/files.js,samples/README.md) | -| Notifications | [source code](https://github.com/googleapis/nodejs-storage/blob/master/samples/notifications.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/notifications.js,samples/README.md) | -| Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/master/samples/requesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/requesterPays.js,samples/README.md) | - -The [Cloud Storage Node.js Client API Reference][client-docs] documentation -also contains samples. - -## Versioning - -This library follows [Semantic Versioning](http://semver.org/). - -This library is considered to be **General Availability (GA)**. This means it -is stable; the code surface will not change in backwards-incompatible ways -unless absolutely necessary (e.g. because of critical security issues) or with -an extensive deprecation period. Issues and requests against **GA** libraries -are addressed with the highest priority. - -More Information: [Google Cloud Platform Launch Stages][launch_stages] - -[launch_stages]: https://cloud.google.com/terms/launch-stages - -## Contributing - -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-storage/blob/master/.github/CONTRIBUTING.md). - -## License - -Apache Version 2.0 - -See [LICENSE](https://github.com/googleapis/nodejs-storage/blob/master/LICENSE) - -[client-docs]: https://cloud.google.com/nodejs/docs/reference/storage/latest/ -[product-docs]: https://cloud.google.com/storage/docs -[shell_img]: //gstatic.com/cloudssh/images/open-btn.png diff --git a/functions/node_modules/@google-cloud/storage/package.json b/functions/node_modules/@google-cloud/storage/package.json deleted file mode 100644 index 6f8bae6d..00000000 --- a/functions/node_modules/@google-cloud/storage/package.json +++ /dev/null @@ -1,209 +0,0 @@ -{ - "_from": "@google-cloud/storage@^1.6.0", - "_id": "@google-cloud/storage@1.7.0", - "_inBundle": false, - "_integrity": "sha512-QaAxzCkbhspwajoaEnT0GcnQcpjPRcBrHYuQsXtD05BtOJgVnHCLXSsfUiRdU0nVpK+Thp7+sTkQ0fvk5PanKg==", - "_location": "/@google-cloud/storage", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@google-cloud/storage@^1.6.0", - "name": "@google-cloud/storage", - "escapedName": "@google-cloud%2fstorage", - "scope": "@google-cloud", - "rawSpec": "^1.6.0", - "saveSpec": null, - "fetchSpec": "^1.6.0" - }, - "_requiredBy": [ - "/firebase-admin" - ], - "_resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-1.7.0.tgz", - "_shasum": "07bff573d92d5c294db6a04af246688875a8f74b", - "_spec": "@google-cloud/storage@^1.6.0", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\firebase-admin", - "author": { - "name": "Google Inc." - }, - "bugs": { - "url": "https://github.com/googleapis/nodejs-storage/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Ace Nassri", - "email": "anassri@google.com" - }, - { - "name": "Alexander Borovykh", - "email": "immaculate.pine@gmail.com" - }, - { - "name": "Alexander Fenster", - "email": "github@fenster.name" - }, - { - "name": "Calvin Metcalf", - "email": "calvin.metcalf@gmail.com" - }, - { - "name": "Colin Ihrig", - "email": "cjihrig@gmail.com" - }, - { - "name": "Cristian Almstrand", - "email": "almstrand@users.noreply.github.com" - }, - { - "name": "Dave Gramlich", - "email": "callmehiphop@gmail.com" - }, - { - "name": "Dominic Valenciana", - "email": "kiricon@live.com" - }, - { - "name": "Eric Uldall", - "email": "ericuldall@gmail.com" - }, - { - "name": "Ernest Landrito", - "email": "landrito@google.com" - }, - { - "name": "Frank Natividad", - "email": "frankyn@users.noreply.github.com" - }, - { - "name": "Jason Dobry", - "email": "jason.dobry@gmail.com" - }, - { - "name": "Jason Dobry", - "email": "jmdobry@users.noreply.github.com" - }, - { - "name": "Justin Sprigg", - "email": "justin.sprigg@gmail.com" - }, - { - "name": "Luke Sneeringer", - "email": "luke@sneeringer.com" - }, - { - "name": "Stephen", - "email": "stephenplusplus@users.noreply.github.com" - }, - { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - }, - { - "name": "Stephen Sawchuk", - "email": "stephenplusplus@users.noreply.github.com" - }, - { - "name": "Tyler Johnson", - "email": "mail@tyler-johnson.ca" - }, - { - "name": "Zach Bjornson", - "email": "bjornson@stanford.edu" - }, - { - "name": "greenkeeper[bot]", - "email": "greenkeeper[bot]@users.noreply.github.com" - } - ], - "dependencies": { - "@google-cloud/common": "^0.17.0", - "arrify": "^1.0.0", - "async": "^2.0.1", - "compressible": "^2.0.12", - "concat-stream": "^1.5.0", - "create-error-class": "^3.0.2", - "duplexify": "^3.5.0", - "extend": "^3.0.0", - "gcs-resumable-upload": "^0.10.2", - "hash-stream-validation": "^0.2.1", - "is": "^3.0.1", - "mime": "^2.2.0", - "mime-types": "^2.0.8", - "once": "^1.3.1", - "pumpify": "^1.5.1", - "request": "^2.85.0", - "safe-buffer": "^5.1.1", - "snakeize": "^0.1.0", - "stream-events": "^1.0.1", - "through2": "^2.0.0", - "xdg-basedir": "^3.0.0" - }, - "deprecated": false, - "description": "Cloud Storage Client Library for Node.js", - "devDependencies": { - "@google-cloud/nodejs-repo-tools": "^2.2.3", - "@google-cloud/pubsub": "*", - "codecov": "^3.0.0", - "eslint": "^4.7.1", - "eslint-config-prettier": "^2.5.0", - "eslint-plugin-node": "^6.0.0", - "eslint-plugin-prettier": "^2.3.1", - "ink-docstrap": "https://github.com/docstrap/docstrap/tarball/master", - "intelli-espower-loader": "^1.0.1", - "jsdoc": "^3.5.4", - "mocha": "^5.0.0", - "normalize-newline": "^3.0.0", - "nyc": "^11.1.0", - "power-assert": "^1.4.4", - "prettier": "^1.7.0", - "prop-assign": "^1.0.0", - "propprop": "^0.3.0", - "proxyquire": "^2.0.0", - "semistandard": "^12.0.0", - "tmp": "^0.0.33", - "uuid": "^3.1.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "src", - "AUTHORS", - "CONTRIBUTORS", - "COPYING" - ], - "homepage": "https://github.com/googleapis/nodejs-storage#readme", - "keywords": [ - "google apis client", - "google api client", - "google apis", - "google api", - "google", - "google cloud platform", - "google cloud", - "cloud", - "google storage", - "storage" - ], - "license": "Apache-2.0", - "main": "./src/index.js", - "name": "@google-cloud/storage", - "repository": { - "type": "git", - "url": "git+https://github.com/googleapis/nodejs-storage.git" - }, - "scripts": { - "all-test": "npm test && npm run system-test && npm run samples-test", - "cover": "nyc --reporter=lcov mocha --require intelli-espower-loader test/*.js && nyc report", - "docs": "repo-tools exec -- jsdoc -c .jsdoc.js", - "generate-scaffolding": "repo-tools generate all && repo-tools generate lib_samples_readme -l samples/ --config ../.cloud-repo-tools.json", - "lint": "repo-tools lint --cmd eslint -- src/ samples/ system-test/ test/", - "prettier": "repo-tools exec -- prettier --write src/**/*.js samples/*.js samples/**/*.js system-test/**/*.js test/**/*.js", - "samples-test": "npm link && cd samples/ && npm link @google-cloud/storage && npm test && cd ../", - "system-test": "repo-tools test run --cmd mocha -- system-test/ --timeout 600000", - "test": "repo-tools test run --cmd npm -- run cover", - "test-no-cover": "repo-tools test run --cmd mocha -- test/" - }, - "version": "1.7.0" -} diff --git a/functions/node_modules/@google-cloud/storage/src/acl.js b/functions/node_modules/@google-cloud/storage/src/acl.js deleted file mode 100644 index 83600e04..00000000 --- a/functions/node_modules/@google-cloud/storage/src/acl.js +++ /dev/null @@ -1,766 +0,0 @@ -/*! - * Copyright 2014 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const arrify = require('arrify'); -const common = require('@google-cloud/common'); -const extend = require('extend'); -const is = require('is'); -const util = require('util'); - -/** - * Cloud Storage uses access control lists (ACLs) to manage object and - * bucket access. ACLs are the mechanism you use to share objects with other - * users and allow other users to access your buckets and objects. - * - * An ACL consists of one or more entries, where each entry grants permissions - * to an entity. Permissions define the actions that can be performed against an - * object or bucket (for example, `READ` or `WRITE`); the entity defines who the - * permission applies to (for example, a specific user or group of users). - * - * Where an `entity` value is accepted, we follow the format the Cloud Storage - * API expects. - * - * Refer to - * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls - * for the most up-to-date values. - * - * - `user-userId` - * - `user-email` - * - `group-groupId` - * - `group-email` - * - `domain-domain` - * - `project-team-projectId` - * - `allUsers` - * - `allAuthenticatedUsers` - * - * Examples: - * - * - The user "liz@example.com" would be `user-liz@example.com`. - * - The group "example@googlegroups.com" would be - * `group-example@googlegroups.com`. - * - To refer to all members of the Google Apps for Business domain - * "example.com", the entity would be `domain-example.com`. - * - * For more detailed information, see - * [About Access Control Lists](http://goo.gl/6qBBPO). - * - * @constructor Acl - * @mixin - * @param {object} options Configuration options. - */ -function Acl(options) { - AclRoleAccessorMethods.call(this); - - this.pathPrefix = options.pathPrefix; - this.request_ = options.request; -} - -/** - * An object of convenience methods to add or delete owner ACL permissions for a - * given entity. - * - * The supported methods include: - * - * - `myFile.acl.owners.addAllAuthenticatedUsers` - * - `myFile.acl.owners.deleteAllAuthenticatedUsers` - * - `myFile.acl.owners.addAllUsers` - * - `myFile.acl.owners.deleteAllUsers` - * - `myFile.acl.owners.addDomain` - * - `myFile.acl.owners.deleteDomain` - * - `myFile.acl.owners.addGroup` - * - `myFile.acl.owners.deleteGroup` - * - `myFile.acl.owners.addProject` - * - `myFile.acl.owners.deleteProject` - * - `myFile.acl.owners.addUser` - * - `myFile.acl.owners.deleteUser` - * - * @return {object} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * //- - * // Add a user as an owner of a file. - * //- - * const myBucket = gcs.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * myFile.acl.owners.addUser('email@example.com', function(err, aclObject) {}); - * - * //- - * // For reference, the above command is the same as running the following. - * //- - * myFile.acl.add({ - * entity: 'user-email@example.com', - * role: gcs.acl.OWNER_ROLE - * }, function(err, aclObject) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myFile.acl.owners.addUser('email@example.com').then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - */ -Acl.prototype.owners = {}; - -/** - * An object of convenience methods to add or delete reader ACL permissions for - * a given entity. - * - * The supported methods include: - * - * - `myFile.acl.readers.addAllAuthenticatedUsers` - * - `myFile.acl.readers.deleteAllAuthenticatedUsers` - * - `myFile.acl.readers.addAllUsers` - * - `myFile.acl.readers.deleteAllUsers` - * - `myFile.acl.readers.addDomain` - * - `myFile.acl.readers.deleteDomain` - * - `myFile.acl.readers.addGroup` - * - `myFile.acl.readers.deleteGroup` - * - `myFile.acl.readers.addProject` - * - `myFile.acl.readers.deleteProject` - * - `myFile.acl.readers.addUser` - * - `myFile.acl.readers.deleteUser` - * - * @return {object} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * //- - * // Add a user as a reader of a file. - * //- - * myFile.acl.readers.addUser('email@example.com', function(err, aclObject) {}); - * - * //- - * // For reference, the above command is the same as running the following. - * //- - * myFile.acl.add({ - * entity: 'user-email@example.com', - * role: gcs.acl.READER_ROLE - * }, function(err, aclObject) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myFile.acl.readers.addUser('email@example.com').then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - */ -Acl.prototype.readers = {}; - -/** - * An object of convenience methods to add or delete writer ACL permissions for - * a given entity. - * - * The supported methods include: - * - * - `myFile.acl.writers.addAllAuthenticatedUsers` - * - `myFile.acl.writers.deleteAllAuthenticatedUsers` - * - `myFile.acl.writers.addAllUsers` - * - `myFile.acl.writers.deleteAllUsers` - * - `myFile.acl.writers.addDomain` - * - `myFile.acl.writers.deleteDomain` - * - `myFile.acl.writers.addGroup` - * - `myFile.acl.writers.deleteGroup` - * - `myFile.acl.writers.addProject` - * - `myFile.acl.writers.deleteProject` - * - `myFile.acl.writers.addUser` - * - `myFile.acl.writers.deleteUser` - * - * @return {object} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * //- - * // Add a user as a writer of a file. - * //- - * myFile.acl.writers.addUser('email@example.com', function(err, aclObject) {}); - * - * //- - * // For reference, the above command is the same as running the following. - * //- - * myFile.acl.add({ - * entity: 'user-email@example.com', - * role: gcs.acl.WRITER_ROLE - * }, function(err, aclObject) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myFile.acl.writers.addUser('email@example.com').then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - */ -Acl.prototype.writers = {}; - -util.inherits(Acl, AclRoleAccessorMethods); - -/** - * @typedef {array} AddAclResponse - * @property {object} 0 The Acl Objects. - * @property {object} 1 The full API response. - */ -/** - * @callback AddAclCallback - * @param {?Error} err Request error, if any. - * @param {object} acl The Acl Objects. - * @param {object} apiResponse The full API response. - */ -/** - * Add access controls on a {@link Bucket} or {@link File}. - * - * @see [BucketAccessControls: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert} - * @see [ObjectAccessControls: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert} - * - * @param {object} options Configuration options. - * @param {string} options.entity Whose permissions will be added. - * @param {string} options.role Permissions allowed for the defined entity. - * See {@link https://cloud.google.com/storage/docs/access-control Access Control}. - * @param {number} [options.generation] **File Objects Only** Select a specific - * revision of this file (as opposed to the latest version, the default). - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {AddAclCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * const options = { - * entity: 'user-useremail@example.com', - * role: gcs.acl.OWNER_ROLE - * }; - * - * myBucket.acl.add(options, function(err, aclObject, apiResponse) {}); - * - * //- - * // For file ACL operations, you can also specify a `generation` property. - * // Here is how you would grant ownership permissions to a user on a specific - * // revision of a file. - * //- - * myFile.acl.add({ - * entity: 'user-useremail@example.com', - * role: gcs.acl.OWNER_ROLE, - * generation: 1 - * }, function(err, aclObject, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myBucket.acl.add(options).then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/acl.js - * region_tag:storage_add_file_owner - * Example of adding an owner to a file: - * - * @example include:samples/acl.js - * region_tag:storage_add_bucket_owner - * Example of adding an owner to a bucket: - * - * @example include:samples/acl.js - * region_tag:storage_add_bucket_default_owner - * Example of adding a default owner to a bucket: - */ -Acl.prototype.add = function(options, callback) { - const self = this; - - const query = {}; - - if (options.generation) { - query.generation = options.generation; - } - - if (options.userProject) { - query.userProject = options.userProject; - } - - this.request( - { - method: 'POST', - uri: '', - qs: query, - json: { - entity: options.entity, - role: options.role.toUpperCase(), - }, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - callback(null, self.makeAclObject_(resp), resp); - } - ); -}; - -/** - * @typedef {array} RemoveAclResponse - * @property {object} 0 The full API response. - */ -/** - * @callback RemoveAclCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Delete access controls on a {@link Bucket} or {@link File}. - * - * @see [BucketAccessControls: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete} - * @see [ObjectAccessControls: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete} - * - * @param {object} options Configuration object. - * @param {string} options.entity Whose permissions will be revoked. - * @param {int} [options.generation] **File Objects Only** Select a specific - * revision of this file (as opposed to the latest version, the default). - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {RemoveAclCallback} callback The callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * myBucket.acl.delete({ - * entity: 'user-useremail@example.com' - * }, function(err, apiResponse) {}); - * - * //- - * // For file ACL operations, you can also specify a `generation` property. - * //- - * myFile.acl.delete({ - * entity: 'user-useremail@example.com', - * generation: 1 - * }, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myFile.acl.delete().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/acl.js - * region_tag:storage_remove_bucket_owner - * Example of removing an owner from a bucket: - * - * @example include:samples/acl.js - * region_tag:storage_remove_bucket_default_owner - * Example of removing a default owner from a bucket: - * - * @example include:samples/acl.js - * region_tag:storage_remove_file_owner - * Example of removing an owner from a bucket: - */ -Acl.prototype.delete = function(options, callback) { - const query = {}; - - if (options.generation) { - query.generation = options.generation; - } - - if (options.userProject) { - query.userProject = options.userProject; - } - - this.request( - { - method: 'DELETE', - uri: '/' + encodeURIComponent(options.entity), - qs: query, - }, - function(err, resp) { - callback(err, resp); - } - ); -}; - -/** - * @typedef {array} GetAclResponse - * @property {object|object[]} 0 Single or array of Acl Objects. - * @property {object} 1 The full API response. - */ -/** - * @callback GetAclCallback - * @param {?Error} err Request error, if any. - * @param {object|object[]} acl Single or array of Acl Objects. - * @param {object} apiResponse The full API response. - */ -/** - * Get access controls on a {@link Bucket} or {@link File}. If - * an entity is omitted, you will receive an array of all applicable access - * controls. - * - * @see [BucketAccessControls: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get} - * @see [ObjectAccessControls: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get} - * - * @param {object|function} [options] Configuration options. If you want to - * receive a list of all access controls, pass the callback function as the - * only argument. - * @param {string} [options.entity] Whose permissions will be fetched. - * @param {number} [options.generation] **File Objects Only** Select a specific - * revision of this file (as opposed to the latest version, the default). - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetAclCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * myBucket.acl.get({ - * entity: 'user-useremail@example.com' - * }, function(err, aclObject, apiResponse) {}); - * - * //- - * // Get all access controls. - * //- - * myBucket.acl.get(function(err, aclObjects, apiResponse) { - * // aclObjects = [ - * // { - * // entity: 'user-useremail@example.com', - * // role: 'owner' - * // } - * // ] - * }); - * - * //- - * // For file ACL operations, you can also specify a `generation` property. - * //- - * myFile.acl.get({ - * entity: 'user-useremail@example.com', - * generation: 1 - * }, function(err, aclObject, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myBucket.acl.get().then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/acl.js - * region_tag:storage_print_file_acl - * Example of printing a file's ACL: - * - * @example include:samples/acl.js - * region_tag:storage_print_file_acl_for_user - * Example of printing a file's ACL for a specific user: - * - * @example include:samples/acl.js - * region_tag:storage_print_bucket_acl - * Example of printing a bucket's ACL: - * - * @example include:samples/acl.js - * region_tag:storage_print_bucket_acl_for_user - * Example of printing a bucket's ACL for a specific user: - */ -Acl.prototype.get = function(options, callback) { - const self = this; - let path = ''; - const query = {}; - - if (is.fn(options)) { - callback = options; - options = null; - } else { - path = '/' + encodeURIComponent(options.entity); - - if (options.generation) { - query.generation = options.generation; - } - - if (options.userProject) { - query.userProject = options.userProject; - } - } - - this.request( - { - uri: path, - qs: query, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - let results; - - if (resp.items) { - results = arrify(resp.items).map(self.makeAclObject_); - } else { - results = self.makeAclObject_(resp); - } - - callback(null, results, resp); - } - ); -}; - -/** - * @typedef {array} UpdateAclResponse - * @property {object} 0 The updated Acl Objects. - * @property {object} 1 The full API response. - */ -/** - * @callback UpdateAclCallback - * @param {?Error} err Request error, if any. - * @param {object} acl The updated Acl Objects. - * @param {object} apiResponse The full API response. - */ -/** - * Update access controls on a {@link Bucket} or {@link File}. - * - * @see [BucketAccessControls: update API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update} - * @see [ObjectAccessControls: update API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update} - * - * @param {object} options Configuration options. - * @param {string} options.entity Whose permissions will be updated. - * @param {string} options.role Permissions allowed for the defined entity. - * See {@link Storage.acl}. - * @param {number} [options.generation] **File Objects Only** Select a specific - * revision of this file (as opposed to the latest version, the default). - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {UpdateAclCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const myFile = myBucket.file('my-file'); - * - * const options = { - * entity: 'user-useremail@example.com', - * role: gcs.acl.WRITER_ROLE - * }; - * - * myBucket.acl.update(options, function(err, aclObject, apiResponse) {}); - * - * //- - * // For file ACL operations, you can also specify a `generation` property. - * //- - * myFile.acl.update({ - * entity: 'user-useremail@example.com', - * role: gcs.acl.WRITER_ROLE, - * generation: 1 - * }, function(err, aclObject, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myFile.acl.update(options).then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - */ -Acl.prototype.update = function(options, callback) { - const self = this; - - const query = {}; - - if (options.generation) { - query.generation = options.generation; - } - - if (options.userProject) { - query.userProject = options.userProject; - } - - this.request( - { - method: 'PUT', - uri: '/' + encodeURIComponent(options.entity), - qs: query, - json: { - role: options.role.toUpperCase(), - }, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - callback(null, self.makeAclObject_(resp), resp); - } - ); -}; - -/** - * Transform API responses to a consistent object format. - * - * @private - */ -Acl.prototype.makeAclObject_ = function(accessControlObject) { - const obj = { - entity: accessControlObject.entity, - role: accessControlObject.role, - }; - - if (accessControlObject.projectTeam) { - obj.projectTeam = accessControlObject.projectTeam; - } - - return obj; -}; - -/** - * Patch requests up to the bucket's request object. - * - * @private - * - * @param {string} method Action. - * @param {string} path Request path. - * @param {*} query Request query object. - * @param {*} body Request body contents. - * @param {function} callback Callback function. - */ -Acl.prototype.request = function(reqOpts, callback) { - reqOpts.uri = this.pathPrefix + reqOpts.uri; - this.request_(reqOpts, callback); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Acl); - -module.exports = Acl; - -/** - * Attach functionality to a {@link Storage.acl} instance. This will add an - * object for each role group (owners, readers, and writers), with each object - * containing methods to add or delete a type of entity. - * - * As an example, here are a few methods that are created. - * - * myBucket.acl.readers.deleteGroup('groupId', function(err) {}); - * - * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {}); - * - * myBucket.acl.writers.addDomain('example.com', function(err, acl) {}); - * - * @private - */ -function AclRoleAccessorMethods() { - AclRoleAccessorMethods.roles.forEach(this._assignAccessMethods.bind(this)); -} - -AclRoleAccessorMethods.accessMethods = ['add', 'delete']; - -AclRoleAccessorMethods.entities = [ - // Special entity groups that do not require further specification. - 'allAuthenticatedUsers', - 'allUsers', - - // Entity groups that require specification, e.g. `user-email@example.com`. - 'domain-', - 'group-', - 'project-', - 'user-', -]; - -AclRoleAccessorMethods.roles = ['OWNER', 'READER', 'WRITER']; - -AclRoleAccessorMethods.prototype._assignAccessMethods = function(role) { - const self = this; - - const accessMethods = AclRoleAccessorMethods.accessMethods; - const entities = AclRoleAccessorMethods.entities; - const roleGroup = role.toLowerCase() + 's'; - - this[roleGroup] = entities.reduce(function(acc, entity) { - const isPrefix = entity.charAt(entity.length - 1) === '-'; - - accessMethods.forEach(function(accessMethod) { - let method = accessMethod + entity[0].toUpperCase() + entity.substr(1); - - if (isPrefix) { - method = method.replace('-', ''); - } - - // Wrap the parent accessor method (e.g. `add` or `delete`) to avoid the - // more complex API of specifying an `entity` and `role`. - acc[method] = function(entityId, options, callback) { - let apiEntity; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - if (isPrefix) { - apiEntity = entity + entityId; - } else { - // If the entity is not a prefix, it is a special entity group that - // does not require further details. The accessor methods only accept - // a callback. - apiEntity = entity; - callback = entityId; - } - - options = extend( - { - entity: apiEntity, - role: role, - }, - options - ); - - const args = [options]; - - if (is.fn(callback)) { - args.push(callback); - } - - return self[accessMethod].apply(self, args); - }; - }); - - return acc; - }, {}); -}; - -module.exports.AclRoleAccessorMethods = AclRoleAccessorMethods; diff --git a/functions/node_modules/@google-cloud/storage/src/bucket.js b/functions/node_modules/@google-cloud/storage/src/bucket.js deleted file mode 100644 index f0c84196..00000000 --- a/functions/node_modules/@google-cloud/storage/src/bucket.js +++ /dev/null @@ -1,2458 +0,0 @@ -/** - * Copyright 2014-2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const arrify = require('arrify'); -const async = require('async'); -const common = require('@google-cloud/common'); -const extend = require('extend'); -const fs = require('fs'); -const is = require('is'); -const mime = require('mime-types'); -const path = require('path'); -const snakeize = require('snakeize'); -const util = require('util'); -const request = require('request'); - -const Acl = require('./acl.js'); -const File = require('./file.js'); -const Iam = require('./iam.js'); -const Notification = require('./notification.js'); - -/** - * The size of a file (in bytes) must be greater than this number to - * automatically trigger a resumable upload. - * - * @const {number} - * @private - */ -const RESUMABLE_THRESHOLD = 5000000; - -/** - * Create a Bucket object to interact with a Cloud Storage bucket. - * - * @class - * @hideconstructor - * - * @param {Storage} storage A {@link Storage} instance. - * @param {string} name The name of the bucket. - * @param {object} [options] Configuration object. - * @param {string} [options.userProject] User project. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - */ -function Bucket(storage, name, options) { - options = options || {}; - - name = name.replace(/^gs:\/\//, ''); - - const methods = { - /** - * Create a bucket. - * - * @method Bucket#create - * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. - * @param {CreateBucketCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * bucket.create(function(err, bucket, apiResponse) { - * if (!err) { - * // The bucket was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.create().then(function(data) { - * const bucket = data[0]; - * const apiResponse = data[1]; - * }); - */ - create: true, - }; - - common.ServiceObject.call(this, { - parent: storage, - baseUrl: '/b', - id: name, - createMethod: storage.createBucket.bind(storage), - methods: methods, - }); - - /** - * The bucket's name. - * @name Bucket#name - * @type {string} - */ - this.name = name; - /** - * A reference to the {@link Storage} associated with this {@link Bucket} - * instance. - * @name Bucket#storage - * @type {string} - */ - this.storage = storage; - - /** - * A user project to apply to each request from this bucket. - * @name Bucket#userProject - * @type {string} - */ - this.userProject = options.userProject; - - /** - * Cloud Storage uses access control lists (ACLs) to manage object and - * bucket access. ACLs are the mechanism you use to share objects with other - * users and allow other users to access your buckets and objects. - * - * An ACL consists of one or more entries, where each entry grants permissions - * to an entity. Permissions define the actions that can be performed against - * an object or bucket (for example, `READ` or `WRITE`); the entity defines - * who the permission applies to (for example, a specific user or group of - * users). - * - * The `acl` object on a Bucket instance provides methods to get you a list of - * the ACLs defined on your bucket, as well as set, update, and delete them. - * - * Buckets also have - * [default ACLs](https://cloud.google.com/storage/docs/access-control/lists#default) - * for all created files. Default ACLs specify permissions that all new - * objects added to the bucket will inherit by default. You can add, delete, - * get, and update entities and permissions for these as well with - * {@link Bucket#acl.default}. - * - * @see [About Access Control Lists]{@link http://goo.gl/6qBBPO} - * @see [Default ACLs]{@link https://cloud.google.com/storage/docs/access-control/lists#default} - * - * @name Bucket#acl - * @mixes Acl - * @property {Acl} default Cloud Storage Buckets have - * [default ACLs](https://cloud.google.com/storage/docs/access-control/lists#default) - * for all created files. You can add, delete, get, and update entities and - * permissions for these as well. The method signatures and examples are all - * the same, after only prefixing the method call with `default`. - * - * @example - * const storage = require('@google-cloud/storage')(); - * - * //- - * // Make a bucket's contents publicly readable. - * //- - * const myBucket = storage.bucket('my-bucket'); - * - * const options = { - * entity: 'allUsers', - * role: storage.acl.READER_ROLE - * }; - * - * myBucket.acl.add(options, function(err, aclObject) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myBucket.acl.add(options).then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/acl.js - * region_tag:storage_print_bucket_acl - * Example of printing a bucket's ACL: - * - * @example include:samples/acl.js - * region_tag:storage_print_bucket_acl_for_user - * Example of printing a bucket's ACL for a specific user: - * - * @example include:samples/acl.js - * region_tag:storage_add_bucket_owner - * Example of adding an owner to a bucket: - * - * @example include:samples/acl.js - * region_tag:storage_remove_bucket_owner - * Example of removing an owner from a bucket: - * - * @example include:samples/acl.js - * region_tag:storage_add_bucket_default_owner - * Example of adding a default owner to a bucket: - * - * @example include:samples/acl.js - * region_tag:storage_remove_bucket_default_owner - * Example of removing a default owner from a bucket: - */ - this.acl = new Acl({ - request: this.request.bind(this), - pathPrefix: '/acl', - }); - - this.acl.default = new Acl({ - request: this.request.bind(this), - pathPrefix: '/defaultObjectAcl', - }); - - /** - * Get and set IAM policies for your bucket. - * - * @name Bucket#iam - * @mixes Iam - * - * @see [Cloud Storage IAM Management](https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management) - * @see [Granting, Changing, and Revoking Access](https://cloud.google.com/iam/docs/granting-changing-revoking-access) - * @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles) - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Get the IAM policy for your bucket. - * //- - * bucket.iam.getPolicy(function(err, policy) { - * console.log(policy); - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.iam.getPolicy().then(function(data) { - * const policy = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/iam.js - * region_tag:storage_view_bucket_iam_members - * Example of retrieving a bucket's IAM policy: - * - * @example include:samples/iam.js - * region_tag:storage_add_bucket_iam_member - * Example of adding to a bucket's IAM policy: - * - * @example include:samples/iam.js - * region_tag:storage_remove_bucket_iam_member - * Example of removing from a bucket's IAM policy: - */ - this.iam = new Iam(this); -} - -util.inherits(Bucket, common.ServiceObject); - -/** - * @typedef {array} CombineResponse - * @property {File} 0 The new {@link File}. - * @property {object} 1 The full API response. - */ -/** - * @callback CombineCallback - * @param {?Error} err Request error, if any. - * @param {File} newFile The new {@link File}. - * @param {object} apiResponse The full API response. - */ -/** - * Combine multiple files into one new file. - * - * @see [Objects: compose API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/compose} - * - * @throws {Error} if a non-array is provided as sources argument. - * @throws {Error} if less than two sources are provided. - * @throws {Error} if no destination is provided. - * - * @param {string[]|File[]} sources The source files that will be - * combined. - * @param {string|File} destination The file you would like the - * source files combined into. - * @param {object} [options] Configuration options. - * @param {string} [options.kmsKeyName] Resource name of the Cloud KMS key, of - * the form - * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, - * that will be used to encrypt the object. Overwrites the object metadata's - * `kms_key_name` value, if any. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {CombineCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const logBucket = storage.bucket('log-bucket'); - * - * const sources = [ - * logBucket.file('2013-logs.txt'), - * logBucket.file('2014-logs.txt') - * ]; - * - * const allLogs = logBucket.file('all-logs.txt'); - * - * logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) { - * // newFile === allLogs - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * logBucket.combine(sources, allLogs).then(function(data) { - * const newFile = data[0]; - * const apiResponse = data[1]; - * }); - */ -Bucket.prototype.combine = function(sources, destination, options, callback) { - if (!is.array(sources) || sources.length < 2) { - throw new Error('You must provide at least two source files.'); - } - - if (!destination) { - throw new Error('A destination file must be specified.'); - } - - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - sources = sources.map(convertToFile); - destination = convertToFile(destination); - callback = callback || common.util.noop; - - if (!destination.metadata.contentType) { - const destinationContentType = mime.contentType(destination.name); - - if (destinationContentType) { - destination.metadata.contentType = destinationContentType; - } - } - - // Make the request from the destination File object. - destination.request( - { - method: 'POST', - uri: '/compose', - json: { - destination: { - contentType: destination.metadata.contentType, - }, - sourceObjects: sources.map(function(source) { - const sourceObject = { - name: source.name, - }; - - if (source.metadata && source.metadata.generation) { - sourceObject.generation = source.metadata.generation; - } - - return sourceObject; - }), - }, - qs: options, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - callback(null, destination, resp); - } - ); - - function convertToFile(file) { - if (file instanceof File) { - return file; - } - - return self.file(file); - } -}; - -/** - * @typedef {array} CreateChannelResponse - * @property {Channel} 0 The new {@link Channel}. - * @property {object} 1 The full API response. - */ -/** - * @callback CreateChannelCallback - * @param {?Error} err Request error, if any. - * @param {Channel} channel The new {@link Channel}. - * @param {object} apiResponse The full API response. - */ -/** - * Create a channel that will be notified when objects in this bucket changes. - * - * @throws {Error} If an ID is not provided. - * @throws {Error} If an address is not provided. - * - * @see [Objects: watchAll API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll} - * - * @param {string} id The ID of the channel to create. - * @param {object} config See a - * [Objects: watchAll request body](https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll). - * @param {string} config.address The address where notifications are - * delivered for this channel. - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {CreateChannelCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * const id = 'new-channel-id'; - * - * const config = { - * address: 'https://...' - * }; - * - * bucket.createChannel(id, config, function(err, channel, apiResponse) { - * if (!err) { - * // Channel created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.createChannel(id, config).then(function(data) { - * const channel = data[0]; - * const apiResponse = data[1]; - * }); - */ -Bucket.prototype.createChannel = function(id, config, options, callback) { - const self = this; - - if (!is.string(id)) { - throw new Error('An ID is required to create a channel.'); - } - - if (!is.string(config.address)) { - throw new Error('An address is required to create a channel.'); - } - - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request( - { - method: 'POST', - uri: '/o/watch', - json: extend( - { - id: id, - type: 'web_hook', - }, - config - ), - qs: options, - }, - function(err, apiResponse) { - if (err) { - callback(err, null, apiResponse); - return; - } - - const resourceId = apiResponse.resourceId; - const channel = self.storage.channel(id, resourceId); - - channel.metadata = apiResponse; - - callback(null, channel, apiResponse); - } - ); -}; - -/** - * Metadata to set for the Notification. - * - * @typedef {object} CreateNotificationRequest - * @property {object} [customAttributes] An optional list of additional - * attributes to attach to each Cloud PubSub message published for this - * notification subscription. - * @property {string[]} [eventTypes] If present, only send notifications about - * listed event types. If empty, sent notifications for all event types. - * @property {string} [objectNamePrefix] If present, only apply this - * notification configuration to object names that begin with this prefix. - * @property {string} [payloadFormat] The desired content of the Payload. - * Defaults to `JSON_API_V1`. - * - * Acceptable values are: - * - `JSON_API_V1` - * - * - `NONE` - * @property {string} [options.userProject] The ID of the project which will be - * billed for the request. - */ -/** - * @typedef {array} CreateNotificationResponse - * @property {Notification} 0 The new {@link Notification}. - * @property {object} 1 The full API response. - */ -/** - * @callback CreateNotificationCallback - * @param {?Error} err Request error, if any. - * @param {Notification} notification The new {@link Notification}. - * @param {object} apiResponse The full API response. - */ -/** - * Creates a notification subscription for the bucket. - * - * @see [Notifications: insert]{@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert} - * - * @param {Topic|string} topic The Cloud PubSub topic to which this - * subscription publishes. If the project ID is omitted, the current project - * ID will be used. - * - * Acceptable formats are: - * - `projects/grape-spaceship-123/topics/my-topic` - * - * - `my-topic` - * @param {CreateNotificationRequest} [options] Metadata to set for the - * notification. - * @param {CreateNotificationCallback} [callback] Callback function. - * @returns {Promise} - * @throws {Error} If a valid topic is not provided. - * @see Notification#create - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const callback = function(err, notification, apiResponse) { - * if (!err) { - * // The notification was created successfully. - * } - * }; - * - * myBucket.createNotification('my-topic', callback); - * - * //- - * // Configure the nofiication by providing Notification metadata. - * //- - * const metadata = { - * objectNamePrefix: 'prefix-' - * }; - * - * myBucket.createNotification('my-topic', metadata, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * myBucket.createNotification('my-topic').then(function(data) { - * const notification = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/notifications.js - * region_tag:storage_create_notification - * Another example: - */ -Bucket.prototype.createNotification = function(topic, options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - if (is.object(topic) && common.util.isCustomType(topic, 'pubsub/topic')) { - topic = topic.name; - } - - if (!is.string(topic)) { - throw new Error('A valid topic name is required.'); - } - - const body = extend({topic: topic}, options); - - if (body.topic.indexOf('projects') !== 0) { - body.topic = 'projects/{{projectId}}/topics/' + body.topic; - } - - body.topic = '//pubsub.googleapis.com/' + body.topic; - - if (!body.payloadFormat) { - body.payloadFormat = 'JSON_API_V1'; - } - - const query = {}; - - if (body.userProject) { - query.userProject = body.userProject; - delete body.userProject; - } - - this.request( - { - method: 'POST', - uri: '/notificationConfigs', - json: snakeize(body), - qs: query, - }, - function(err, apiResponse) { - if (err) { - callback(err, null, apiResponse); - return; - } - - const notification = self.notification(apiResponse.id); - - notification.metadata = apiResponse; - - callback(null, notification, apiResponse); - } - ); -}; - -/** - * @typedef {array} DeleteBucketResponse - * @property {object} 0 The full API response. - */ -/** - * @callback DeleteBucketCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Delete the bucket. - * - * @see [Buckets: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {DeleteBucketCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * bucket.delete(function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.delete().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/buckets.js - * region_tag:storage_delete_bucket - * Another example: - */ -Bucket.prototype.delete = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request( - { - method: 'DELETE', - uri: '', - qs: options, - }, - callback || common.util.noop - ); -}; - -/** - * @callback DeleteFilesCallback - * @param {?Error|?Error[]} err Request error, if any, or array of errors from - * files that were not able to be deleted. - * @param {object} apiResponse The full API response. - */ -/** - * Iterate over the bucket's files, calling `file.delete()` on each. - * - * This is not an atomic request. A delete attempt will be made - * for each file individually. Any one can fail, in which case only a portion of - * the files you intended to be deleted would have. - * - * Operations are performed in parallel, up to 10 at once. The first error - * breaks the loop and will execute the provided callback with it. Specify - * `{ force: true }` to suppress the errors until all files have had a chance to - * be processed. - * - * The `query` object passed as the first argument will also be passed to - * {@link Bucket#getFiles}. - * - * @see [Objects: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete} - * - * @param {object} [query] Query object. See {@link Bucket#getFiles} - * for all of the supported properties. - * @param {boolean} [query.force] Suppress errors until all files have been - * processed. - * @param {string} [query.userProject] The ID of the project which will be - * billed for the request. - * @param {DeleteFilesCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Delete all of the files in the bucket. - * //- - * bucket.deleteFiles(function(err) {}); - * - * //- - * // By default, if a file cannot be deleted, this method will stop deleting - * // files from your bucket. You can override this setting with `force: true`. - * //- - * bucket.deleteFiles({ - * force: true - * }, function(errors) { - * // `errors`: - * // Array of errors if any occurred, otherwise null. - * }); - * - * //- - * // The first argument to this method acts as a query to - * // {@link Bucket#getFiles}. As an example, you can delete files - * // which match a prefix. - * //- - * bucket.deleteFiles({ - * prefix: 'images/' - * }, function(err) { - * if (!err) { - * // All files in the `images` directory have been deleted. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.deleteFiles().then(function() {}); - */ -Bucket.prototype.deleteFiles = function(query, callback) { - if (is.fn(query)) { - callback = query; - query = {}; - } - - query = query || {}; - - const MAX_PARALLEL_LIMIT = 10; - const errors = []; - - this.getFiles(query, function(err, files) { - if (err) { - callback(err); - return; - } - - function deleteFile(file, callback) { - file.delete(query, function(err) { - if (err) { - if (query.force) { - errors.push(err); - callback(); - return; - } - - callback(err); - return; - } - - callback(); - }); - } - - // Iterate through each file and attempt to delete it. - async.eachLimit(files, MAX_PARALLEL_LIMIT, deleteFile, function(err) { - if (err || errors.length > 0) { - callback(err || errors); - return; - } - - callback(); - }); - }); -}; - -/** - * @typedef {array} DeleteLabelsResponse - * @property {object} 0 The full API response. - */ -/** - * @callback DeleteLabelsCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Delete one or more labels from this bucket. - * - * @param {string|string[]} labels The labels to delete. If no labels are - * provided, all of the labels are removed. - * @param {DeleteLabelsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Delete all of the labels from this bucket. - * //- - * bucket.deleteLabels(function(err, apiResponse) {}); - * - * //- - * // Delete a single label. - * //- - * bucket.deleteLabels('labelone', function(err, apiResponse) {}); - * - * //- - * // Delete a specific set of labels. - * //- - * bucket.deleteLabels([ - * 'labelone', - * 'labeltwo' - * ], function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.deleteLabels().then(function(data) { - * const apiResponse = data[0]; - * }); - */ -Bucket.prototype.deleteLabels = function(labels, callback) { - const self = this; - - if (is.fn(labels)) { - callback = labels; - labels = []; - } - - labels = arrify(labels); - - if (labels.length === 0) { - this.getLabels(function(err, labels) { - if (err) { - callback(err); - return; - } - - deleteLabels(Object.keys(labels)); - }); - } else { - deleteLabels(labels); - } - - function deleteLabels(labels) { - const nullLabelMap = labels.reduce(function(nullLabelMap, labelKey) { - nullLabelMap[labelKey] = null; - return nullLabelMap; - }, {}); - - self.setLabels(nullLabelMap, callback); - } -}; - -/** - * @typedef {array} DisableRequesterPaysResponse - * @property {object} 0 The full API response. - */ -/** - * @callback DisableRequesterPaysCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - *
- * Early Access Testers Only - *

- * This feature is not yet widely-available. - *

- *
- * - * Disable `requesterPays` functionality from this bucket. - * - * @param {DisableRequesterPaysCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.disableRequesterPays(function(err, apiResponse) { - * if (!err) { - * // requesterPays functionality disabled successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.disableRequesterPays().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/requesterPays.js - * region_tag:storage_disable_requester_pays - * Example of disabling requester pays: - */ -Bucket.prototype.disableRequesterPays = function(callback) { - this.setMetadata( - { - billing: { - requesterPays: false, - }, - }, - callback || common.util.noop - ); -}; - -/** - * @typedef {array} EnableRequesterPaysResponse - * @property {object} 0 The full API response. - */ -/** - * @callback EnableRequesterPaysCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - *
- * Early Access Testers Only - *

- * This feature is not yet widely-available. - *

- *
- * - * Enable `requesterPays` functionality for this bucket. This enables you, the - * bucket owner, to have the requesting user assume the charges for the access - * to your bucket and its contents. - * - * @param {EnableRequesterPaysCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.enableRequesterPays(function(err, apiResponse) { - * if (!err) { - * // requesterPays functionality enabled successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.enableRequesterPays().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/requesterPays.js - * region_tag:storage_enable_requester_pays - * Example of enabling requester pays: - */ -Bucket.prototype.enableRequesterPays = function(callback) { - this.setMetadata( - { - billing: { - requesterPays: true, - }, - }, - callback || common.util.noop - ); -}; - -/** - * @typedef {array} BucketExistsResponse - * @property {boolean} 0 Whether the {@link Bucket} exists. - */ -/** - * @callback BucketExistsCallback - * @param {?Error} err Request error, if any. - * @param {boolean} exists Whether the {@link Bucket} exists. - */ -/** - * Check if the bucket exists. - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {BucketExistsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.exists(function(err, exists) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.exists().then(function(data) { - * const exists = data[0]; - * }); - */ -Bucket.prototype.exists = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = options || {}; - - this.get(options, function(err) { - if (err) { - if (err.code === 404) { - callback(null, false); - } else { - callback(err); - } - - return; - } - - callback(null, true); - }); -}; - -/** - * Create a {@link File} object. See {@link File} to see how to handle - * the different use cases you may have. - * - * @param {string} name The name of the file in this bucket. - * @param {object} [options] Configuration options. - * @param {string|number} [options.generation] Only use a specific revision of - * this file. - * @param {string} [options.encryptionKey] A custom encryption key. See - * [Customer-supplied Encryption Keys](https://cloud.google.com/storage/docs/encryption#customer-supplied). - * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will - * be used to encrypt the object. Must be in the format: - * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. - * KMS key ring must use the same location as the bucket. - * @returns {File} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * const file = bucket.file('my-existing-file.png'); - */ -Bucket.prototype.file = function(name, options) { - if (!name) { - throw Error('A file name must be specified.'); - } - - return new File(this, name, options); -}; - -/** - * @typedef {array} GetBucketResponse - * @property {Bucket} 0 The {@link Bucket}. - * @property {object} 1 The full API response. - */ -/** - * @callback GetBucketCallback - * @param {?Error} err Request error, if any. - * @param {Bucket} bucket The {@link Bucket}. - * @param {object} apiResponse The full API response. - */ -/** - * Get a bucket if it exists. - * - * You may optionally use this to "get or create" an object by providing an - * object with `autoCreate` set to `true`. Any extra configuration that is - * normally required for the `create` method must be contained within this - * object as well. - * - * @param {object} [options] Configuration options. - * @param {boolean} [options.autoCreate] Automatically create the object if - * it does not exist. Default: `false` - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetBucketCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.get(function(err, bucket, apiResponse) { - * // `bucket.metadata` has been populated. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.get().then(function(data) { - * const bucket = data[0]; - * const apiResponse = data[1]; - * }); - */ -Bucket.prototype.get = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = options || {}; - - const autoCreate = options.autoCreate; - delete options.autoCreate; - - function onCreate(err, bucket, apiResponse) { - if (err) { - if (err.code === 409) { - self.get(options, callback); - return; - } - - callback(err, null, apiResponse); - return; - } - - callback(null, bucket, apiResponse); - } - - this.getMetadata(options, function(err, metadata) { - if (err) { - if (err.code === 404 && autoCreate) { - const args = []; - - if (!is.empty(options)) { - args.push(options); - } - - args.push(onCreate); - - self.create.apply(self, args); - return; - } - - callback(err, null, metadata); - return; - } - - callback(null, self, metadata); - }); -}; - -/** - * Query object for listing files. - * - * @typedef {object} GetFilesRequest - * @property {boolean} [autoPaginate=true] Have pagination handled - * automatically. - * @property {string} [delimiter] Results will contain only objects whose - * names, aside from the prefix, do not contain delimiter. Objects whose - * names, aside from the prefix, contain delimiter will have their name - * truncated after the delimiter, returned in `apiResponse.prefixes`. - * Duplicate prefixes are omitted. - * @property {string} [directory] Filter results based on a directory name, or - * more technically, a "prefix". - * @property {string} [prefix] Filter results to objects whose names begin - * with this prefix. - * @property {number} [maxApiCalls] Maximum number of API calls to make. - * @property {number} [maxResults] Maximum number of items plus prefixes to - * return. - * @property {string} [pageToken] A previously-returned page token - * representing part of the larger set of results to view. - * @property {string} [userProject] The ID of the project which will be - * billed for the request. - * @property {boolean} [versions] If true, returns File objects scoped to - * their versions. - */ -/** - * @typedef {array} GetFilesResponse - * @property {File[]} 0 Array of {@link File} instances. - */ -/** - * @callback GetFilesCallback - * @param {?Error} err Request error, if any. - * @param {File[]} files Array of {@link File} instances. - */ -/** - * Get {@link File} objects for the files currently in the bucket. - * - * @see [Objects: list API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/list} - * - * @param {GetFilesRequest} [query] Query object for listing files. - * @param {GetFilesCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.getFiles(function(err, files) { - * if (!err) { - * // files is an array of File objects. - * } - * }); - * - * //- - * // If your bucket has versioning enabled, you can get all of your files - * // scoped to their generation. - * //- - * bucket.getFiles({ - * versions: true - * }, function(err, files) { - * // Each file is scoped to its generation. - * }); - * - * //- - * // To control how many API requests are made and page through the results - * // manually, set `autoPaginate` to `false`. - * //- - * const callback = function(err, files, nextQuery, apiResponse) { - * if (nextQuery) { - * // More results exist. - * bucket.getFiles(nextQuery, callback); - * } - * - * // The `metadata` property is populated for you with the metadata at the - * // time of fetching. - * files[0].metadata; - * - * // However, in cases where you are concerned the metadata could have - * // changed, use the `getMetadata` method. - * files[0].getMetadata(function(err, metadata) {}); - * }; - * - * bucket.getFiles({ - * autoPaginate: false - * }, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.getFiles().then(function(data) { - * const files = data[0]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_list_files - * Another example: - * - * @example include:samples/files.js - * region_tag:storage_list_files_with_prefix - * Example of listing files, filtered by a prefix: - */ -Bucket.prototype.getFiles = function(query, callback) { - const self = this; - - if (!callback) { - callback = query; - query = {}; - } - - query = extend({}, query); - - if (query.directory) { - query.prefix = `${query.directory}/`.replace(/\/*$/, '/'); - delete query.directory; - } - - this.request( - { - uri: '/o', - qs: query, - }, - function(err, resp) { - if (err) { - callback(err, null, null, resp); - return; - } - - const files = arrify(resp.items).map(function(file) { - const options = {}; - - if (query.versions) { - options.generation = file.generation; - } - - if (file.kmsKeyName) { - options.kmsKeyName = file.kmsKeyName; - } - - const fileInstance = self.file(file.name, options); - fileInstance.metadata = file; - - return fileInstance; - }); - - let nextQuery = null; - if (resp.nextPageToken) { - nextQuery = extend({}, query, { - pageToken: resp.nextPageToken, - }); - } - - callback(null, files, nextQuery, resp); - } - ); -}; - -/** - * Get {@link File} objects for the files currently in the bucket as a - * readable object stream. - * - * @method Bucket#getFilesStream - * @param {GetFilesRequest} [query] Query object for listing files. - * @returns {ReadableStream} A readable stream that emits {@link File} instances. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.getFilesStream() - * .on('error', console.error) - * .on('data', function(file) { - * // file is a File object. - * }) - * .on('end', function() { - * // All files retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * bucket.getFilesStream() - * .on('data', function(file) { - * this.end(); - * }); - */ -Bucket.prototype.getFilesStream = common.paginator.streamify('getFiles'); - -/** - * @typedef {array} GetLabelsResponse - * @property {object} 0 Object of labels currently set on this bucket. - */ -/** - * @callback GetLabelsCallback - * @param {?Error} err Request error, if any. - * @param {object} labels Object of labels currently set on this bucket. - */ -/** - * Get the labels currently set on this bucket. - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetLabelsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.getLabels(function(err, labels) { - * if (err) { - * // Error handling omitted. - * } - * - * // labels = { - * // label: 'labelValue', - * // ... - * // } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.getLabels().then(function(data) { - * const labels = data[0]; - * }); - */ -Bucket.prototype.getLabels = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.getMetadata(options, function(err, metadata) { - if (err) { - callback(err); - return; - } - - callback(null, metadata.labels || {}); - }); -}; - -/** - * @typedef {array} GetBucketMetadataResponse - * @property {object} 0 The bucket metadata. - * @property {object} 1 The full API response. - */ -/** - * @callback GetBucketMetadataCallback - * @param {?Error} err Request error, if any. - * @param {object} files The bucket metadata. - * @param {object} apiResponse The full API response. - */ -/** - * Get the bucket's metadata. - * - * To set metadata, see {@link Bucket#setMetadata}. - * - * @see [Buckets: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/get} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetBucketMetadataCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.getMetadata(function(err, metadata, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.getMetadata().then(function(data) { - * const metadata = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/requesterPays.js - * region_tag:storage_get_requester_pays_status - * Example of retrieving the requester pays status of a bucket: - */ -Bucket.prototype.getMetadata = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request( - { - uri: '', - qs: options, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - self.metadata = resp; - - callback(null, self.metadata, resp); - } - ); -}; - -/** - * @typedef {array} GetNotificationsResponse - * @property {Notification[]} 0 Array of {@link Notification} instances. - * @property {object} 1 The full API response. - */ -/** - * @callback GetNotificationsCallback - * @param {?Error} err Request error, if any. - * @param {Notification[]} notifications Array of {@link Notification} - * instances. - * @param {object} apiResponse The full API response. - */ -/** - * Retrieves a list of notification subscriptions for a given bucket. - * - * @see [Notifications: list]{@link https://cloud.google.com/storage/docs/json_api/v1/notifications/list} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetNotificationsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * - * bucket.getNotifications(function(err, notifications, apiResponse) { - * if (!err) { - * // notifications is an array of Notification objects. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.getNotifications().then(function(data) { - * const notifications = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/notifications.js - * region_tag:storage_list_notifications - * Another example: - */ -Bucket.prototype.getNotifications = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request( - { - uri: '/notificationConfigs', - qs: options, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - const notifications = arrify(resp.items).map(function(notification) { - const notificationInstance = self.notification(notification.id); - notificationInstance.metadata = notification; - return notificationInstance; - }); - - callback(null, notifications, resp); - } - ); -}; - -/** - * @typedef {array} MakeBucketPrivateResponse - * @property {File[]} 0 List of files made private. - */ -/** - * @callback MakeBucketPrivateCallback - * @param {?Error} err Request error, if any. - * @param {File[]} files List of files made private. - */ -/** - * Make the bucket listing private. - * - * You may also choose to make the contents of the bucket private by specifying - * `includeFiles: true`. This will automatically run - * {@link File#makePrivate} for every file in the bucket. - * - * When specifying `includeFiles: true`, use `force: true` to delay execution of - * your callback until all files have been processed. By default, the callback - * is executed after the first error. Use `force` to queue such errors until all - * files have been processed, after which they will be returned as an array as - * the first argument to your callback. - * - * NOTE: This may cause the process to be long-running and use a high number of - * requests. Use with caution. - * - * @see [Buckets: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch} - * - * @param {object} [options] Configuration options. - * @param {boolean} [options.includeFiles=false] Make each file in the bucket - * private. - * @param {boolean} [options.force] Queue errors occurred while making files - * private until all files have been processed. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {MakeBucketPrivateCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Make the bucket private. - * //- - * bucket.makePrivate(function(err) {}); - * - * //- - * // Make the bucket and its contents private. - * //- - * const opts = { - * includeFiles: true - * }; - * - * bucket.makePrivate(opts, function(err, files) { - * // `err`: - * // The first error to occur, otherwise null. - * // - * // `files`: - * // Array of files successfully made private in the bucket. - * }); - * - * //- - * // Make the bucket and its contents private, using force to suppress errors - * // until all files have been processed. - * //- - * const opts = { - * includeFiles: true, - * force: true - * }; - * - * bucket.makePrivate(opts, function(errors, files) { - * // `errors`: - * // Array of errors if any occurred, otherwise null. - * // - * // `files`: - * // Array of files successfully made private in the bucket. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.makePrivate(opts).then(function(data) { - * const files = data[0]; - * }); - */ -Bucket.prototype.makePrivate = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = options || {}; - options.private = true; - - async.series([setPredefinedAcl, makeFilesPrivate], callback); - - function setPredefinedAcl(done) { - const query = { - predefinedAcl: 'projectPrivate', - }; - - if (options.userProject) { - query.userProject = options.userProject; - } - - self.setMetadata( - { - // You aren't allowed to set both predefinedAcl & acl properties on a - // bucket so acl must explicitly be nullified. - acl: null, - }, - query, - done - ); - } - - function makeFilesPrivate(done) { - if (!options.includeFiles) { - done(); - return; - } - - self.makeAllFilesPublicPrivate_(options, done); - } -}; - -/** - * @typedef {array} MakeBucketPublicResponse - * @property {File[]} 0 List of files made public. - */ -/** - * @callback MakeBucketPublicCallback - * @param {?Error} err Request error, if any. - * @param {File[]} files List of files made public. - */ -/** - * Make the bucket publicly readable. - * - * You may also choose to make the contents of the bucket publicly readable by - * specifying `includeFiles: true`. This will automatically run - * {@link File#makePublic} for every file in the bucket. - * - * When specifying `includeFiles: true`, use `force: true` to delay execution of - * your callback until all files have been processed. By default, the callback - * is executed after the first error. Use `force` to queue such errors until all - * files have been processed, after which they will be returned as an array as - * the first argument to your callback. - * - * NOTE: This may cause the process to be long-running and use a high number of - * requests. Use with caution. - * - * @see [Buckets: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch} - * - * @param {object} [options] Configuration options. - * @param {boolean} [options.includeFiles=false] Make each file in the bucket - * publicly readable. - * @param {boolean} [options.force] Queue errors occurred while making files - * public until all files have been processed. - * @param {MakeBucketPublicCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Make the bucket publicly readable. - * //- - * bucket.makePublic(function(err) {}); - * - * //- - * // Make the bucket and its contents publicly readable. - * //- - * const opts = { - * includeFiles: true - * }; - * - * bucket.makePublic(opts, function(err, files) { - * // `err`: - * // The first error to occur, otherwise null. - * // - * // `files`: - * // Array of files successfully made public in the bucket. - * }); - * - * //- - * // Make the bucket and its contents publicly readable, using force to - * // suppress errors until all files have been processed. - * //- - * const opts = { - * includeFiles: true, - * force: true - * }; - * - * bucket.makePublic(opts, function(errors, files) { - * // `errors`: - * // Array of errors if any occurred, otherwise null. - * // - * // `files`: - * // Array of files successfully made public in the bucket. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.makePublic(opts).then(function(data) { - * const files = data[0]; - * }); - */ -Bucket.prototype.makePublic = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = options || {}; - options.public = true; - - async.series( - [addAclPermissions, addDefaultAclPermissions, makeFilesPublic], - callback - ); - - function addAclPermissions(done) { - // Allow reading bucket contents while preserving original permissions. - self.acl.add( - { - entity: 'allUsers', - role: 'READER', - }, - done - ); - } - - function addDefaultAclPermissions(done) { - self.acl.default.add( - { - entity: 'allUsers', - role: 'READER', - }, - done - ); - } - - function makeFilesPublic(done) { - if (!options.includeFiles) { - done(); - return; - } - - self.makeAllFilesPublicPrivate_(options, done); - } -}; - -/** - * Get a reference to a Cloud Pub/Sub Notification. - * - * @param {string} id ID of notification. - * @returns {Notification} - * @see Notification - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * const notification = bucket.notification('1'); - */ -Bucket.prototype.notification = function(id) { - if (!id) { - throw new Error('You must supply a notification ID.'); - } - - return new Notification(this, id); -}; - -/** - * Makes request and applies userProject query parameter if necessary. - * - * @private - * - * @param {object} reqOpts - The request options. - * @param {function} callback - The callback function. - */ -Bucket.prototype.request = function(reqOpts, callback) { - if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) { - reqOpts.qs = extend(reqOpts.qs, {userProject: this.userProject}); - } - - return common.ServiceObject.prototype.request.call(this, reqOpts, callback); -}; - -/** - * @typedef {array} SetLabelsResponse - * @property {object} 0 The bucket metadata. - */ -/** - * @callback SetLabelsCallback - * @param {?Error} err Request error, if any. - * @param {object} metadata The bucket metadata. - */ -/** - * Set labels on the bucket. - * - * This makes an underlying call to {@link Bucket#setMetadata}, which - * is a PATCH request. This means an individual label can be overwritten, but - * unmentioned labels will not be touched. - * - * @param {object} labels Labels to set on the bucket. - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {SetLabelsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * const labels = { - * labelone: 'labelonevalue', - * labeltwo: 'labeltwovalue' - * }; - * - * bucket.setLabels(labels, function(err, metadata) { - * if (!err) { - * // Labels set successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.setLabels(labels).then(function(data) { - * const metadata = data[0]; - * }); - */ -Bucket.prototype.setLabels = function(labels, options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - callback = callback || common.util.noop; - - this.setMetadata({labels}, options, callback); -}; - -/** - * @typedef {array} SetBucketMetadataResponse - * @property {object} 0 The bucket metadata. - */ -/** - * @callback SetBucketMetadataCallback - * @param {?Error} err Request error, if any. - * @param {object} metadata The bucket metadata. - */ -/** - * Set the bucket's metadata. - * - * @see [Buckets: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch} - * - * @param {object} metadata The metadata you wish to set. - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {SetBucketMetadataCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Set website metadata field on the bucket. - * //- - * const metadata = { - * website: { - * mainPageSuffix: 'http://example.com', - * notFoundPage: 'http://example.com/404.html' - * } - * }; - * - * bucket.setMetadata(metadata, function(err, apiResponse) {}); - * - * //- - * // Enable versioning for your bucket. - * //- - * bucket.setMetadata({ - * versioning: { - * enabled: true - * } - * }, function(err, apiResponse) {}); - * - * //- - * // Enable KMS encryption for objects within this bucket. - * //- - * bucket.setMetadata({ - * encryption: { - * defaultKmsKeyName: 'projects/grape-spaceship-123/...' - * } - * }, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.setMetadata(metadata).then(function(data) { - * const apiResponse = data[0]; - * }); - */ -Bucket.prototype.setMetadata = function(metadata, options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - callback = callback || common.util.noop; - - this.request( - { - method: 'PATCH', - uri: '', - json: metadata, - qs: options, - }, - function(err, resp) { - if (err) { - callback(err, resp); - return; - } - - self.metadata = resp; - - callback(null, resp); - } - ); -}; - -/** - * @callback SetStorageClassCallback - * @param {?Error} err Request error, if any. - */ -/** - * Set the default storage class for new files in this bucket. - * - * @see [Storage Classes]{@link https://cloud.google.com/storage/docs/storage-classes} - * - * @param {string} storageClass The new storage class. (`multi_regional`, - * `regional`, `standard`, `nearline`, `coldline`, or - * `durable_reduced_availability`) - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] - The ID of the project which will be - * billed for the request. - * @param {SetStorageClassCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.setStorageClass('regional', function(err, apiResponse) { - * if (err) { - * // Error handling omitted. - * } - * - * // The storage class was updated successfully. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.setStorageClass('regional').then(function() {}); - */ -Bucket.prototype.setStorageClass = function(storageClass, options, callback) { - // In case we get input like `storageClass`, convert to `storage_class`. - storageClass = storageClass - .replace(/-/g, '_') - .replace(/([a-z])([A-Z])/g, function(_, low, up) { - return low + '_' + up; - }) - .toUpperCase(); - - this.setMetadata({storageClass}, options, callback); -}; - -/** - * Set a user project to be billed for all requests made from this Bucket - * object and any files referenced from this Bucket object. - * - * @param {string} userProject The user project. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * bucket.setUserProject('grape-spaceship-123'); - */ -Bucket.prototype.setUserProject = function(userProject) { - this.userProject = userProject; -}; - -/** - * @typedef {array} UploadResponse - * @property {object} 0 The uploaded {@link File}. - * @property {object} 1 The full API response. - */ -/** - * @callback UploadCallback - * @param {?Error} err Request error, if any. - * @param {object} metadata The uploaded {@link File}. - * @param {object} apiResponse The full API response. - */ -/** - * Upload a file to the bucket. This is a convenience method that wraps - * {@link File#createWriteStream}. - * - * You can specify whether or not an upload is resumable by setting - * `options.resumable`. *Resumable uploads are enabled by default if your input - * file is larger than 5 MB.* - * - * For faster crc32c computation, you must manually install - * [`fast-crc32c`](http://www.gitnpm.com/fast-crc32c): - * - * $ npm install --save fast-crc32c - * - * @see [Upload Options (Simple or Resumable)]{@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads} - * @see [Objects: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert} - * - * @param {string} pathString The fully qualified path or url to the file you - * wish to upload to your bucket. - * @param {object} [options] Configuration options. - * @param {string|File} [options.destination] The place to save - * your file. If given a string, the file will be uploaded to the bucket - * using the string as a filename. When given a File object, your local file - * will be uploaded to the File object's bucket and under the File object's - * name. Lastly, when this argument is omitted, the file is uploaded to your - * bucket using the name of the local file or the path of the url relative to it's domain. - * @param {string} [options.encryptionKey] A custom encryption key. See - * [Customer-supplied Encryption Keys](https://cloud.google.com/storage/docs/encryption#customer-supplied). - * @param {boolean} [options.gzip] Automatically gzip the file. This will set - * `options.metadata.contentEncoding` to `gzip`. - * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will - * be used to encrypt the object. Must be in the format: - * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. - * @param {object} [options.metadata] See an - * [Objects: insert request body](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON). - * @param {string} [options.offset] The starting byte of the upload stream, for - * resuming an interrupted upload. Defaults to 0. - * @param {string} [options.predefinedAcl] Apply a predefined set of access - * controls to this object. - * - * Acceptable values are: - * - **`authenticatedRead`** - Object owner gets `OWNER` access, and - * `allAuthenticatedUsers` get `READER` access. - * - * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and - * project team owners get `OWNER` access. - * - * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project - * team owners get `READER` access. - * - * - **`private`** - Object owner gets `OWNER` access. - * - * - **`projectPrivate`** - Object owner gets `OWNER` access, and project - * team members get access according to their roles. - * - * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` get - * `READER` access. - * @param {boolean} [options.private] Make the uploaded file private. (Alias for - * `options.predefinedAcl = 'private'`) - * @param {boolean} [options.public] Make the uploaded file public. (Alias for - * `options.predefinedAcl = 'publicRead'`) - * @param {boolean} [options.resumable] Force a resumable upload. (default: - * true for files larger than 5 MB). - * @param {string} [options.uri] The URI for an already-created resumable - * upload. See {@link File#createResumableUpload}. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {string|boolean} [options.validation] Possible values: `"md5"`, - * `"crc32c"`, or `false`. By default, data integrity is validated with an - * MD5 checksum for maximum reliability. CRC32c will provide better - * performance with less reliability. You may also choose to skip validation - * completely, however this is **not recommended**. - * @param {object} [options.requestOptions] When `pathString` is a URL, - * additional [options for the HTTP request](https://github.com/request/request#requestoptions-callback) - * could be provided here. - * @param {UploadCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * - * //- - * // Upload a file from a local path. - * //- - * bucket.upload('/local/path/image.png', function(err, file, apiResponse) { - * // Your bucket now contains: - * // - "image.png" (with the contents of `/local/path/image.png') - * - * // `file` is an instance of a File object that refers to your new file. - * }); - * - * //- - * // You can also upload a file from a URL. - * //- - * - * bucket.upload('https://example.com/images/image.png', function(err, file, apiResponse) { - * // Your bucket now contains: - * // - "image.png" - * - * // `file` is an instance of a File object that refers to your new file. - * }); - * - * //- - * // It's not always that easy. You will likely want to specify the filename - * // used when your new file lands in your bucket. - * // - * // You may also want to set metadata or customize other options. - * //- - * const options = { - * destination: 'new-image.png', - * resumable: true, - * validation: 'crc32c', - * metadata: { - * metadata: { - * event: 'Fall trip to the zoo' - * } - * } - * }; - * - * bucket.upload('local-image.png', options, function(err, file) { - * // Your bucket now contains: - * // - "new-image.png" (with the contents of `local-image.png') - * - * // `file` is an instance of a File object that refers to your new file. - * }); - * - * //- - * // You can also have a file gzip'd on the fly. - * //- - * bucket.upload('index.html', { gzip: true }, function(err, file) { - * // Your bucket now contains: - * // - "index.html" (automatically compressed with gzip) - * - * // Downloading the file with `file.download` will automatically decode the - * // file. - * }); - * - * //- - * // You may also re-use a File object, {File}, that references - * // the file you wish to create or overwrite. - * //- - * const options = { - * destination: bucket.file('existing-file.png'), - * resumable: false - * }; - * - * bucket.upload('local-img.png', options, function(err, newFile) { - * // Your bucket now contains: - * // - "existing-file.png" (with the contents of `local-img.png') - * - * // Note: - * // The `newFile` parameter is equal to `file`. - * }); - * - * //- - * // To use - * // - * // Customer-supplied Encryption Keys, provide the `encryptionKey` option. - * //- - * const crypto = require('crypto'); - * const encryptionKey = crypto.randomBytes(32); - * - * bucket.upload('img.png', { - * encryptionKey: encryptionKey - * }, function(err, newFile) { - * // `img.png` was uploaded with your custom encryption key. - * - * // `newFile` is already configured to use the encryption key when making - * // operations on the remote object. - * - * // However, to use your encryption key later, you must create a `File` - * // instance with the `key` supplied: - * const file = bucket.file('img.png', { - * encryptionKey: encryptionKey - * }); - * - * // Or with `file#setEncryptionKey`: - * const file = bucket.file('img.png'); - * file.setEncryptionKey(encryptionKey); - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.upload('local-image.png').then(function(data) { - * const file = data[0]; - * }); - * - * //- - * // Additional options for download request could be provided. - * //- - * bucket.upload('https://example.com/images/image.png', { - * requestOptions: { - * headers: { - * 'User-Agent': 'curl/7.54.0' - * } - * } - * }, function(err, newFile) { - * // Custom `User-Agent` header will be used for the download request of - * // "https://example.com/images/image.png". - * }); - * - * @example include:samples/files.js - * region_tag:storage_upload_file - * Another example: - * - * @example include:samples/encryption.js - * region_tag:storage_upload_encrypted_file - * Example of uploading an encrypted file: - */ -Bucket.prototype.upload = function(pathString, options, callback) { - if (global.GCLOUD_SANDBOX_ENV) { - return; - } - - const isURL = /^(http|https):/.test(pathString); - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend( - { - metadata: {}, - }, - options - ); - - const requestOptions = Object.assign( - { - url: pathString, - }, - options.requestOptions - ); - - let newFile; - if (options.destination instanceof File) { - newFile = options.destination; - } else if (is.string(options.destination)) { - // Use the string as the name of the file. - newFile = this.file(options.destination, { - encryptionKey: options.encryptionKey, - kmsKeyName: options.kmsKeyName, - }); - } else { - // Resort to using the name of the incoming file. - const destination = path.basename(pathString); - newFile = this.file(destination, { - encryptionKey: options.encryptionKey, - kmsKeyName: options.kmsKeyName, - }); - } - - const contentType = mime.contentType(path.basename(pathString)); - - if (contentType && !options.metadata.contentType) { - options.metadata.contentType = contentType; - } - - if (is.boolean(options.resumable)) { - upload(); - } else if (isURL) { - request.head(requestOptions, function(err, resp) { - if (err) { - callback(err); - return; - } - - const contentLength = resp.headers['content-length']; - - if (is.number(contentLength)) { - options.resumable = contentLength > RESUMABLE_THRESHOLD; - } - - upload(); - }); - } else { - // Determine if the upload should be resumable if it's over the threshold. - fs.stat(pathString, function(err, fd) { - if (err) { - callback(err); - return; - } - - options.resumable = fd.size > RESUMABLE_THRESHOLD; - - upload(); - }); - } - - function upload() { - let sourceStream; - - if (isURL) { - sourceStream = request.get(requestOptions); - } else { - sourceStream = fs.createReadStream(pathString); - } - - sourceStream - .on('error', callback) - .pipe(newFile.createWriteStream(options)) - .on('error', callback) - .on('finish', function() { - callback(null, newFile, newFile.metadata); - }); - } -}; - -/** - * Iterate over all of a bucket's files, calling `file.makePublic()` (public) - * or `file.makePrivate()` (private) on each. - * - * Operations are performed in parallel, up to 10 at once. The first error - * breaks the loop, and will execute the provided callback with it. Specify - * `{ force: true }` to suppress the errors. - * - * @private - * - * @param {object} options] Configuration options. - * @param {boolean} [options.force] Suppress errors until all files have been - * processed. - * @param {boolean} [options.private] Make files private. - * @param {boolean} [options.public] Make files public. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {function} callback Callback function. - */ -Bucket.prototype.makeAllFilesPublicPrivate_ = function(options, callback) { - const MAX_PARALLEL_LIMIT = 10; - const errors = []; - const updatedFiles = []; - - this.getFiles(options, function(err, files) { - if (err) { - callback(err); - return; - } - - function processFile(file, callback) { - if (options.public) { - file.makePublic(processedCallback); - } else if (options.private) { - file.makePrivate(options, processedCallback); - } - - function processedCallback(err) { - if (err) { - if (options.force) { - errors.push(err); - callback(); - return; - } - - callback(err); - return; - } - - updatedFiles.push(file); - callback(); - } - } - - // Iterate through each file and make it public or private. - async.eachLimit(files, MAX_PARALLEL_LIMIT, processFile, function(err) { - if (err || errors.length > 0) { - callback(err || errors, updatedFiles); - return; - } - - callback(null, updatedFiles); - }); - }); -}; - -/*! Developer Documentation - * - * These methods can be auto-paginated. - */ -common.paginator.extend(Bucket, 'getFiles'); - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Bucket, { - exclude: ['file', 'notification'], -}); - -/** - * Reference to the {@link Bucket} class. - * @name module:@google-cloud/storage.Bucket - * @see Bucket - */ -module.exports = Bucket; diff --git a/functions/node_modules/@google-cloud/storage/src/channel.js b/functions/node_modules/@google-cloud/storage/src/channel.js deleted file mode 100644 index 3d7f9b0e..00000000 --- a/functions/node_modules/@google-cloud/storage/src/channel.js +++ /dev/null @@ -1,116 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const common = require('@google-cloud/common'); -const util = require('util'); - -/** - * Create a channel object to interact with a Cloud Storage channel. - * - * @see [Object Change Notification]{@link https://cloud.google.com/storage/docs/object-change-notification} - * - * @class - * - * @param {string} id The ID of the channel. - * @param {string} resourceId The resource ID of the channel. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const channel = storage.channel('id', 'resource-id'); - */ -function Channel(storage, id, resourceId) { - const config = { - parent: storage, - baseUrl: '/channels', - - // An ID shouldn't be included in the API requests. - // RE: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1145 - id: '', - - methods: { - // Only need `request`. - }, - }; - - common.ServiceObject.call(this, config); - - this.metadata.id = id; - this.metadata.resourceId = resourceId; -} - -util.inherits(Channel, common.ServiceObject); - -/** - * @typedef {array} StopResponse - * @property {object} 0 The full API response. - */ -/** - * @callback StopCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Stop this channel. - * - * @param {StopCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const channel = storage.channel('id', 'resource-id'); - * channel.stop(function(err, apiResponse) { - * if (!err) { - * // Channel stopped successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * channel.stop().then(function(data) { - * const apiResponse = data[0]; - * }); - */ -Channel.prototype.stop = function(callback) { - callback = callback || common.util.noop; - - this.request( - { - method: 'POST', - uri: '/stop', - json: this.metadata, - }, - function(err, apiResponse) { - callback(err, apiResponse); - } - ); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Channel); - -/** - * Reference to the {@link Channel} class. - * @name module:@google-cloud/storage.Channel - * @see Channel - */ -module.exports = Channel; diff --git a/functions/node_modules/@google-cloud/storage/src/file.js b/functions/node_modules/@google-cloud/storage/src/file.js deleted file mode 100644 index 95899887..00000000 --- a/functions/node_modules/@google-cloud/storage/src/file.js +++ /dev/null @@ -1,2475 +0,0 @@ -/*! - * Copyright 2014 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const Buffer = require('safe-buffer').Buffer; -const common = require('@google-cloud/common'); -const compressible = require('compressible'); -const concat = require('concat-stream'); -const createErrorClass = require('create-error-class'); -const crypto = require('crypto'); -const duplexify = require('duplexify'); -const extend = require('extend'); -const fs = require('fs'); -const hashStreamValidation = require('hash-stream-validation'); -const is = require('is'); -const mime = require('mime'); -const once = require('once'); -const os = require('os'); -const pumpify = require('pumpify'); -const resumableUpload = require('gcs-resumable-upload'); -const streamEvents = require('stream-events'); -const through = require('through2'); -const util = require('util'); -const xdgBasedir = require('xdg-basedir'); -const zlib = require('zlib'); -const url = require('url'); - -const Acl = require('./acl.js'); - -/** - * Custom error type for errors related to creating a resumable upload. - * - * @private - */ -const ResumableUploadError = createErrorClass('ResumableUploadError'); - -/** - * Custom error type for errors related to getting signed errors and policies. - * - * @private - */ -const SigningError = createErrorClass('SigningError'); - -/** - * @const {string} - * @private - */ -const STORAGE_DOWNLOAD_BASE_URL = 'https://storage.googleapis.com'; - -/** - * @const {string} - * @private - */ -const STORAGE_UPLOAD_BASE_URL = - 'https://www.googleapis.com/upload/storage/v1/b'; - -/** - * @const {RegExp} - * @private - */ -const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/; - -/** - * A File object is created from your {@link Bucket} object using - * {@link Bucket#file}. - * - * @class - * @param {Bucket} bucket The Bucket instance this file is - * attached to. - * @param {string} name The name of the remote file. - * @param {object} [options] Configuration options. - * @param {string} [options.encryptionKey] A custom encryption key. - * @param {number} [options.generation] Generation to scope the file to. - * @param {string} [options.kmsKeyName] Cloud KMS Key used to encrypt this - * object, if the object is encrypted by such a key. Limited availability; - * usable only by enabled projects. - * @param {string} [options.userProject] The ID of the project which will be - * billed for all requests made from File object. - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - */ -function File(bucket, name, options) { - options = options || {}; - - this.bucket = bucket; - this.storage = bucket.parent; - - this.kmsKeyName = options.kmsKeyName; - this.userProject = options.userProject || bucket.userProject; - - Object.defineProperty(this, 'name', { - enumerable: true, - value: name.replace(/^\/+/, ''), // Remove leading slashes. - }); - - const generation = parseInt(options.generation, 10); - - if (!isNaN(generation)) { - this.generation = generation; - this.requestQueryObject = { - generation: this.generation, - }; - } - - common.ServiceObject.call(this, { - parent: bucket, - baseUrl: '/o', - id: encodeURIComponent(this.name), - }); - - if (options.encryptionKey) { - this.setEncryptionKey(options.encryptionKey); - } - - /** - * Cloud Storage uses access control lists (ACLs) to manage object and - * bucket access. ACLs are the mechanism you use to share objects with other - * users and allow other users to access your buckets and objects. - * - * An ACL consists of one or more entries, where each entry grants permissions - * to an entity. Permissions define the actions that can be performed against - * an object or bucket (for example, `READ` or `WRITE`); the entity defines - * who the permission applies to (for example, a specific user or group of - * users). - * - * The `acl` object on a File instance provides methods to get you a list of - * the ACLs defined on your bucket, as well as set, update, and delete them. - * - * @see [About Access Control lists]{@link http://goo.gl/6qBBPO} - * - * @name File#acl - * @mixes Acl - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * //- - * // Make a file publicly readable. - * //- - * const options = { - * entity: 'allUsers', - * role: storage.acl.READER_ROLE - * }; - * - * file.acl.add(options, function(err, aclObject) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.acl.add(options).then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - */ - this.acl = new Acl({ - request: this.request.bind(this), - pathPrefix: '/acl', - }); -} - -util.inherits(File, common.ServiceObject); - -/** - * @typedef {array} CopyResponse - * @property {File} 0 The copied {@link File}. - * @property {object} 1 The full API response. - */ -/** - * @callback CopyCallback - * @param {?Error} err Request error, if any. - * @param {File} copiedFile The copied {@link File}. - * @param {object} apiResponse The full API response. - */ -/** - * Copy this file to another file. By default, this will copy the file to the - * same bucket, but you can choose to copy it to another Bucket by providing - * a Bucket or File object or a URL starting with "gs://". - * - * @see [Objects: rewrite API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite} - * - * @throws {Error} If the destination file is not provided. - * - * @param {string|Bucket|File} destination Destination file. - * @param {object} [options] Configuration options. See an - * [Object resource](https://cloud.google.com/storage/docs/json_api/v1/objects#resource). - * @param {string} [options.destinationKmsKeyName] Resource name of the Cloud - * KMS key, of the form - * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, - * that will be used to encrypt the object. Overwrites the object metadata's - * `kms_key_name` value, if any. - * @param {string} [options.keepAcl] Retain the ACL for the new file. - * @param {string} [options.predefinedAcl] Set the ACL for the new file. - * @param {string} [options.token] A previously-returned `rewriteToken` from an - * unfinished rewrite request. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {CopyCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * - * //- - * // You can pass in a variety of types for the destination. - * // - * // For all of the below examples, assume we are working with the following - * // Bucket and File objects. - * //- - * const bucket = storage.bucket('my-bucket'); - * const file = bucket.file('my-image.png'); - * - * //- - * // If you pass in a string for the destination, the file is copied to its - * // current bucket, under the new name provided. - * //- - * file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) { - * // `my-bucket` now contains: - * // - "my-image.png" - * // - "my-image-copy.png" - * - * // `copiedFile` is an instance of a File object that refers to your new - * // file. - * }); - * - * //- - * // If you pass in a string starting with "gs://" for the destination, the - * // file is copied to the other bucket and under the new name provided. - * //- - * const newLocation = 'gs://another-bucket/my-image-copy.png'; - * file.copy(newLocation, function(err, copiedFile, apiResponse) { - * // `my-bucket` still contains: - * // - "my-image.png" - * // - * // `another-bucket` now contains: - * // - "my-image-copy.png" - * - * // `copiedFile` is an instance of a File object that refers to your new - * // file. - * }); - * - * //- - * // If you pass in a Bucket object, the file will be copied to that bucket - * // using the same name. - * //- - * const anotherBucket = storage.bucket('another-bucket'); - * file.copy(anotherBucket, function(err, copiedFile, apiResponse) { - * // `my-bucket` still contains: - * // - "my-image.png" - * // - * // `another-bucket` now contains: - * // - "my-image.png" - * - * // `copiedFile` is an instance of a File object that refers to your new - * // file. - * }); - * - * //- - * // If you pass in a File object, you have complete control over the new - * // bucket and filename. - * //- - * const anotherFile = anotherBucket.file('my-awesome-image.png'); - * file.copy(anotherFile, function(err, copiedFile, apiResponse) { - * // `my-bucket` still contains: - * // - "my-image.png" - * // - * // `another-bucket` now contains: - * // - "my-awesome-image.png" - * - * // Note: - * // The `copiedFile` parameter is equal to `anotherFile`. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.copy(newLocation).then(function(data) { - * const newFile = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_copy_file - * Another example: - */ -File.prototype.copy = function(destination, options, callback) { - const self = this; - - const noDestinationError = new Error('Destination file should have a name.'); - - if (!destination) { - throw noDestinationError; - } - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend(true, {}, options); - callback = callback || common.util.noop; - - let destBucket; - let destName; - let newFile; - - if (is.string(destination)) { - const parsedDestination = GS_URL_REGEXP.exec(destination); - if (parsedDestination !== null && parsedDestination.length === 3) { - destBucket = this.storage.bucket(parsedDestination[1]); - destName = parsedDestination[2]; - } else { - destBucket = this.bucket; - destName = destination; - } - } else if ( - destination.constructor && - destination.constructor.name === 'Bucket' - ) { - destBucket = destination; - destName = this.name; - } else if (destination instanceof File) { - destBucket = destination.bucket; - destName = destination.name; - newFile = destination; - } else { - throw noDestinationError; - } - - const query = {}; - if (is.defined(this.generation)) { - query.sourceGeneration = this.generation; - } - if (is.defined(options.token)) { - query.rewriteToken = options.token; - } - if (is.defined(options.userProject)) { - query.userProject = options.userProject; - delete options.userProject; - } - - newFile = newFile || destBucket.file(destName); - - const headers = {}; - - if (is.defined(this.encryptionKey)) { - headers['x-goog-copy-source-encryption-algorithm'] = 'AES256'; - headers['x-goog-copy-source-encryption-key'] = this.encryptionKeyBase64; - headers[ - 'x-goog-copy-source-encryption-key-sha256' - ] = this.encryptionKeyHash; - } - - if (is.defined(newFile.encryptionKey)) { - this.setEncryptionKey(newFile.encryptionKey); - } else if (is.defined(options.destinationKmsKeyName)) { - query.destinationKmsKeyName = options.destinationKmsKeyName; - delete options.destinationKmsKeyName; - } else if (is.defined(newFile.kmsKeyName)) { - query.destinationKmsKeyName = newFile.kmsKeyName; - } - - if (query.destinationKmsKeyName) { - this.kmsKeyName = query.destinationKmsKeyName; - - const keyIndex = this.interceptors.indexOf(this.encryptionKeyInterceptor); - if (keyIndex > -1) { - this.interceptors.splice(keyIndex, 1); - } - } - - this.request( - { - method: 'POST', - uri: `/rewriteTo/b/${destBucket.name}/o/${encodeURIComponent(destName)}`, - qs: query, - json: options, - headers: headers, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - if (resp.rewriteToken) { - const options = { - token: resp.rewriteToken, - }; - - if (query.userProject) { - options.userProject = query.userProject; - } - - if (query.destinationKmsKeyName) { - options.destinationKmsKeyName = query.destinationKmsKeyName; - } - - self.copy(newFile, options, callback); - return; - } - - callback(null, newFile, resp); - } - ); -}; - -/** - * Create a readable stream to read the contents of the remote file. It can be - * piped to a writable stream or listened to for 'data' events to read a file's - * contents. - * - * In the unlikely event there is a mismatch between what you downloaded and the - * version in your Bucket, your error handler will receive an error with code - * "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best recourse is - * to try downloading the file again. - * - * For faster crc32c computation, you must manually install - * [`fast-crc32c`](http://www.gitnpm.com/fast-crc32c): - * - * $ npm install --save fast-crc32c - * - * NOTE: Readable streams will emit the `end` event when the file is fully - * downloaded. - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {string|boolean} [options.validation] Possible values: `"md5"`, - * `"crc32c"`, or `false`. By default, data integrity is validated with a - * CRC32c checksum. You may use MD5 if preferred, but that hash is not - * supported for composite objects. An error will be raised if MD5 is - * specified but is not available. You may also choose to skip validation - * completely, however this is **not recommended**. - * @param {number} [options.start] A byte offset to begin the file's download - * from. Default is 0. NOTE: Byte ranges are inclusive; that is, - * `options.start = 0` and `options.end = 999` represent the first 1000 - * bytes in a file or object. NOTE: when specifying a byte range, data - * integrity is not available. - * @param {number} [options.end] A byte offset to stop reading the file at. - * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and - * `options.end = 999` represent the first 1000 bytes in a file or object. - * NOTE: when specifying a byte range, data integrity is not available. - * @returns {ReadableStream} - * - * @example - * //- - * //

Downloading a File

- * // - * // The example below demonstrates how we can reference a remote file, then - * // pipe its contents to a local file. This is effectively creating a local - * // backup of your remote data. - * //- - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * - * const fs = require('fs'); - * const remoteFile = bucket.file('image.png'); - * const localFilename = '/Users/stephen/Photos/image.png'; - * - * remoteFile.createReadStream() - * .on('error', function(err) {}) - * .on('response', function(response) { - * // Server connected and responded with the specified status and headers. - * }) - * .on('end', function() { - * // The file is fully downloaded. - * }) - * .pipe(fs.createWriteStream(localFilename)); - * - * //- - * // To limit the downloaded data to only a byte range, pass an options object. - * //- - * const logFile = myBucket.file('access_log'); - * logFile.createReadStream({ - * start: 10000, - * end: 20000 - * }) - * .on('error', function(err) {}) - * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); - * - * //- - * // To read a tail byte range, specify only `options.end` as a negative - * // number. - * //- - * const logFile = myBucket.file('access_log'); - * logFile.createReadStream({ - * end: -100 - * }) - * .on('error', function(err) {}) - * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); - */ -File.prototype.createReadStream = function(options) { - options = options || {}; - - const self = this; - const rangeRequest = is.number(options.start) || is.number(options.end); - const tailRequest = options.end < 0; - - let validateStream; // Created later, if necessary. - const throughStream = streamEvents(through()); - - let crc32c = true; - let md5 = false; - - let refreshedMetadata = false; - - if (is.string(options.validation)) { - options.validation = options.validation.toLowerCase(); - crc32c = options.validation === 'crc32c'; - md5 = options.validation === 'md5'; - } else if (options.validation === false) { - crc32c = false; - } - - if (rangeRequest) { - if (is.string(options.validation) || options.validation === true) { - throw new Error('Cannot use validation with file ranges (start/end).'); - } - // Range requests can't receive data integrity checks. - crc32c = false; - md5 = false; - } - - // Authenticate the request, then pipe the remote API request to the stream - // returned to the user. - function makeRequest() { - const reqOpts = { - forever: false, - uri: '', - headers: { - 'Accept-Encoding': 'gzip', - }, - qs: { - alt: 'media', - }, - }; - - if (self.generation) { - reqOpts.qs.generation = self.generation; - } - - if (options.userProject) { - reqOpts.qs.userProject = options.userProject; - } - - if (rangeRequest) { - const start = is.number(options.start) ? options.start : '0'; - const end = is.number(options.end) ? options.end : ''; - - reqOpts.headers.Range = `bytes=${tailRequest ? end : `${start}-${end}`}`; - } - - self - .requestStream(reqOpts) - .on('error', err => { - throughStream.destroy(err); - }) - .on('response', res => { - throughStream.emit('response', res); - common.util.handleResp(null, res, null, onResponse); - }) - .resume(); - - // We listen to the response event from the request stream so that we can... - // - // 1) Intercept any data from going to the user if an error occurred. - // 2) Calculate the hashes from the http.IncomingMessage response stream, - // which will return the bytes from the source without decompressing - // gzip'd content. We then send it through decompressed, if applicable, - // to the user. - function onResponse(err, body, rawResponseStream) { - if (err) { - // Get error message from the body. - rawResponseStream.pipe( - concat(function(body) { - err.message = body.toString(); - throughStream.destroy(err); - }) - ); - - return; - } - - const headers = rawResponseStream.toJSON().headers; - const isCompressed = headers['content-encoding'] === 'gzip'; - - const shouldRunValidation = !rangeRequest && (crc32c || md5); - - const throughStreams = []; - - if (shouldRunValidation) { - validateStream = hashStreamValidation({crc32c, md5}); - throughStreams.push(validateStream); - } - - if (isCompressed) { - throughStreams.push(zlib.createGunzip()); - } - - if (throughStreams.length === 1) { - rawResponseStream = rawResponseStream.pipe(throughStreams[0]); - } else if (throughStreams.length > 1) { - rawResponseStream = rawResponseStream.pipe(pumpify.obj(throughStreams)); - } - - rawResponseStream.on('end', onComplete).pipe(throughStream, {end: false}); - } - - // This is hooked to the `complete` event from the request stream. This is - // our chance to validate the data and let the user know if anything went - // wrong. - function onComplete(err) { - if (err) { - throughStream.destroy(err); - return; - } - - if (rangeRequest) { - throughStream.end(); - return; - } - - if (!refreshedMetadata) { - refreshedMetadata = true; - self.getMetadata({userProject: options.userProject}, onComplete); - return; - } - - const hashes = { - crc32c: self.metadata.crc32c, - md5: self.metadata.md5Hash, - }; - - // If we're doing validation, assume the worst-- a data integrity - // mismatch. If not, these tests won't be performed, and we can assume the - // best. - let failed = crc32c || md5; - - if (crc32c && hashes.crc32c) { - // We must remove the first four bytes from the returned checksum. - // http://stackoverflow.com/questions/25096737/ - // base64-encoding-of-crc32c-long-value - failed = !validateStream.test('crc32c', hashes.crc32c.substr(4)); - } - - if (md5 && hashes.md5) { - failed = !validateStream.test('md5', hashes.md5); - } - - if (md5 && !hashes.md5) { - const hashError = new Error( - [ - 'MD5 verification was specified, but is not available for the', - 'requested object. MD5 is not available for composite objects.', - ].join(' ') - ); - hashError.code = 'MD5_NOT_AVAILABLE'; - - throughStream.destroy(hashError); - } else if (failed) { - const mismatchError = new Error( - [ - 'The downloaded data did not match the data from the server.', - 'To be sure the content is the same, you should download the', - 'file again.', - ].join(' ') - ); - mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; - - throughStream.destroy(mismatchError); - } else { - throughStream.end(); - } - } - } - - throughStream.on('reading', makeRequest); - - return throughStream; -}; - -/** - * @typedef {array} CreateResumableUploadResponse - * @property {string} 0 The resumable upload's unique session URI. - */ -/** - * @callback CreateResumableUploadCallback - * @param {?Error} err Request error, if any. - * @param {string} uri The resumable upload's unique session URI. - */ -/** - * Create a unique resumable upload session URI. This is the first step when - * performing a resumable upload. - * - * See the [Resumable upload guide](https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload) - * for more on how the entire process works. - * - *

Note

- * - * If you are just looking to perform a resumable upload without worrying about - * any of the details, see {@link File#createWriteStream}. Resumable uploads - * are performed by default. - * - * @see [Resumable upload guide]{@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload} - * - * @param {object} [options] Configuration options. - * @param {object} [options.metadata] Metadata to set on the file. - * @param {string} [options.origin] Origin header to set for the upload. - * @param {string} [options.predefinedAcl] Apply a predefined set of access - * controls to this object. - * - * Acceptable values are: - * - **`authenticatedRead`** - Object owner gets `OWNER` access, and - * `allAuthenticatedUsers` get `READER` access. - * - * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and - * project team owners get `OWNER` access. - * - * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project - * team owners get `READER` access. - * - * - **`private`** - Object owner gets `OWNER` access. - * - * - **`projectPrivate`** - Object owner gets `OWNER` access, and project - * team members get access according to their roles. - * - * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` get - * `READER` access. - * @param {boolean} [options.private] Make the uploaded file private. (Alias for - * `options.predefinedAcl = 'private'`) - * @param {boolean} [options.public] Make the uploaded file public. (Alias for - * `options.predefinedAcl = 'publicRead'`) - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {CreateResumableUploadCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * file.createResumableUpload(function(err, uri) { - * if (!err) { - * // `uri` can be used to PUT data to. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.createResumableUpload().then(function(data) { - * const uri = data[0]; - * }); - */ -File.prototype.createResumableUpload = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - resumableUpload.createURI( - { - authClient: this.storage.authClient, - bucket: this.bucket.name, - file: this.name, - generation: this.generation, - key: this.encryptionKey, - kmsKeyName: this.kmsKeyName, - metadata: options.metadata, - offset: options.offset, - origin: options.origin, - predefinedAcl: options.predefinedAcl, - private: options.private, - public: options.public, - userProject: options.userProject, - }, - callback - ); -}; - -/** - * Create a writable stream to overwrite the contents of the file in your - * bucket. - * - * A File object can also be used to create files for the first time. - * - * Resumable uploads are automatically enabled and must be shut off explicitly - * by setting `options.resumable` to `false`. - * - * Resumable uploads require write access to the $HOME directory. Through - * [`config-store`](http://www.gitnpm.com/configstore), some metadata is stored. - * By default, if the directory is not writable, we will fall back to a simple - * upload. However, if you explicitly request a resumable upload, and we cannot - * write to the config directory, we will return a `ResumableUploadError`. - * - *

- * There is some overhead when using a resumable upload that can cause - * noticeable performance degradation while uploading a series of small files. - * When uploading files less than 10MB, it is recommended that the resumable - * feature is disabled. - *

- * - * For faster crc32c computation, you must manually install - * [`fast-crc32c`](http://www.gitnpm.com/fast-crc32c): - * - * $ npm install --save fast-crc32c - * - * NOTE: Writable streams will emit the `finish` event when the file is fully - * uploaded. - * - * @see [Upload Options (Simple or Resumable)]{@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload} - * @see [Objects: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert} - * - * @param {object} [options] Configuration options. - * @param {string} [options.contentType] Alias for - * `options.metadata.contentType`. If set to `auto`, the file name is used - * to determine the contentType. - * @param {string|boolean} [options.gzip] If true, automatically gzip the file. - * If set to `auto`, the contentType is used to determine if the file should - * be gzipped. This will set `options.metadata.contentEncoding` to `gzip` if - * necessary. - * @param {object} [options.metadata] See the examples below or - * [Objects: insert request body](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON) - * for more details. - * @param {string} [options.offset] The starting byte of the upload stream, for - * resuming an interrupted upload. Defaults to 0. - * @param {string} [options.predefinedAcl] Apply a predefined set of access - * controls to this object. - * - * Acceptable values are: - * - **`authenticatedRead`** - Object owner gets `OWNER` access, and - * `allAuthenticatedUsers` get `READER` access. - * - * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and - * project team owners get `OWNER` access. - * - * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project - * team owners get `READER` access. - * - * - **`private`** - Object owner gets `OWNER` access. - * - * - **`projectPrivate`** - Object owner gets `OWNER` access, and project - * team members get access according to their roles. - * - * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` get - * `READER` access. - * @param {boolean} [options.private] Make the uploaded file private. (Alias for - * `options.predefinedAcl = 'private'`) - * @param {boolean} [options.public] Make the uploaded file public. (Alias for - * `options.predefinedAcl = 'publicRead'`) - * @param {boolean} [options.resumable] Force a resumable upload. NOTE: When - * working with streams, the file format and size is unknown until it's - * completely consumed. Because of this, it's best for you to be explicit - * for what makes sense given your input. - * @param {string} [options.uri] The URI for an already-created resumable - * upload. See {@link File#createResumableUpload}. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {string|boolean} [options.validation] Possible values: `"md5"`, - * `"crc32c"`, or `false`. By default, data integrity is validated with a - * CRC32c checksum. You may use MD5 if preferred, but that hash is not - * supported for composite objects. An error will be raised if MD5 is - * specified but is not available. You may also choose to skip validation - * completely, however this is **not recommended**. - * @returns {WritableStream} - * - * @example - * const fs = require('fs'); - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * //- - * //

Uploading a File

- * // - * // Now, consider a case where we want to upload a file to your bucket. You - * // have the option of using {@link Bucket#upload}, but that is just - * // a convenience method which will do the following. - * //- - * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') - * .pipe(file.createWriteStream()) - * .on('error', function(err) {}) - * .on('finish', function() { - * // The file upload is complete. - * }); - * - * //- - * //

Uploading a File with gzip compression

- * //- - * fs.createReadStream('/Users/stephen/site/index.html') - * .pipe(file.createWriteStream({ gzip: true })) - * .on('error', function(err) {}) - * .on('finish', function() { - * // The file upload is complete. - * }); - * - * //- - * // Downloading the file with `createReadStream` will automatically decode the - * // file. - * //- - * - * //- - * //

Uploading a File with Metadata

- * // - * // One last case you may run into is when you want to upload a file to your - * // bucket and set its metadata at the same time. Like above, you can use - * // {@link Bucket#upload} to do this, which is just a wrapper around - * // the following. - * //- - * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') - * .pipe(file.createWriteStream({ - * metadata: { - * contentType: 'image/jpeg', - * metadata: { - * custom: 'metadata' - * } - * } - * })) - * .on('error', function(err) {}) - * .on('finish', function() { - * // The file upload is complete. - * }); - */ -File.prototype.createWriteStream = function(options) { - options = options || {}; - - const self = this; - - options = extend({metadata: {}}, options); - - if (options.contentType) { - options.metadata.contentType = options.contentType; - - if (options.metadata.contentType === 'auto') { - options.metadata.contentType = mime.getType(this.name); - } - } - - let gzip = options.gzip; - - if (gzip === 'auto') { - gzip = compressible(options.metadata.contentType); - } - - if (gzip) { - options.metadata.contentEncoding = 'gzip'; - } - - let crc32c = true; - let md5 = false; - - if (is.string(options.validation)) { - options.validation = options.validation.toLowerCase(); - crc32c = options.validation === 'crc32c'; - md5 = options.validation === 'md5'; - } else if (options.validation === false) { - crc32c = false; - } - - // Collect data as it comes in to store in a hash. This is compared to the - // checksum value on the returned metadata from the API. - const validateStream = hashStreamValidation({ - crc32c: crc32c, - md5: md5, - }); - - const fileWriteStream = duplexify(); - - const stream = streamEvents( - pumpify([ - gzip ? zlib.createGzip() : through(), - validateStream, - fileWriteStream, - ]) - ); - - // Wait until we've received data to determine what upload technique to use. - stream.on('writing', function() { - if (options.resumable === false) { - self.startSimpleUpload_(fileWriteStream, options); - return; - } - - // Same as configstore: - // https://github.com/yeoman/configstore/blob/f09f067e50e6a636cfc648a6fc36a522062bd49d/index.js#L11 - const configDir = xdgBasedir.config || os.tmpdir(); - - fs.access(configDir, fs.W_OK, function(err) { - if (err) { - if (options.resumable) { - const error = new ResumableUploadError( - [ - 'A resumable upload could not be performed. The directory,', - `${configDir}, is not writable. You may try another upload,`, - 'this time setting `options.resumable` to `false`.', - ].join(' ') - ); - stream.destroy(error); - return; - } - - // User didn't care, resumable or not. Fall back to simple upload. - self.startSimpleUpload_(fileWriteStream, options); - return; - } - - self.startResumableUpload_(fileWriteStream, options); - }); - }); - - fileWriteStream.on('response', stream.emit.bind(stream, 'response')); - - // This is to preserve the `finish` event. We wait until the request stream - // emits "complete", as that is when we do validation of the data. After that - // is successful, we can allow the stream to naturally finish. - // - // Reference for tracking when we can use a non-hack solution: - // https://github.com/nodejs/node/pull/2314 - fileWriteStream.on('prefinish', function() { - stream.cork(); - }); - - // Compare our hashed version vs the completed upload's version. - fileWriteStream.on('complete', function() { - const metadata = self.metadata; - - // If we're doing validation, assume the worst-- a data integrity mismatch. - // If not, these tests won't be performed, and we can assume the best. - let failed = crc32c || md5; - - if (crc32c && metadata.crc32c) { - // We must remove the first four bytes from the returned checksum. - // http://stackoverflow.com/questions/25096737/ - // base64-encoding-of-crc32c-long-value - failed = !validateStream.test('crc32c', metadata.crc32c.substr(4)); - } - - if (md5 && metadata.md5Hash) { - failed = !validateStream.test('md5', metadata.md5Hash); - } - - if (failed) { - self.delete(function(err) { - let code; - let message; - - if (err) { - code = 'FILE_NO_UPLOAD_DELETE'; - message = [ - 'The uploaded data did not match the data from the server. As a', - 'precaution, we attempted to delete the file, but it was not', - 'successful. To be sure the content is the same, you should try', - 'removing the file manually, then uploading the file again.', - '\n\nThe delete attempt failed with this message:', - '\n\n ' + err.message, - ].join(' '); - } else if (md5 && !metadata.md5Hash) { - code = 'MD5_NOT_AVAILABLE'; - message = [ - 'MD5 verification was specified, but is not available for the', - 'requested object. MD5 is not available for composite objects.', - ].join(' '); - } else { - code = 'FILE_NO_UPLOAD'; - message = [ - 'The uploaded data did not match the data from the server. As a', - 'precaution, the file has been deleted. To be sure the content', - 'is the same, you should try uploading the file again.', - ].join(' '); - } - - const error = new Error(message); - error.code = code; - error.errors = [err]; - - fileWriteStream.destroy(error); - }); - - return; - } - - stream.uncork(); - }); - - return stream; -}; - -/** - * @typedef {array} DeleteFileResponse - * @property {object} 0 The full API response. - */ -/** - * @callback DeleteFileCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Delete the file. - * - * @see [Objects: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {DeleteFileCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * file.delete(function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.delete().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_delete_file - * Another example: - */ -File.prototype.delete = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend({}, this.requestQueryObject, options); - - this.parent.delete.call(this, options, callback); -}; - -/** - * @typedef {array} DownloadResponse - * @property {object} [0] The contents of a File. - */ -/** - * @callback DownloadCallback - * @param {?Error} err Request error, if any. - * @param {buffer} [contents] The contents of a File. - */ -/** - * Convenience method to download a file into memory or to a local destination. - * - * @param {object} [options] Configuration options. The arguments match those - * passed to {@link File#createReadStream}. - * @param {string} [options.destination] Local file path to write the file's - * contents to. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {DownloadCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * //- - * // Download a file into memory. The contents will be available as the second - * // argument in the demonstration below, `contents`. - * //- - * file.download(function(err, contents) {}); - * - * //- - * // Download a file to a local destination. - * //- - * file.download({ - * destination: '/Users/me/Desktop/file-backup.txt' - * }, function(err) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.download().then(function(data) { - * const contents = data[0]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_download_file - * Another example: - * - * @example include:samples/encryption.js - * region_tag:storage_download_encrypted_file - * Example of downloading an encrypted file: - * - * @example include:samples/requesterPays.js - * region_tag:storage_download_file_requester_pays - * Example of downloading a file where the requester pays: - */ -File.prototype.download = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - callback = once(callback); - - const destination = options.destination; - delete options.destination; - - const fileStream = this.createReadStream(options); - - if (destination) { - fileStream - .on('error', callback) - .pipe(fs.createWriteStream(destination)) - .on('error', callback) - .on('finish', callback); - } else { - fileStream.on('error', callback).pipe(concat(callback.bind(null, null))); - } -}; - -/** - * @typedef {array} FileExistsResponse - * @property {boolean} 0 Whether the {@link File} exists. - */ -/** - * @callback FileExistsCallback - * @param {?Error} err Request error, if any. - * @param {boolean} exists Whether the {@link File} exists. - */ -/** - * Check if the file exists. - * - * @param {options} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {FileExistsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * file.exists(function(err, exists) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.exists().then(function(data) { - * const exists = data[0]; - * }); - */ -File.prototype.exists = function(options, callback) { - this.parent.exists.call(this, options, callback); -}; - -/** - * The Storage API allows you to use a custom key for server-side encryption. - * - * @see [Customer-supplied Encryption Keys]{@link https://cloud.google.com/storage/docs/encryption#customer-supplied} - * - * @param {string|buffer} encryptionKey An AES-256 encryption key. - * @returns {File} - * - * @example - * const crypto = require('crypto'); - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const encryptionKey = crypto.randomBytes(32); - * - * const fileWithCustomEncryption = myBucket.file('my-file'); - * fileWithCustomEncryption.setEncryptionKey(encryptionKey); - * - * const fileWithoutCustomEncryption = myBucket.file('my-file'); - * - * fileWithCustomEncryption.save('data', function(err) { - * // Try to download with the File object that hasn't had - * // `setEncryptionKey()` called: - * fileWithoutCustomEncryption.download(function(err) { - * // We will receive an error: - * // err.message === 'Bad Request' - * - * // Try again with the File object we called `setEncryptionKey()` on: - * fileWithCustomEncryption.download(function(err, contents) { - * // contents.toString() === 'data' - * }); - * }); - * }); - * - * @example include:samples/encryption.js - * region_tag:storage_upload_encrypted_file - * Example of uploading an encrypted file: - * - * @example include:samples/encryption.js - * region_tag:storage_download_encrypted_file - * Example of downloading an encrypted file: - */ -File.prototype.setEncryptionKey = function(encryptionKey) { - const self = this; - - this.encryptionKey = encryptionKey; - this.encryptionKeyBase64 = Buffer.from(encryptionKey).toString('base64'); - - this.encryptionKeyHash = crypto - .createHash('sha256') - .update(this.encryptionKeyBase64, 'base64') - .digest('base64'); - - this.encryptionKeyInterceptor = { - request: function(reqOpts) { - reqOpts.headers = reqOpts.headers || {}; - reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; - reqOpts.headers['x-goog-encryption-key'] = self.encryptionKeyBase64; - reqOpts.headers['x-goog-encryption-key-sha256'] = self.encryptionKeyHash; - return reqOpts; - }, - }; - - this.interceptors.push(this.encryptionKeyInterceptor); - - return this; -}; - -/** - * @typedef {array} GetFileResponse - * @property {File} 0 The {@link File}. - * @property {object} 1 The full API response. - */ -/** - * @callback GetFileCallback - * @param {?Error} err Request error, if any. - * @param {File} file The {@link File}. - * @param {object} apiResponse The full API response. - */ -/** - * Get a file object and its metadata if it exists. - * - * @param {options} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetFileCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * file.get(function(err, file, apiResponse) { - * // file.metadata` has been populated. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.get().then(function(data) { - * const file = data[0]; - * const apiResponse = data[1]; - * }); - */ -File.prototype.get = function(options, callback) { - this.parent.get.call(this, options, callback); -}; - -/** - * @typedef {array} GetFileMetadataResponse - * @property {object} 0 The {@link File} metadata. - * @property {object} 1 The full API response. - */ -/** - * @callback GetFileMetadataCallback - * @param {?Error} err Request error, if any. - * @param {object} metadata The {@link File} metadata. - * @param {object} apiResponse The full API response. - */ -/** - * Get the file's metadata. - * - * @see [Objects: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/get} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetFileMetadataCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * file.getMetadata(function(err, metadata, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.getMetadata().then(function(data) { - * const metadata = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_get_metadata - * Another example: - */ -File.prototype.getMetadata = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend({}, this.requestQueryObject, options); - - this.parent.getMetadata.call(this, options, callback); -}; - -/** - * @typedef {array} GetSignedPolicyResponse - * @property {object} 0 The document policy. - */ -/** - * @callback GetSignedPolicyCallback - * @param {?Error} err Request error, if any. - * @param {object} policy The document policy. - */ -/** - * Get a signed policy document to allow a user to upload data with a POST - * request. - * - * In Google Cloud Platform environments, such as Cloud Functions and App - * Engine, you usually don't provide a `keyFilename` or `credentials` during - * instantiation. In those environments, we call the - * [signBlob API](https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob#authorization-scopes) - * to create a signed policy. That API requires either the - * `https://www.googleapis.com/auth/iam` or - * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are - * enabled. - * - * @see [Policy Document Reference]{@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument} - * - * @throws {Error} If an expiration timestamp from the past is given. - * @throws {Error} If options.equals has an array with less or more than two - * members. - * @throws {Error} If options.startsWith has an array with less or more than two - * members. - * - * @param {object} options Configuration options. - * @param {array|array[]} [options.equals] Array of request parameters and - * their expected value (e.g. [['$', '']]). Values are - * translated into equality constraints in the conditions field of the - * policy document (e.g. ['eq', '$', '']). If only one - * equality condition is to be specified, options.equals can be a one- - * dimensional array (e.g. ['$', '']). - * @param {*} options.expires - A timestamp when this policy will expire. Any - * value given is passed to `new Date()`. - * @param {array|array[]} [options.startsWith] Array of request parameters and - * their expected prefixes (e.g. [['$', '']). Values are - * translated into starts-with constraints in the conditions field of the - * policy document (e.g. ['starts-with', '$', '']). If only - * one prefix condition is to be specified, options.startsWith can be a one- - * dimensional array (e.g. ['$', '']). - * @param {string} [options.acl] ACL for the object from possibly predefined - * ACLs. - * @param {string} [options.successRedirect] The URL to which the user client - * is redirected if the upload is successful. - * @param {string} [options.successStatus] - The status of the Google Storage - * response if the upload is successful (must be string). - * @param {object} [options.contentLengthRange] - * @param {number} [options.contentLengthRange.min] Minimum value for the - * request's content length. - * @param {number} [options.contentLengthRange.max] Maximum value for the - * request's content length. - * @param {GetSignedPolicyCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * const options = { - * equals: ['$Content-Type', 'image/jpeg'], - * expires: '10-25-2022', - * contentLengthRange: { - * min: 0, - * max: 1024 - * } - * }; - * - * file.getSignedPolicy(options, function(err, policy) { - * // policy.string: the policy document in plain text. - * // policy.base64: the policy document in base64. - * // policy.signature: the policy signature in base64. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.getSignedPolicy(options).then(function(data) { - * const policy = data[0]; - * }); - */ -File.prototype.getSignedPolicy = function(options, callback) { - const expires = new Date(options.expires); - - if (expires < Date.now()) { - throw new Error('An expiration date cannot be in the past.'); - } - - options = extend({}, options); - - const conditions = [ - ['eq', '$key', this.name], - { - bucket: this.bucket.name, - }, - ]; - - if (is.array(options.equals)) { - if (!is.array(options.equals[0])) { - options.equals = [options.equals]; - } - options.equals.forEach(function(condition) { - if (!is.array(condition) || condition.length !== 2) { - throw new Error('Equals condition must be an array of 2 elements.'); - } - conditions.push(['eq', condition[0], condition[1]]); - }); - } - - if (is.array(options.startsWith)) { - if (!is.array(options.startsWith[0])) { - options.startsWith = [options.startsWith]; - } - options.startsWith.forEach(function(condition) { - if (!is.array(condition) || condition.length !== 2) { - throw new Error('StartsWith condition must be an array of 2 elements.'); - } - conditions.push(['starts-with', condition[0], condition[1]]); - }); - } - - if (options.acl) { - conditions.push({ - acl: options.acl, - }); - } - - if (options.successRedirect) { - conditions.push({ - success_action_redirect: options.successRedirect, - }); - } - - if (options.successStatus) { - conditions.push({ - success_action_status: options.successStatus, - }); - } - - if (options.contentLengthRange) { - const min = options.contentLengthRange.min; - const max = options.contentLengthRange.max; - if (!is.number(min) || !is.number(max)) { - throw new Error('ContentLengthRange must have numeric min & max fields.'); - } - conditions.push(['content-length-range', min, max]); - } - - const policy = { - expiration: expires.toISOString(), - conditions: conditions, - }; - - const policyString = JSON.stringify(policy); - const policyBase64 = Buffer.from(policyString).toString('base64'); - - this.storage.authClient.sign(policyBase64, function(err, signature) { - if (err) { - callback(new SigningError(err.message)); - return; - } - - callback(null, { - string: policyString, - base64: policyBase64, - signature: signature, - }); - }); -}; - -/** - * @typedef {array} GetSignedUrlResponse - * @property {object} 0 The signed URL. - */ -/** - * @callback GetSignedUrlCallback - * @param {?Error} err Request error, if any. - * @param {object} url The signed URL. - */ -/** - * Get a signed URL to allow limited time access to the file. - * - * In Google Cloud Platform environments, such as Cloud Functions and App - * Engine, you usually don't provide a `keyFilename` or `credentials` during - * instantiation. In those environments, we call the - * [signBlob API](https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob#authorization-scopes) - * to create a signed URL. That API requires either the - * `https://www.googleapis.com/auth/iam` or - * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are - * enabled. - * - * @see [Signed URLs Reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls} - * - * @throws {Error} if an expiration timestamp from the past is given. - * - * @param {object} config Configuration object. - * @param {string} config.action "read" (HTTP: GET), "write" (HTTP: PUT), or - * "delete" (HTTP: DELETE), "resumable" (HTTP: POST). - * @param {string} [config.cname] The cname for this bucket, i.e., - * "https://cdn.example.com". - * @param {string} [config.contentMd5] The MD5 digest value in base64. If you - * provide this, the client must provide this HTTP header with this same - * value in its request. - * @param {string} [config.contentType] If you provide this value, the client - * must provide this HTTP header set to the same value. - * @param {*} config.expires A timestamp when this link will expire. Any value - * given is passed to `new Date()`. - * @param {object} [config.extensionHeaders] If these headers are used, the - * server will check to make sure that the client provides matching values. - * See [Canonical extension headers](https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers) - * for the requirements of this feature, most notably: - * - The header name must be prefixed with `x-goog-` - * - The header name must be all lowercase - * @param {string} [config.promptSaveAs] The filename to prompt the user to - * save the file as when the signed url is accessed. This is ignored if - * `config.responseDisposition` is set. - * @param {string} [config.responseDisposition] The - * [response-content-disposition parameter](http://goo.gl/yMWxQV) of the - * signed url. - * @param {string} [config.responseType] The response-content-type parameter - * of the signed url. - * @param {GetSignedUrlCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * //- - * // Generate a URL that allows temporary access to download your file. - * //- - * const request = require('request'); - * - * const config = { - * action: 'read', - * expires: '03-17-2025' - * }; - * - * file.getSignedUrl(config, function(err, url) { - * if (err) { - * console.error(err); - * return; - * } - * - * // The file is now available to read from this URL. - * request(url, function(err, resp) { - * // resp.statusCode = 200 - * }); - * }); - * - * //- - * // Generate a URL to allow write permissions. This means anyone with this URL - * // can send a POST request with new data that will overwrite the file. - * //- - * file.getSignedUrl({ - * action: 'write', - * expires: '03-17-2025' - * }, function(err, url) { - * if (err) { - * console.error(err); - * return; - * } - * - * // The file is now available to be written to. - * const writeStream = request.put(url); - * writeStream.end('New data'); - * - * writeStream.on('complete', function(resp) { - * // Confirm the new content was saved. - * file.download(function(err, fileContents) { - * console.log('Contents:', fileContents.toString()); - * // Contents: New data - * }); - * }); - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.getSignedUrl(config).then(function(data) { - * const url = data[0]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_generate_signed_url - * Another example: - */ -File.prototype.getSignedUrl = function(config, callback) { - const self = this; - const expires = new Date(config.expires); - const expiresInSeconds = Math.round(expires / 1000); // The API expects seconds. - - if (expires < Date.now()) { - throw new Error('An expiration date cannot be in the past.'); - } - - config = extend({}, config); - - config.action = { - read: 'GET', - write: 'PUT', - delete: 'DELETE', - resumable: 'POST', - }[config.action]; - - const name = encodeURIComponent(this.name); - config.resource = '/' + this.bucket.name + '/' + name; - - let extensionHeadersString = ''; - - if (config.action === 'POST') { - config.extensionHeaders = extend({}, config.extensionHeaders, { - 'x-goog-resumable': 'start', - }); - } - - if (config.extensionHeaders) { - for (const headerName in config.extensionHeaders) { - extensionHeadersString += `${headerName}:${ - config.extensionHeaders[headerName] - }\n`; - } - } - - const blobToSign = [ - config.action, - config.contentMd5 || '', - config.contentType || '', - expiresInSeconds, - extensionHeadersString + config.resource, - ].join('\n'); - - const authClient = this.storage.authClient; - - authClient.sign(blobToSign, function(err, signature) { - if (err) { - callback(new SigningError(err.message)); - return; - } - - const query = { - GoogleAccessId: authClient.credentials.client_email, - Expires: expiresInSeconds, - Signature: signature, - }; - - if (is.string(config.responseType)) { - query['response-content-type'] = config.responseType; - } - - if (is.string(config.promptSaveAs)) { - query['response-content-disposition'] = - 'attachment; filename="' + config.promptSaveAs + '"'; - } - if (is.string(config.responseDisposition)) { - query['response-content-disposition'] = config.responseDisposition; - } - - if (self.generation) { - query.generation = self.generation; - } - - const parsedHost = url.parse(config.cname || STORAGE_DOWNLOAD_BASE_URL); - const signedUrl = url.format({ - protocol: parsedHost.protocol, - hostname: parsedHost.hostname, - pathname: self.bucket.name + '/' + name, - query: query, - }); - - callback(null, signedUrl); - }); -}; - -/** - * @typedef {array} MakeFilePrivateResponse - * @property {object} 0 The full API response. - */ -/** - * @callback MakeFilePrivateCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Make a file private to the project and remove all other permissions. - * Set `options.strict` to true to make the file private to only the owner. - * - * @see [Objects: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch} - * - * @param {object} [options] Configuration options. - * @param {boolean} [options.strict] If true, set the file to be private to - * only the owner user. Otherwise, it will be private to the project. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {MakeFilePrivateCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * //- - * // Set the file private so only project maintainers can see and modify it. - * //- - * file.makePrivate(function(err) {}); - * - * //- - * // Set the file private so only the owner can see and modify it. - * //- - * file.makePrivate({ strict: true }, function(err) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.makePrivate().then(function(data) { - * const apiResponse = data[0]; - * }); - */ -File.prototype.makePrivate = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - const query = { - predefinedAcl: options.strict ? 'private' : 'projectPrivate', - }; - - if (options.userProject) { - query.userProject = options.userProject; - } - - this.setMetadata( - { - // You aren't allowed to set both predefinedAcl & acl properties on a file, - // so acl must explicitly be nullified, destroying all previous acls on the - // file. - acl: null, - }, - query, - callback - ); -}; - -/** - * @typedef {array} MakeFilePublicResponse - * @property {object} 0 The full API response. - */ -/** - * @callback MakeFilePublicCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Set a file to be publicly readable and maintain all previous permissions. - * - * @see [ObjectAccessControls: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert} - * - * @param {MakeFilePublicCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * file.makePublic(function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.makePublic().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_make_public - * Another example: - */ -File.prototype.makePublic = function(callback) { - callback = callback || common.util.noop; - - this.acl.add( - { - entity: 'allUsers', - role: 'READER', - }, - function(err, resp) { - callback(err, resp); - } - ); -}; - -/** - * @typedef {array} MoveResponse - * @property {File} 0 The destination File. - * @property {object} 1 The full API response. - */ -/** - * @callback MoveCallback - * @param {?Error} err Request error, if any. - * @param {File} destinationFile The destination File. - * @param {object} apiResponse The full API response. - */ -/** - * Move this file to another location. By default, this will rename the file - * and keep it in the same bucket, but you can choose to move it to another - * Bucket by providing a Bucket or File object or a URL beginning with "gs://". - * - * **Warning**: - * There is currently no atomic `move` method in the Cloud Storage API, - * so this method is a composition of {@link File#copy} (to the new - * location) and {@link File#delete} (from the old location). While - * unlikely, it is possible that an error returned to your callback could be - * triggered from either one of these API calls failing, which could leave a - * duplicate file lingering. - * - * @see [Objects: copy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/copy} - * - * @throws {Error} If the destination file is not provided. - * - * @param {string|Bucket|File} destination Destination file. - * @param {object} [options] Configuration options. See an - * [Object resource](https://cloud.google.com/storage/docs/json_api/v1/objects#resource). - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {MoveCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * //- - * // You can pass in a variety of types for the destination. - * // - * // For all of the below examples, assume we are working with the following - * // Bucket and File objects. - * //- - * const bucket = storage.bucket('my-bucket'); - * const file = bucket.file('my-image.png'); - * - * //- - * // If you pass in a string for the destination, the file is moved to its - * // current bucket, under the new name provided. - * //- - * file.move('my-image-new.png', function(err, destinationFile, apiResponse) { - * // `my-bucket` no longer contains: - * // - "my-image.png" - * // but contains instead: - * // - "my-image-new.png" - * - * // `destinationFile` is an instance of a File object that refers to your - * // new file. - * }); - * - * //- - * // If you pass in a string starting with "gs://" for the destination, the - * // file is copied to the other bucket and under the new name provided. - * //- - * const newLocation = 'gs://another-bucket/my-image-new.png'; - * file.move(newLocation, function(err, destinationFile, apiResponse) { - * // `my-bucket` no longer contains: - * // - "my-image.png" - * // - * // `another-bucket` now contains: - * // - "my-image-new.png" - * - * // `destinationFile` is an instance of a File object that refers to your - * // new file. - * }); - * - * //- - * // If you pass in a Bucket object, the file will be moved to that bucket - * // using the same name. - * //- - * const anotherBucket = gcs.bucket('another-bucket'); - * - * file.move(anotherBucket, function(err, destinationFile, apiResponse) { - * // `my-bucket` no longer contains: - * // - "my-image.png" - * // - * // `another-bucket` now contains: - * // - "my-image.png" - * - * // `destinationFile` is an instance of a File object that refers to your - * // new file. - * }); - * - * //- - * // If you pass in a File object, you have complete control over the new - * // bucket and filename. - * //- - * const anotherFile = anotherBucket.file('my-awesome-image.png'); - * - * file.move(anotherFile, function(err, destinationFile, apiResponse) { - * // `my-bucket` no longer contains: - * // - "my-image.png" - * // - * // `another-bucket` now contains: - * // - "my-awesome-image.png" - * - * // Note: - * // The `destinationFile` parameter is equal to `anotherFile`. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.move('my-image-new.png').then(function(data) { - * const destinationFile = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/files.js - * region_tag:storage_move_file - * Another example: - */ -File.prototype.move = function(destination, options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - callback = callback || common.util.noop; - - this.copy(destination, options, function(err, destinationFile, apiResponse) { - if (err) { - callback(err, null, apiResponse); - return; - } - - self.delete(options, function(err, apiResponse) { - callback(err, destinationFile, apiResponse); - }); - }); -}; - -/** - * Makes request and applies userProject query parameter if necessary. - * - * @private - * - * @param {object} reqOpts - The request options. - * @param {function} callback - The callback function. - */ -File.prototype.request = function(reqOpts, callback) { - if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) { - reqOpts.qs = extend(reqOpts.qs, {userProject: this.userProject}); - } - - return common.ServiceObject.prototype.request.call(this, reqOpts, callback); -}; - -/** - * This method allows you to update the encryption key associated with this - * file. - * - * @see [Customer-supplied Encryption Keys]{@link https://cloud.google.com/storage/docs/encryption#customer-supplied} - * - * @param {string|buffer|object} options If a string or Buffer is provided, it - * is interpreted as an AES-256, customer-supplied encryption key. If you'd - * like to use a Cloud KMS key name, you must specify an options object with - * the property name: `kmsKeyName`. - * @param {string|buffer} [options.encryptionKey] An AES-256 encryption key. - * @param {string} [options.kmsKeyName] A Cloud KMS key name. - * @returns {File} - * - * @example include:samples/encryption.js - * region_tag:storage_rotate_encryption_key - * Example of rotating the encryption key for this file: - */ -File.prototype.rotateEncryptionKey = function(options, callback) { - if (!is.object(options)) { - options = { - encryptionKey: options, - }; - } - - const newFile = this.bucket.file(this.id, options); - this.copy(newFile, callback); -}; - -/** - * @callback SaveCallback - * @param {?Error} err Request error, if any. - */ -/** - * Write arbitrary data to a file. - * - * *This is a convenience method which wraps {@link File#createWriteStream}.* - * - * Resumable uploads are automatically enabled and must be shut off explicitly - * by setting `options.resumable` to `false`. - * - *

- * There is some overhead when using a resumable upload that can cause - * noticeable performance degradation while uploading a series of small files. - * When uploading files less than 10MB, it is recommended that the resumable - * feature is disabled. - *

- * - * @param {*} data The data to write to a file. - * @param {object} [options] See {@link File#createWriteStream}'s `options` - * parameter. - * @param {SaveCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * const contents = 'This is the contents of the file.'; - * - * file.save(contents, function(err) { - * if (!err) { - * // File written successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.save(contents).then(function() {}); - */ -File.prototype.save = function(data, options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.createWriteStream(options) - .on('error', callback) - .on('finish', callback) - .end(data); -}; - -/** - * @typedef {array} SetFileMetadataResponse - * @property {object} 0 The full API response. - */ -/** - * @callback SetFileMetadataCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Merge the given metadata with the current remote file's metadata. This - * will set metadata if it was previously unset or update previously set - * metadata. To unset previously set metadata, set its value to null. - * - * You can set custom key/value pairs in the metadata key of the given - * object, however the other properties outside of this object must adhere - * to the [official API documentation](https://goo.gl/BOnnCK). - * - * See the examples below for more information. - * - * @see [Objects: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch} - * - * @param {object} [metadata] The metadata you wish to update. - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {SetFileMetadataCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const file = myBucket.file('my-file'); - * - * const metadata = { - * contentType: 'application/x-font-ttf', - * metadata: { - * my: 'custom', - * properties: 'go here' - * } - * }; - * - * file.setMetadata(metadata, function(err, apiResponse) {}); - * - * // Assuming current metadata = { hello: 'world', unsetMe: 'will do' } - * file.setMetadata({ - * metadata: { - * abc: '123', // will be set. - * unsetMe: null, // will be unset (deleted). - * hello: 'goodbye' // will be updated from 'hello' to 'goodbye'. - * } - * }, function(err, apiResponse) { - * // metadata should now be { abc: '123', hello: 'goodbye' } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.setMetadata(metadata).then(function(data) { - * const apiResponse = data[0]; - * }); - */ -File.prototype.setMetadata = function(metadata, options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend({}, this.requestQueryObject, options); - - this.parent.setMetadata.call(this, metadata, options, callback); -}; - -/** - * @typedef {array} SetStorageClassResponse - * @property {object} 0 The full API response. - */ -/** - * @callback SetStorageClassCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Set the storage class for this file. - * - * @see [Per-Object Storage Class]{@link https://cloud.google.com/storage/docs/per-object-storage-class} - * @see [Storage Classes]{@link https://cloud.google.com/storage/docs/storage-classes} - * - * @param {string} storageClass The new storage class. (`multi_regional`, - * `regional`, `nearline`, `coldline`) - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {SetStorageClassCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * file.setStorageClass('regional', function(err, apiResponse) { - * if (err) { - * // Error handling omitted. - * } - * - * // The storage class was updated successfully. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * file.setStorageClass('regional').then(function() {}); - */ -File.prototype.setStorageClass = function(storageClass, options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend(true, {}, options); - - // In case we get input like `storageClass`, convert to `storage_class`. - options.storageClass = storageClass - .replace(/-/g, '_') - .replace(/([a-z])([A-Z])/g, function(_, low, up) { - return low + '_' + up; - }) - .toUpperCase(); - - this.copy(this, options, function(err, file, apiResponse) { - if (err) { - callback(err, apiResponse); - return; - } - - self.metadata = file.metadata; - - callback(null, apiResponse); - }); -}; - -/** - * Set a user project to be billed for all requests made from this File object. - * - * @param {string} userProject The user project. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('albums'); - * const file = bucket.file('my-file'); - * - * file.setUserProject('grape-spaceship-123'); - */ -File.prototype.setUserProject = function(userProject) { - this.userProject = userProject; -}; - -/** - * This creates a gcs-resumable-upload upload stream. - * - * @see [gcs-resumable-upload]{@link https://github.com/stephenplusplus/gcs-resumable-upload} - * - * @param {Duplexify} stream - Duplexify stream of data to pipe to the file. - * @param {object=} options - Configuration object. - * - * @private - */ -File.prototype.startResumableUpload_ = function(dup, options) { - const self = this; - - options = extend( - { - metadata: {}, - }, - options - ); - - const uploadStream = resumableUpload({ - authClient: this.storage.authClient, - bucket: this.bucket.name, - file: this.name, - generation: this.generation, - key: this.encryptionKey, - kmsKeyName: this.kmsKeyName, - metadata: options.metadata, - offset: options.offset, - predefinedAcl: options.predefinedAcl, - private: options.private, - public: options.public, - uri: options.uri, - userProject: options.userProject, - }); - - uploadStream - .on('response', function(resp) { - dup.emit('response', resp); - }) - .on('metadata', function(metadata) { - self.metadata = metadata; - }) - .on('finish', function() { - dup.emit('complete'); - }); - - dup.setWritable(uploadStream); -}; - -/** - * Takes a readable stream and pipes it to a remote file. Unlike - * `startResumableUpload_`, which uses the resumable upload technique, this - * method uses a simple upload (all or nothing). - * - * @param {Duplexify} dup - Duplexify stream of data to pipe to the file. - * @param {object=} options - Configuration object. - * - * @private - */ -File.prototype.startSimpleUpload_ = function(dup, options) { - const self = this; - - options = extend( - { - metadata: {}, - }, - options - ); - - const reqOpts = { - qs: { - name: self.name, - }, - uri: `${STORAGE_UPLOAD_BASE_URL}/${self.bucket.name}/o`, - }; - - if (is.defined(this.generation)) { - reqOpts.qs.ifGenerationMatch = this.generation; - } - - if (is.defined(this.kmsKeyName)) { - reqOpts.qs.kmsKeyName = this.kmsKeyName; - } - - if (options.userProject) { - reqOpts.qs.userProject = options.userProject; - } - - if (options.predefinedAcl) { - reqOpts.qs.predefinedAcl = options.predefinedAcl; - } else if (options.private) { - reqOpts.qs.predefinedAcl = 'private'; - } else if (options.public) { - reqOpts.qs.predefinedAcl = 'publicRead'; - } - - common.util.makeWritableStream(dup, { - makeAuthenticatedRequest: function(reqOpts) { - self.request(reqOpts, function(err, body, resp) { - if (err) { - dup.destroy(err); - return; - } - - self.metadata = body; - dup.emit('response', resp); - dup.emit('complete'); - }); - }, - metadata: options.metadata, - request: reqOpts, - }); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(File, { - exclude: ['setEncryptionKey'], -}); - -/** - * Reference to the {@link File} class. - * @name module:@google-cloud/storage.File - * @see File - */ -module.exports = File; diff --git a/functions/node_modules/@google-cloud/storage/src/iam.js b/functions/node_modules/@google-cloud/storage/src/iam.js deleted file mode 100644 index 90b9bc08..00000000 --- a/functions/node_modules/@google-cloud/storage/src/iam.js +++ /dev/null @@ -1,300 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const arrify = require('arrify'); -const common = require('@google-cloud/common'); -const extend = require('extend'); -const is = require('is'); - -/** - * Get and set IAM policies for your Cloud Storage bucket. - * - * @see [Cloud Storage IAM Management](https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management) - * @see [Granting, Changing, and Revoking Access](https://cloud.google.com/iam/docs/granting-changing-revoking-access) - * @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles) - * - * @constructor Iam - * @mixin - * - * @param {Bucket} bucket The parent instance. - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * // bucket.iam - */ -function Iam(bucket) { - this.request_ = bucket.request.bind(bucket); - this.resourceId_ = 'buckets/' + bucket.id; -} - -/** - * @typedef {object} GetPolicyRequest - * @property {string} userProject The ID of the project which will be billed for - * the request. - */ -/** - * @typedef {array} GetPolicyResponse - * @property {object} 0 The policy. - * @property {object} 1 The full API response. - */ -/** - * @callback GetPolicyCallback - * @param {?Error} err Request error, if any. - * @param {object} acl The policy. - * @param {object} apiResponse The full API response. - */ -/** - * Get the IAM policy. - * - * @param {GetPolicyRequest} [options] Request options. - * @param {GetPolicyCallback} [callback] Callback function. - * @returns {Promise} - * - * @see [Buckets: setIamPolicy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * bucket.iam.getPolicy(function(err, policy, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.iam.getPolicy().then(function(data) { - * const policy = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/iam.js - * region_tag:storage_view_bucket_iam_members - * Example of retrieving a bucket's IAM policy: - */ -Iam.prototype.getPolicy = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request_( - { - uri: '/iam', - qs: options, - }, - callback - ); -}; - -/** - * @typedef {array} SetPolicyResponse - * @property {object} 0 The policy. - * @property {object} 1 The full API response. - */ -/** - * @callback SetPolicyCallback - * @param {?Error} err Request error, if any. - * @param {object} acl The policy. - * @param {object} apiResponse The full API response. - */ -/** - * Set the IAM policy. - * - * @throws {Error} If no policy is provided. - * - * @param {object} policy The policy. - * @param {array} policy.bindings Bindings associate members with roles. - * @param {string} [policy.etag] Etags are used to perform a read-modify-write. - * @param {object} [options] Configuration opbject. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {SetPolicyCallback} callback Callback function. - * @returns {Promise} - * - * @see [Buckets: setIamPolicy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy} - * @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles) - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * - * const myPolicy = { - * bindings: [ - * { - * role: 'roles/storage.admin', - * members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] - * } - * ] - * }; - * - * bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.iam.setPolicy(myPolicy).then(function(data) { - * const policy = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/iam.js - * region_tag:storage_add_bucket_iam_member - * Example of adding to a bucket's IAM policy: - * - * @example include:samples/iam.js - * region_tag:storage_remove_bucket_iam_member - * Example of removing from a bucket's IAM policy: - */ -Iam.prototype.setPolicy = function(policy, options, callback) { - if (!is.object(policy)) { - throw new Error('A policy object is required.'); - } - - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request_( - { - method: 'PUT', - uri: '/iam', - json: extend( - { - resourceId: this.resourceId_, - }, - policy - ), - qs: options, - }, - callback - ); -}; - -/** - * @typedef {array} TestIamPermissionsResponse - * @property {object[]} 0 A subset of permissions that the caller is allowed. - * @property {object} 1 The full API response. - */ -/** - * @callback TestIamPermissionsCallback - * @param {?Error} err Request error, if any. - * @param {object[]} acl A subset of permissions that the caller is allowed. - * @param {object} apiResponse The full API response. - */ -/** - * Test a set of permissions for a resource. - * - * @throws {Error} If permissions are not provided. - * - * @param {string|string[]} permissions The permission(s) to test for. - * @param {object} [options] Configuration object. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {TestIamPermissionsCallback} [callback] Callback function. - * @returns {Promise} - * - * @see [Buckets: testIamPermissions API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const bucket = storage.bucket('my-bucket'); - * - * //- - * // Test a single permission. - * //- - * const test = 'storage.buckets.delete'; - * - * bucket.iam.testPermissions(test, function(err, permissions, apiResponse) { - * console.log(permissions); - * // { - * // "storage.buckets.delete": true - * // } - * }); - * - * //- - * // Test several permissions at once. - * //- - * const tests = [ - * 'storage.buckets.delete', - * 'storage.buckets.get' - * ]; - * - * bucket.iam.testPermissions(tests, function(err, permissions) { - * console.log(permissions); - * // { - * // "storage.buckets.delete": false, - * // "storage.buckets.get": true - * // } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * bucket.iam.testPermissions(test).then(function(data) { - * const permissions = data[0]; - * const apiResponse = data[1]; - * }); - */ -Iam.prototype.testPermissions = function(permissions, options, callback) { - if (!is.array(permissions) && !is.string(permissions)) { - throw new Error('Permissions are required.'); - } - - if (is.fn(options)) { - callback = options; - options = {}; - } - - options = extend( - { - permissions: arrify(permissions), - }, - options - ); - - this.request_( - { - uri: '/iam/testPermissions', - qs: options, - useQuerystring: true, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - const availablePermissions = arrify(resp.permissions); - - const permissionsHash = permissions.reduce(function(acc, permission) { - acc[permission] = availablePermissions.indexOf(permission) > -1; - return acc; - }, {}); - - callback(null, permissionsHash, resp); - } - ); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Iam); - -module.exports = Iam; diff --git a/functions/node_modules/@google-cloud/storage/src/index.js b/functions/node_modules/@google-cloud/storage/src/index.js deleted file mode 100644 index 09953035..00000000 --- a/functions/node_modules/@google-cloud/storage/src/index.js +++ /dev/null @@ -1,591 +0,0 @@ -/** - * Copyright 2014-2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const arrify = require('arrify'); -const common = require('@google-cloud/common'); -const extend = require('extend'); -const util = require('util'); - -const Bucket = require('./bucket.js'); -const Channel = require('./channel.js'); -const File = require('./file.js'); - -/** - * @typedef {object} ClientConfig - * @property {string} [projectId] The project ID from the Google Developer's - * Console, e.g. 'grape-spaceship-123'. We will also check the environment - * variable `GCLOUD_PROJECT` for your project ID. If your app is running in - * an environment which supports {@link https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application Application Default Credentials}, - * your project ID will be detected automatically. - * @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key - * downloaded from the Google Developers Console. If you provide a path to a - * JSON file, the `projectId` option above is not necessary. NOTE: .pem and - * .p12 require you to specify the `email` option as well. - * @property {string} [email] Account email address. Required when using a .pem - * or .p12 keyFilename. - * @property {object} [credentials] Credentials object. - * @property {string} [credentials.client_email] - * @property {string} [credentials.private_key] - * @property {boolean} [autoRetry=true] Automatically retry requests if the - * response is related to rate limits or certain intermittent server errors. - * We will exponentially backoff subsequent requests by default. - * @property {number} [maxRetries=3] Maximum number of automatic retries - * attempted before returning the error. - * @property {Constructor} [promise] Custom promise module to use instead of - * native Promises. - */ - -/*! Developer Documentation - * - * Invoke this method to create a new Storage object bound with pre-determined - * configuration options. For each object that can be created (e.g., a bucket), - * there is an equivalent static and instance method. While they are classes, - * they can be instantiated without use of the `new` keyword. - */ -/** - *

ACLs

- * Cloud Storage uses access control lists (ACLs) to manage object and - * bucket access. ACLs are the mechanism you use to share files with other users - * and allow other users to access your buckets and files. - * - * To learn more about ACLs, read this overview on - * [Access Control](https://cloud.google.com/storage/docs/access-control). - * - * @see [Cloud Storage overview]{@link https://cloud.google.com/storage/docs/overview} - * @see [Access Control]{@link https://cloud.google.com/storage/docs/access-control} - * - * @class - * @hideconstructor - * - * @example Create a client that uses Application Default Credentials (ADC) - * const Storage = require('@google-cloud/storage'); - * const storage = new Storage(); - * - * @example Create a client with explicit credentials - * const Storage = require('@google-cloud/storage'); - * const storage = new Storage({ - * projectId: 'your-project-id', - * keyFilename: '/path/to/keyfile.json' - * }); - * - * @param {ClientConfig} [options] Configuration options. - */ -function Storage(options) { - if (!(this instanceof Storage)) { - return new Storage(options); - } - - options = common.util.normalizeArguments(this, options); - - const config = { - baseUrl: 'https://www.googleapis.com/storage/v1', - projectIdRequired: false, - scopes: [ - 'https://www.googleapis.com/auth/iam', - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/devstorage.full_control', - ], - packageJson: require('../package.json'), - }; - - common.Service.call(this, config, options); -} - -util.inherits(Storage, common.Service); - -/** - * Cloud Storage uses access control lists (ACLs) to manage object and - * bucket access. ACLs are the mechanism you use to share objects with other - * users and allow other users to access your buckets and objects. - * - * This object provides constants to refer to the three permission levels that - * can be granted to an entity: - * - * - `gcs.acl.OWNER_ROLE` - ("OWNER") - * - `gcs.acl.READER_ROLE` - ("READER") - * - `gcs.acl.WRITER_ROLE` - ("WRITER") - * - * @see [About Access Control Lists]{@link https://cloud.google.com/storage/docs/access-control/lists} - * - * @name Storage.acl - * @type {object} - * @property {string} OWNER_ROLE - * @property {string} READER_ROLE - * @property {string} WRITER_ROLE - * - * @example - * const storage = require('@google-cloud/storage')(); - * const albums = storage.bucket('albums'); - * - * //- - * // Make all of the files currently in a bucket publicly readable. - * //- - * const options = { - * entity: 'allUsers', - * role: storage.acl.READER_ROLE - * }; - * - * albums.acl.add(options, function(err, aclObject) {}); - * - * //- - * // Make any new objects added to a bucket publicly readable. - * //- - * albums.acl.default.add(options, function(err, aclObject) {}); - * - * //- - * // Grant a user ownership permissions to a bucket. - * //- - * albums.acl.add({ - * entity: 'user-useremail@example.com', - * role: storage.acl.OWNER_ROLE - * }, function(err, aclObject) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * albums.acl.add(options).then(function(data) { - * const aclObject = data[0]; - * const apiResponse = data[1]; - * }); - */ -Storage.acl = { - OWNER_ROLE: 'OWNER', - READER_ROLE: 'READER', - WRITER_ROLE: 'WRITER', -}; - -/** - * Reference to {@link Storage.acl}. - * - * @name Storage#acl - * @see Storage.acl - */ -Storage.prototype.acl = Storage.acl; - -/** - * Get a reference to a Cloud Storage bucket. - * - * @param {string} name Name of the bucket. - * @param {object} [options] Configuration object. - * @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to - * encrypt objects inserted into this bucket, if no encryption method is - * specified. - * @param {string} [options.userProject] User project to be billed for all - * requests made from this Bucket object. - * @returns {Bucket} - * @see Bucket - * - * @example - * const storage = require('@google-cloud/storage')(); - * const albums = storage.bucket('albums'); - * const photos = storage.bucket('photos'); - */ -Storage.prototype.bucket = function(name, options) { - if (!name) { - throw new Error('A bucket name is needed to use Cloud Storage.'); - } - - return new Bucket(this, name, options); -}; - -/** - * Reference a channel to receive notifications about changes to your bucket. - * - * @param {string} id The ID of the channel. - * @param {string} resourceId The resource ID of the channel. - * @returns {Channel} - * @see Channel - * - * @example - * const storage = require('@google-cloud/storage')(); - * const channel = storage.channel('id', 'resource-id'); - */ -Storage.prototype.channel = function(id, resourceId) { - return new Channel(this, id, resourceId); -}; - -/** - * Metadata to set for the bucket. - * - * @typedef {object} CreateBucketRequest - * @property {boolean} [coldline=false] Specify the storage class as Coldline. - * @property {boolean} [dra=false] Specify the storage class as Durable Reduced - * Availability. - * @property {boolean} [multiRegional=false] Specify the storage class as - * Multi-Regional. - * @property {boolean} [nearline=false] Specify the storage class as Nearline. - * @property {boolean} [regional=false] Specify the storage class as Regional. - * @property {boolean} [requesterPays=false] **Early Access Testers Only** - * Force the use of the User Project metadata field to assign operational - * costs when an operation is made on a Bucket and its objects. - * @property {string} [userProject] The ID of the project which will be billed - * for the request. - */ -/** - * @typedef {array} CreateBucketResponse - * @property {Bucket} 0 The new {@link Bucket}. - * @property {object} 1 The full API response. - */ -/** - * @callback CreateBucketCallback - * @param {?Error} err Request error, if any. - * @param {Bucket} bucket The new {@link Bucket}. - * @param {object} apiResponse The full API response. - */ -/** - * Create a bucket. - * - * Cloud Storage uses a flat namespace, so you can't create a bucket with - * a name that is already in use. For more information, see - * [Bucket Naming Guidelines](https://cloud.google.com/storage/docs/bucketnaming.html#requirements). - * - * @see [Buckets: insert API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/insert} - * @see [Storage Classes]{@link https://cloud.google.com/storage/docs/storage-classes} - * - * @param {string} name Name of the bucket to create. - * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. - * @param {CreateBucketCallback} [callback] Callback function. - * @returns {Promise} - * @throws {Error} If a name is not provided. - * @see Bucket#create - * - * @example - * const storage = require('@google-cloud/storage')(); - * const callback = function(err, bucket, apiResponse) { - * // `bucket` is a Bucket object. - * }; - * - * storage.createBucket('new-bucket', callback); - * - * //- - * // Create a bucket in a specific location and region. See the - * // Official JSON API docs for complete details on the `location` option. - * // - * //- - * const metadata = { - * location: 'US-CENTRAL1', - * regional: true - * }; - * - * storage.createBucket('new-bucket', metadata, callback); - * - * //- - * // Enable versioning on a new bucket. - * //- - * const metadata = { - * versioning: { - * enabled: true - * } - * }; - * - * storage.createBucket('new-bucket', metadata, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * storage.createBucket('new-bucket').then(function(data) { - * const bucket = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/buckets.js - * region_tag:storage_create_bucket - * Another example: - */ -Storage.prototype.createBucket = function(name, metadata, callback) { - const self = this; - - if (!name) { - throw new Error('A name is required to create a bucket.'); - } - - if (!callback) { - callback = metadata; - metadata = {}; - } - - const body = extend({}, metadata, { - name: name, - }); - - const storageClasses = { - coldline: 'COLDLINE', - dra: 'DURABLE_REDUCED_AVAILABILITY', - multiRegional: 'MULTI_REGIONAL', - nearline: 'NEARLINE', - regional: 'REGIONAL', - }; - - Object.keys(storageClasses).forEach(function(storageClass) { - if (body[storageClass]) { - body.storageClass = storageClasses[storageClass]; - delete body[storageClass]; - } - }); - - if (body.requesterPays) { - body.billing = { - requesterPays: body.requesterPays, - }; - delete body.requesterPays; - } - - const query = { - project: this.projectId, - }; - - if (body.userProject) { - query.userProject = body.userProject; - delete body.userProject; - } - - this.request( - { - method: 'POST', - uri: '/b', - qs: query, - json: body, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - const bucket = self.bucket(name); - bucket.metadata = resp; - - callback(null, bucket, resp); - } - ); -}; - -/** - * Query object for listing buckets. - * - * @typedef {object} GetBucketsRequest - * @property {boolean} [autoPaginate=true] Have pagination handled - * automatically. - * @property {number} [maxApiCalls] Maximum number of API calls to make. - * @property {number} [maxResults] Maximum number of items plus prefixes to - * return. - * @property {string} [pageToken] A previously-returned page token - * representing part of the larger set of results to view. - * @property {string} [userProject] The ID of the project which will be billed - * for the request. - */ -/** - * @typedef {array} GetBucketsResponse - * @property {Bucket[]} 0 Array of {@link Bucket} instances. - */ -/** - * @callback GetBucketsCallback - * @param {?Error} err Request error, if any. - * @param {Bucket[]} buckets Array of {@link Bucket} instances. - */ -/** - * Get Bucket objects for all of the buckets in your project. - * - * @see [Buckets: list API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/list} - * - * @param {GetBucketsRequest} [query] Query object for listing buckets. - * @param {GetBucketsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * storage.getBuckets(function(err, buckets) { - * if (!err) { - * // buckets is an array of Bucket objects. - * } - * }); - * - * //- - * // To control how many API requests are made and page through the results - * // manually, set `autoPaginate` to `false`. - * //- - * const callback = function(err, buckets, nextQuery, apiResponse) { - * if (nextQuery) { - * // More results exist. - * storage.getBuckets(nextQuery, callback); - * } - * - * // The `metadata` property is populated for you with the metadata at the - * // time of fetching. - * buckets[0].metadata; - * - * // However, in cases where you are concerned the metadata could have - * // changed, use the `getMetadata` method. - * buckets[0].getMetadata(function(err, metadata, apiResponse) {}); - * }; - * - * storage.getBuckets({ - * autoPaginate: false - * }, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * storage.getBuckets().then(function(data) { - * const buckets = data[0]; - * }); - * - * @example include:samples/buckets.js - * region_tag:storage_list_buckets - * Another example: - */ -Storage.prototype.getBuckets = function(query, callback) { - const self = this; - - if (!callback) { - callback = query; - query = {}; - } - - query.project = query.project || this.projectId; - - this.request( - { - uri: '/b', - qs: query, - }, - function(err, resp) { - if (err) { - callback(err, null, null, resp); - return; - } - - const buckets = arrify(resp.items).map(function(bucket) { - const bucketInstance = self.bucket(bucket.id); - bucketInstance.metadata = bucket; - return bucketInstance; - }); - - let nextQuery = null; - if (resp.nextPageToken) { - nextQuery = extend({}, query, {pageToken: resp.nextPageToken}); - } - - callback(null, buckets, nextQuery, resp); - } - ); -}; - -/** - * Get {@link Bucket} objects for all of the buckets in your project as - * a readable object stream. - * - * @method Storage#getBucketsStream - * @param {GetBucketsRequest} [query] Query object for listing buckets. - * @returns {ReadableStream} A readable stream that emits {@link Bucket} instances. - * - * @example - * storage.getBucketsStream() - * .on('error', console.error) - * .on('data', function(bucket) { - * // bucket is a Bucket object. - * }) - * .on('end', function() { - * // All buckets retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * storage.getBucketsStream() - * .on('data', function(bucket) { - * this.end(); - * }); - */ -Storage.prototype.getBucketsStream = common.paginator.streamify('getBuckets'); - -/*! Developer Documentation - * - * These methods can be auto-paginated. - */ -common.paginator.extend(Storage, 'getBuckets'); - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Storage, { - exclude: ['bucket', 'channel'], -}); - -/** - * {@link Bucket} class. - * - * @name Storage.Bucket - * @see Bucket - * @type {Constructor} - */ -Storage.Bucket = Bucket; - -/** - * {@link Channel} class. - * - * @name Storage.Channel - * @see Channel - * @type {Constructor} - */ -Storage.Channel = Channel; - -/** - * {@link File} class. - * - * @name Storage.File - * @see File - * @type {Constructor} - */ -Storage.File = File; - -/** - * The default export of the `@google-cloud/storage` package is the - * {@link Storage} class, which also serves as a factory function which produces - * {@link Storage} instances. - * - * See {@link Storage} and {@link ClientConfig} for client methods and - * configuration options. - * - * @module {Storage} @google-cloud/storage - * @alias nodejs-storage - * - * @example Install the client library with npm: - * npm install --save @google-cloud/storage - * - * @example Import the client library - * const Storage = require('@google-cloud/storage'); - * - * @example Create a client that uses Application Default Credentials (ADC): - * const storage = new Storage(); - * - * @example Create a client with explicit credentials: - * const storage = new Storage({ - * projectId: 'your-project-id', - * keyFilename: '/path/to/keyfile.json' - * }); - * - * @example include:samples/quickstart.js - * region_tag:storage_quickstart - * Full quickstart example: - */ -module.exports = Storage; diff --git a/functions/node_modules/@google-cloud/storage/src/notification.js b/functions/node_modules/@google-cloud/storage/src/notification.js deleted file mode 100644 index ed30cf56..00000000 --- a/functions/node_modules/@google-cloud/storage/src/notification.js +++ /dev/null @@ -1,350 +0,0 @@ -/*! - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -const common = require('@google-cloud/common'); -const is = require('is'); -const util = require('util'); - -/** - * A Notification object is created from your {@link Bucket} object using - * {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub - * notifications. - * - * @see [Cloud Pub/Sub Notifications for Google Cloud Storage]{@link https://cloud.google.com/storage/docs/pubsub-notifications} - * - * @class - * @hideconstructor - * - * @param {Bucket} bucket The bucket instance this notification is attached to. - * @param {string} id The ID of the notification. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * - * const notification = myBucket.notification('1'); - */ -function Notification(bucket, id) { - const methods = { - /** - * Creates a notification subscription for the bucket. - * - * @see [Notifications: insert]{@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert} - * - * @param {Topic|string} topic The Cloud PubSub topic to which this - * subscription publishes. If the project ID is omitted, the current - * project ID will be used. - * - * Acceptable formats are: - * - `projects/grape-spaceship-123/topics/my-topic` - * - * - `my-topic` - * @param {CreateNotificationRequest} [options] Metadata to set for - * the notification. - * @param {CreateNotificationCallback} [callback] Callback function. - * @returns {Promise} - * @throws {Error} If a valid topic is not provided. - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const notification = myBucket.notification('1'); - * - * notification.create(function(err, notification, apiResponse) { - * if (!err) { - * // The notification was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * notification.create().then(function(data) { - * const notification = data[0]; - * const apiResponse = data[1]; - * }); - */ - create: true, - - /** - * @typedef {array} NotificationExistsResponse - * @property {boolean} 0 Whether the notification exists or not. - */ - /** - * @callback NotificationExistsCallback - * @param {?Error} err Request error, if any. - * @param {boolean} exists Whether the notification exists or not. - */ - /** - * Check if the notification exists. - * - * @param {NotificationExistsCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const notification = myBucket.notification('1'); - * - * notification.exists(function(err, exists) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * notification.exists().then(function(data) { - * const exists = data[0]; - * }); - */ - exists: true, - }; - - common.ServiceObject.call(this, { - parent: bucket, - baseUrl: '/notificationConfigs', - id: id.toString(), - createMethod: bucket.createNotification.bind(bucket), - methods: methods, - }); -} - -util.inherits(Notification, common.ServiceObject); - -/** - * @typedef {array} DeleteNotificationResponse - * @property {object} 0 The full API response. - */ -/** - * @callback DeleteNotificationCallback - * @param {?Error} err Request error, if any. - * @param {object} apiResponse The full API response. - */ -/** - * Permanently deletes a notification subscription. - * - * @see [Notifications: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/notifications/delete} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {DeleteNotificationCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const notification = myBucket.notification('1'); - * - * notification.delete(function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * notification.delete().then(function(data) { - * const apiResponse = data[0]; - * }); - * - * @example include:samples/notifications.js - * region_tag:storage_delete_notification - * Another example: - */ -Notification.prototype.delete = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request( - { - method: 'DELETE', - uri: '', - qs: options, - }, - callback || common.util.noop - ); -}; - -/** - * @typedef {array} GetNotificationResponse - * @property {Notification} 0 The {@link Notification} - * @property {object} 1 The full API response. - */ -/** - * @callback GetNotificationCallback - * @param {?Error} err Request error, if any. - * @param {Notification} notification The {@link Notification}. - * @param {object} apiResponse The full API response. - */ -/** - * Get a notification and its metadata if it exists. - * - * @see [Notifications: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get} - * - * @param {object} [options] Configuration options. - * See {@link Bucket#createNotification} for create options. - * @param {boolean} [options.autoCreate] Automatically create the object if - * it does not exist. Default: `false`. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetNotificationCallback} [callback] Callback function. - * @return {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const notification = myBucket.notification('1'); - * - * notification.get(function(err, notification, apiResponse) { - * // `notification.metadata` has been populated. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * notification.get().then(function(data) { - * const notification = data[0]; - * const apiResponse = data[1]; - * }); - */ -Notification.prototype.get = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - const autoCreate = options.autoCreate; - delete options.autoCreate; - - function onCreate(err, notification, apiResponse) { - if (err) { - if (err.code === 409) { - self.get(options, callback); - return; - } - - callback(err, null, apiResponse); - return; - } - - callback(null, notification, apiResponse); - } - - this.getMetadata(options, function(err, metadata) { - if (err) { - if (err.code === 404 && autoCreate) { - const args = []; - - if (!is.empty(options)) { - args.push(options); - } - - args.push(onCreate); - - self.create.apply(self, args); - return; - } - - callback(err, null, metadata); - return; - } - - callback(null, self, metadata); - }); -}; - -/** - * @typedef {array} GetNotificationMetadataResponse - * @property {object} 0 The notification metadata. - * @property {object} 1 The full API response. - */ -/** - * @callback GetNotificationMetadataCallback - * @param {?Error} err Request error, if any. - * @param {object} files The notification metadata. - * @param {object} apiResponse The full API response. - */ -/** - * Get the notification's metadata. - * - * @see [Notifications: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get} - * - * @param {object} [options] Configuration options. - * @param {string} [options.userProject] The ID of the project which will be - * billed for the request. - * @param {GetNotificationMetadataCallback} [callback] Callback function. - * @returns {Promise} - * - * @example - * const storage = require('@google-cloud/storage')(); - * const myBucket = storage.bucket('my-bucket'); - * const notification = myBucket.notification('1'); - * - * notification.getMetadata(function(err, metadata, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * notification.getMetadata().then(function(data) { - * const metadata = data[0]; - * const apiResponse = data[1]; - * }); - * - * @example include:samples/notifications.js - * region_tag:storage_notifications_get_metadata - * Another example: - */ -Notification.prototype.getMetadata = function(options, callback) { - const self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - this.request( - { - uri: '', - qs: options, - }, - function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - self.metadata = resp; - - callback(null, self.metadata, resp); - } - ); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Notification); - -/** - * Reference to the {@link Notification} class. - * @name module:@google-cloud/storage.Notification - * @see Notification - */ -module.exports = Notification; diff --git a/functions/node_modules/@grpc/proto-loader/README.md b/functions/node_modules/@grpc/proto-loader/README.md deleted file mode 100644 index 651da848..00000000 --- a/functions/node_modules/@grpc/proto-loader/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# gRPC Protobuf Loader - -A utility package for loading `.proto` files for use with gRPC, using the latest Protobuf.js package. - -## Installation - -```sh -npm install @grpc/proto-loader -``` - -## Usage - -```js -const protoLoader = require('@grpc/proto-loader'); -const grpcLibrary = require('grpc'); -// OR -const grpcLibrary = require('@grpc/grpc-js'); - -protoLoader.load(protoFileName, options).then(packageDefinition => { - const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); -}); -// OR -const packageDefinition = protoLoader.loadSync(protoFileName, options); -const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); -``` - -The options parameter is an object that can have the following optional properties: - -| Field name | Valid values | Description -|------------|--------------|------------ -| `keepCase` | `true` or `false` | Preserve field names. The default is to change them to camel case. -| `longs` | `String` or `Number` | The type to use to represent `long` values. Defaults to a `Long` object type. -| `enums` | `String` | The type to use to represent `enum` values. Defaults to the numeric value. -| `bytes` | `Array` or `String` | The type to use to represent `bytes` values. Defaults to `Buffer`. -| `defaults` | `true` or `false` | Set default values on output objects. Defaults to `false`. -| `arrays` | `true` or `false` | Set empty arrays for missing array values even if `defaults` is `false` Defaults to `false`. -| `objects` | `true` or `false` | Set empty objects for missing object values even if `defaults` is `false` Defaults to `false`. -| `oneofs` | `true` or `false` | Set virtual oneof properties to the present field's name. Defaults to `false`. -| `includeDirs` | An array of strings | A list of search paths for imported `.proto` files. - -The following options object closely approximates the existing behavior of `grpc.load`: - -```js -const options = { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true -} -``` diff --git a/functions/node_modules/@grpc/proto-loader/build/src/index.d.ts b/functions/node_modules/@grpc/proto-loader/build/src/index.d.ts deleted file mode 100644 index ecc45ca4..00000000 --- a/functions/node_modules/@grpc/proto-loader/build/src/index.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// -/** - * @license - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -import * as Protobuf from 'protobufjs'; -export interface Serialize { - (value: T): Buffer; -} -export interface Deserialize { - (bytes: Buffer): T; -} -export interface MethodDefinition { - path: string; - requestStream: boolean; - responseStream: boolean; - requestSerialize: Serialize; - responseSerialize: Serialize; - requestDeserialize: Deserialize; - responseDeserialize: Deserialize; - originalName?: string; -} -export interface ServiceDefinition { - [index: string]: MethodDefinition; -} -export interface PackageDefinition { - [index: string]: ServiceDefinition; -} -export declare type Options = Protobuf.IParseOptions & Protobuf.IConversionOptions & { - includeDirs?: string[]; -}; -/** - * Load a .proto file with the specified options. - * @param filename The file path to load. Can be an absolute path or relative to - * an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -export declare function load(filename: string, options?: Options): Promise; -export declare function loadSync(filename: string, options?: Options): PackageDefinition; diff --git a/functions/node_modules/@grpc/proto-loader/build/src/index.js b/functions/node_modules/@grpc/proto-loader/build/src/index.js deleted file mode 100644 index 2607116d..00000000 --- a/functions/node_modules/@grpc/proto-loader/build/src/index.js +++ /dev/null @@ -1,157 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * @license - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -var Protobuf = require("protobufjs"); -var fs = require("fs"); -var path = require("path"); -var _ = require("lodash"); -function joinName(baseName, name) { - if (baseName === '') { - return name; - } - else { - return baseName + '.' + name; - } -} -function getAllServices(obj, parentName) { - var objName = joinName(parentName, obj.name); - if (obj.hasOwnProperty('methods')) { - return [[objName, obj]]; - } - else { - return obj.nestedArray.map(function (child) { - if (child.hasOwnProperty('nested')) { - return getAllServices(child, objName); - } - else { - return []; - } - }).reduce(function (accumulator, currentValue) { return accumulator.concat(currentValue); }, []); - } -} -function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; -} -function createSerializer(cls) { - return function serialize(arg) { - var message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -} -function createMethodDefinition(method, serviceName, options) { - return { - path: '/' + serviceName + '/' + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(method.resolvedRequestType), - requestDeserialize: createDeserializer(method.resolvedRequestType, options), - responseSerialize: createSerializer(method.resolvedResponseType), - responseDeserialize: createDeserializer(method.resolvedResponseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: _.camelCase(method.name) - }; -} -function createServiceDefinition(service, name, options) { - var def = {}; - for (var _i = 0, _a = service.methodsArray; _i < _a.length; _i++) { - var method = _a[_i]; - def[method.name] = createMethodDefinition(method, name, options); - } - return def; -} -function createPackageDefinition(root, options) { - var def = {}; - for (var _i = 0, _a = getAllServices(root, ''); _i < _a.length; _i++) { - var _b = _a[_i], name = _b[0], service = _b[1]; - def[name] = createServiceDefinition(service, name, options); - } - return def; -} -function addIncludePathResolver(root, includePaths) { - root.resolvePath = function (origin, target) { - for (var _i = 0, includePaths_1 = includePaths; _i < includePaths_1.length; _i++) { - var directory = includePaths_1[_i]; - var fullPath = path.join(directory, target); - try { - fs.accessSync(fullPath, fs.constants.R_OK); - return fullPath; - } - catch (err) { - continue; - } - } - return null; - }; -} -/** - * Load a .proto file with the specified options. - * @param filename The file path to load. Can be an absolute path or relative to - * an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -function load(filename, options) { - var root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!(options.includeDirs instanceof Array)) { - return Promise.reject(new Error('The includeDirs option must be an array')); - } - addIncludePathResolver(root, options.includeDirs); - } - return root.load(filename, options).then(function (loadedRoot) { - loadedRoot.resolveAll(); - return createPackageDefinition(root, options); - }); -} -exports.load = load; -function loadSync(filename, options) { - var root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!(options.includeDirs instanceof Array)) { - throw new Error('The include option must be an array'); - } - addIncludePathResolver(root, options.includeDirs); - } - var loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return createPackageDefinition(root, options); -} -exports.loadSync = loadSync; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/LICENSE b/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/LICENSE deleted file mode 100644 index 21071075..00000000 --- a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ - MIT License - - Copyright (c) Microsoft Corporation. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE diff --git a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/README.md b/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/README.md deleted file mode 100644 index 1f8df83a..00000000 --- a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Installation -> `npm install --save @types/node` - -# Summary -This package contains type definitions for Node.js (http://nodejs.org/). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v9 - -Additional Details - * Last updated: Tue, 18 Dec 2018 21:38:45 GMT - * Dependencies: none - * Global values: Buffer, NodeJS, SlowBuffer, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, require, setImmediate, setInterval, setTimeout - -# Credits -These definitions were written by Microsoft TypeScript , DefinitelyTyped , Parambir Singh , Christian Vaagland Tellnes , Wilco Bakker , Nicolas Voigt , Chigozirim C. , Flarna , Mariusz Wiktorczyk , wwwy3y3 , Deividas Bakanas , Kelvin Jin , Alvis HT Tang , Sebastian Silbermann , Hannes Magnusson , Alberto Schiabel , Klaus Meinhardt , Huw , Nicolas Even , Bruno Scheufler , Mohsen Azimi , Hoàng Văn Khải , Alexander T. , Lishude , Andrew Makarov , Eugene Y. Q. Shen . diff --git a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/index.d.ts b/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/index.d.ts deleted file mode 100644 index 5bafe1ec..00000000 --- a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/index.d.ts +++ /dev/null @@ -1,7802 +0,0 @@ -// Type definitions for Node.js 9.6 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Parambir Singh -// Christian Vaagland Tellnes -// Wilco Bakker -// Nicolas Voigt -// Chigozirim C. -// Flarna -// Mariusz Wiktorczyk -// wwwy3y3 -// Deividas Bakanas -// Kelvin Jin -// Alvis HT Tang -// Sebastian Silbermann -// Hannes Magnusson -// Alberto Schiabel -// Klaus Meinhardt -// Huw -// Nicolas Even -// Bruno Scheufler -// Mohsen Azimi -// Hoàng Văn Khải -// Alexander T. -// Lishude -// Andrew Makarov -// Eugene Y. Q. Shen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/** inspector module types */ -/// - -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: NodeJS.InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * The console.markTimeline() method is the deprecated form of console.timeStamp(). - * - * @deprecated Use console.timeStamp() instead. - */ - markTimeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: string[]): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timeline() method is the deprecated form of console.time(). - * - * @deprecated Use console.time() instead. - */ - timeline(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * The console.timelineEnd() method is the deprecated form of console.timeEnd(). - * - * @deprecated Use console.timeEnd() instead. - */ - timelineEnd(label?: string): void; -} - -interface Error { - stack?: string; -} - -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -// compat for TypeScript 1.8 -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } - -// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IteratorResult { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; -} - -/************************************************ -* * -* GLOBAL * -* * -************************************************/ -declare var process: NodeJS.Process; -declare var global: NodeJS.Global; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare namespace setTimeout { - export function __promisify__(ms: number): Promise; - export function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timer): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearInterval(intervalId: NodeJS.Timer): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; -declare namespace setImmediate { - export function __promisify__(): Promise; - export function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: any): void; - -// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -interface NodeRequireFunction { - /* tslint:disable-next-line:callable-types */ - (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve: RequireResolve; - cache: any; - extensions: NodeExtensions; - main: NodeModule | undefined; -} - -interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; -} - -interface NodeExtensions { - '.js': (m: NodeModule, filename: string) => any; - '.json': (m: NodeModule, filename: string) => any; - '.node': (m: NodeModule, filename: string) => any; - [ext: string]: (m: NodeModule, filename: string) => any; -} - -declare var require: NodeRequire; - -interface NodeModule { - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: NodeModule | null; - children: NodeModule[]; - paths: string[]; -} - -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; -declare var SlowBuffer: { - new(str: string, encoding?: string): Buffer; - new(size: number): Buffer; - new(size: Uint8Array): Buffer; - new(array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends Uint8Array { - constructor: typeof Buffer; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Uint8Array): boolean; - compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ -declare var Buffer: { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - new(str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - new(size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new(array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - new(arrayBuffer: ArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new(array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - new(buffer: Buffer): Buffer; - prototype: Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - from(data: any[] | string | Buffer | ArrayBuffer /*| TypedArray*/): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - */ - from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. (TypedArray is also allowed, but it is only available starting ES2017) - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - byteLength(string: string | Buffer | DataView | ArrayBuffer, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - concat(list: Uint8Array[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Uint8Array, buf2: Uint8Array): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafeSlow(size: number): Buffer; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - poolSize: number; -}; - -/************************************************ -* * -* GLOBAL INTERFACES * -* * -************************************************/ -declare namespace NodeJS { - export interface InspectOptions { - showHidden?: boolean; - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - breakLength?: number; - } - - export interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream): Console; - } - - export interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - export class EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - listenerCount(type: string | symbol): number; - // Added in Node 6... - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): this; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): this; - } - - export interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(cb?: Function): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface ReadWriteStream extends ReadableStream, WritableStream { } - - export interface Events extends EventEmitter { } - - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - } - - export interface CpuUsage { - user: number; - system: number; - } - - export interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: any, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - - export interface Socket extends ReadWriteStream { - isTTY?: true; - } - - export interface ProcessEnv { - [key: string]: string | undefined; - } - - export interface WriteStream extends Socket { - readonly writableHighWaterMark: number; - readonly writableLength: number; - columns?: number; - rows?: number; - _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error | undefined, callback: Function): void; - _final(callback: Function): void; - setDefaultEncoding(encoding: string): this; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - } - export interface ReadStream extends Socket { - readonly readableHighWaterMark: number; - readonly readableLength: number; - isRaw?: boolean; - setRawMode?(mode: boolean): void; - _read(size: number): void; - _destroy(err: Error | undefined, callback: Function): void; - push(chunk: any, encoding?: string): boolean; - destroy(error?: Error): void; - } - - export interface Process extends EventEmitter { - stdout: WriteStream; - stderr: WriteStream; - stdin: ReadStream; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: Array): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - version: string; - versions: ProcessVersions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): void; - pid: number; - ppid: number; - title: string; - arch: string; - platform: Platform; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?: [number, number]): [number, number]; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - - /** - * EventEmitter - * 1. beforeExit - * 2. disconnect - * 3. exit - * 4. message - * 5. rejectionHandled - * 6. uncaughtException - * 7. unhandledRejection - * 8. warning - * 9. message - * 10. - * 11. newListener/removeListener inherited from EventEmitter - */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - } - - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - export interface Timer { - ref(): void; - unref(): void; - } - - class Module { - static runMain(): void; - static wrap(code: string): string; - static builtinModules: string[]; - - static Module: typeof Module; - - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: Module | null; - children: Module[]; - paths: string[]; - - constructor(id: string, parent?: Module); - } -} - -interface IterableIterator { } - -/************************************************ -* * -* MODULES * -* * -************************************************/ -declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; -} - -declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } - - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } - - interface ParsedUrlQuery { [key: string]: string | string[] | undefined; } - - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; -} - -declare module "events" { - class internal extends NodeJS.EventEmitter { } - - namespace internal { - export class EventEmitter extends internal { - static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated - static defaultMaxListeners: number; - - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - eventNames(): Array; - listenerCount(type: string | symbol): number; - } - } - - export = internal; -} - -declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; - import { URL } from "url"; - - // incoming headers will never contain number - export interface IncomingHttpHeaders { - 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; - 'accept-patch'?: string; - 'accept-ranges'?: string; - 'authorization'?: string; - 'age'?: string; - 'allow'?: string; - 'alt-svc'?: string; - 'cache-control'?: string; - 'connection'?: string; - 'content-disposition'?: string; - 'content-encoding'?: string; - 'content-language'?: string; - 'content-length'?: string; - 'content-location'?: string; - 'content-range'?: string; - 'content-type'?: string; - 'date'?: string; - 'expires'?: string; - 'host'?: string; - 'last-modified'?: string; - 'location'?: string; - 'pragma'?: string; - 'proxy-authenticate'?: string; - 'public-key-pins'?: string; - 'retry-after'?: string; - 'set-cookie'?: string[]; - 'strict-transport-security'?: string; - 'trailer'?: string; - 'transfer-encoding'?: string; - 'tk'?: string; - 'upgrade'?: string; - 'user-agent'?: string; - 'vary'?: string; - 'via'?: string; - 'warning'?: string; - 'www-authenticate'?: string; - [header: string]: string | string[] | undefined; - } - - // outgoing headers allows numbers (as they are converted internally to strings) - export interface OutgoingHttpHeaders { - [header: string]: number | string | string[] | undefined; - } - - export interface ClientRequestArgs { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number | string; - defaultPort?: number | string; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: OutgoingHttpHeaders; - auth?: string; - agent?: Agent | boolean; - _defaultAgent?: Agent; - timeout?: number; - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 - createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; - } - - export class Server extends net.Server { - constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); - - setTimeout(msecs?: number, callback?: () => void): this; - setTimeout(callback: () => void): this; - maxHeadersCount: number; - timeout: number; - keepAliveTimeout: number; - } - /** - * @deprecated Use IncomingMessage - */ - export class ServerRequest extends IncomingMessage { - connection: net.Socket; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js - export class OutgoingMessage extends stream.Writable { - upgrading: boolean; - chunkedEncoding: boolean; - shouldKeepAlive: boolean; - useChunkedEncodingByDefault: boolean; - sendDate: boolean; - finished: boolean; - headersSent: boolean; - connection: net.Socket; - - constructor(); - - setTimeout(msecs: number, callback?: () => void): this; - destroy(error: Error): void; - setHeader(name: string, value: number | string | string[]): void; - getHeader(name: string): number | string | string[] | undefined; - getHeaders(): OutgoingHttpHeaders; - getHeaderNames(): string[]; - hasHeader(name: string): boolean; - removeHeader(name: string): void; - addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; - flushHeaders(): void; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 - export class ServerResponse extends OutgoingMessage { - statusCode: number; - statusMessage: string; - - constructor(req: IncomingMessage); - - assignSocket(socket: net.Socket): void; - detachSocket(socket: net.Socket): void; - // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 - // no args in writeContinue callback - writeContinue(callback?: () => void): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 - export class ClientRequest extends OutgoingMessage { - connection: net.Socket; - socket: net.Socket; - aborted: number; - - constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); - - abort(): void; - onSocket(socket: net.Socket): void; - setTimeout(timeout: number, callback?: () => void): this; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - } - - export class IncomingMessage extends stream.Readable { - constructor(socket: net.Socket); - - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - connection: net.Socket; - headers: IncomingHttpHeaders; - rawHeaders: string[]; - trailers: { [key: string]: string | undefined }; - rawTrailers: string[]; - setTimeout(msecs: number, callback: () => void): this; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - destroy(error?: Error): void; - } - - /** - * @deprecated Use IncomingMessage - */ - export class ClientResponse extends IncomingMessage { } - - export interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } - - export class Agent { - maxFreeSockets: number; - maxSockets: number; - sockets: any; - requests: any; - - constructor(opts?: AgentOptions); - - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } - - export var METHODS: string[]; - - export var STATUS_CODES: { - [errorCode: number]: string | undefined; - [errorCode: string]: string | undefined; - }; - - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; - export function createClient(port?: number, host?: string): any; - - // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, - // create interface RequestOptions would make the naming more clear to developers - export interface RequestOptions extends ClientRequestArgs { } - export function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; -} - -declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - import * as net from "net"; - - // interfaces - export interface ClusterSettings { - execArgv?: string[]; // default: process.execArgv - exec?: string; - args?: string[]; - silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - inspectPort?: number | (() => number); - } - - export interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" - } - - export class Worker extends events.EventEmitter { - id: number; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - exitedAfterDisconnect: boolean; - - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "listening", listener: (address: Address) => void): this; - addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "listening", address: Address): boolean; - emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "listening", listener: (address: Address) => void): this; - on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "listening", listener: (address: Address) => void): this; - once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "listening", listener: (address: Address) => void): this; - prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "listening", listener: (address: Address) => void): this; - prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: () => void): this; - } - - export interface Cluster extends events.EventEmitter { - Worker: Worker; - disconnect(callback?: Function): void; - fork(env?: any): Worker; - isMaster: boolean; - isWorker: boolean; - // TODO: cluster.schedulingPolicy - settings: ClusterSettings; - setupMaster(settings?: ClusterSettings): void; - worker?: Worker; - workers?: { - [index: string]: Worker | undefined - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: any) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect", worker: Worker): boolean; - emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - emit(event: "fork", worker: Worker): boolean; - emit(event: "listening", worker: Worker, address: Address): boolean; - emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online", worker: Worker): boolean; - emit(event: "setup", settings: any): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", listener: (worker: Worker) => void): this; - on(event: "listening", listener: (worker: Worker, address: Address) => void): this; - on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: any) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", listener: (worker: Worker) => void): this; - once(event: "listening", listener: (worker: Worker, address: Address) => void): this; - once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: any) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", listener: (worker: Worker) => void): this; - prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: any) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: any) => void): this; - } - - export function disconnect(callback?: Function): void; - export function fork(env?: any): Worker; - export var isMaster: boolean; - export var isWorker: boolean; - // TODO: cluster.schedulingPolicy - export var settings: ClusterSettings; - export function setupMaster(settings?: ClusterSettings): void; - export var worker: Worker; - export var workers: { - [index: string]: Worker | undefined - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - export function addListener(event: string, listener: (...args: any[]) => void): Cluster; - export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function emit(event: string | symbol, ...args: any[]): boolean; - export function emit(event: "disconnect", worker: Worker): boolean; - export function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - export function emit(event: "fork", worker: Worker): boolean; - export function emit(event: "listening", worker: Worker, address: Address): boolean; - export function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - export function emit(event: "online", worker: Worker): boolean; - export function emit(event: "setup", settings: any): boolean; - - export function on(event: string, listener: (...args: any[]) => void): Cluster; - export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function on(event: "fork", listener: (worker: Worker) => void): Cluster; - export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function on(event: "online", listener: (worker: Worker) => void): Cluster; - export function on(event: "setup", listener: (settings: any) => void): Cluster; - - export function once(event: string, listener: (...args: any[]) => void): Cluster; - export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function once(event: "fork", listener: (worker: Worker) => void): Cluster; - export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function once(event: "online", listener: (worker: Worker) => void): Cluster; - export function once(event: "setup", listener: (settings: any) => void): Cluster; - - export function removeListener(event: string, listener: (...args: any[]) => void): Cluster; - export function removeAllListeners(event?: string): Cluster; - export function setMaxListeners(n: number): Cluster; - export function getMaxListeners(): number; - export function listeners(event: string): Function[]; - export function listenerCount(type: string): number; - - export function prependListener(event: string, listener: (...args: any[]) => void): Cluster; - export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; - export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function eventNames(): string[]; -} - -declare module "zlib" { - import * as stream from "stream"; - - export interface ZlibOptions { - flush?: number; // default: zlib.constants.Z_NO_FLUSH - finishFlush?: number; // default: zlib.constants.Z_FINISH - chunkSize?: number; // default: 16*1024 - windowBits?: number; - level?: number; // compression only - memLevel?: number; // compression only - strategy?: number; // compression only - dictionary?: any; // deflate/inflate only, empty dictionary by default - } - - export interface Zlib { - readonly bytesRead: number; - close(callback?: () => void): void; - flush(kind?: number | (() => void), callback?: () => void): void; - } - - export interface ZlibParams { - params(level: number, strategy: number, callback: () => void): void; - } - - export interface ZlibReset { - reset(): void; - } - - export interface Gzip extends stream.Transform, Zlib { } - export interface Gunzip extends stream.Transform, Zlib { } - export interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } - export interface Inflate extends stream.Transform, Zlib, ZlibReset { } - export interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } - export interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } - export interface Unzip extends stream.Transform, Zlib { } - - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; - - type InputType = string | Buffer | DataView | ArrayBuffer /* | TypedArray */; - export function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; - export function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - export function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; - export function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; - export function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; - export function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - export function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - export function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; - - export namespace constants { - // Allowed flush values. - - export const Z_NO_FLUSH: number; - export const Z_PARTIAL_FLUSH: number; - export const Z_SYNC_FLUSH: number; - export const Z_FULL_FLUSH: number; - export const Z_FINISH: number; - export const Z_BLOCK: number; - export const Z_TREES: number; - - // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. - - export const Z_OK: number; - export const Z_STREAM_END: number; - export const Z_NEED_DICT: number; - export const Z_ERRNO: number; - export const Z_STREAM_ERROR: number; - export const Z_DATA_ERROR: number; - export const Z_MEM_ERROR: number; - export const Z_BUF_ERROR: number; - export const Z_VERSION_ERROR: number; - - // Compression levels. - - export const Z_NO_COMPRESSION: number; - export const Z_BEST_SPEED: number; - export const Z_BEST_COMPRESSION: number; - export const Z_DEFAULT_COMPRESSION: number; - - // Compression strategy. - - export const Z_FILTERED: number; - export const Z_HUFFMAN_ONLY: number; - export const Z_RLE: number; - export const Z_FIXED: number; - export const Z_DEFAULT_STRATEGY: number; - } - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; -} - -declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - export interface NetworkInterfaceBase { - address: string; - netmask: string; - mac: string; - internal: boolean; - cidr: string | null; - } - - export interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: "IPv4"; - } - - export interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: "IPv6"; - scopeid: number; - } - - export type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; - - export function hostname(): string; - export function loadavg(): number[]; - export function uptime(): number; - export function freemem(): number; - export function totalmem(): number; - export function cpus(): CpuInfo[]; - export function type(): string; - export function release(): string; - export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function homedir(): string; - export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; - export var constants: { - UV_UDP_REUSEADDR: number, - signals: { - SIGHUP: number; - SIGINT: number; - SIGQUIT: number; - SIGILL: number; - SIGTRAP: number; - SIGABRT: number; - SIGIOT: number; - SIGBUS: number; - SIGFPE: number; - SIGKILL: number; - SIGUSR1: number; - SIGSEGV: number; - SIGUSR2: number; - SIGPIPE: number; - SIGALRM: number; - SIGTERM: number; - SIGCHLD: number; - SIGSTKFLT: number; - SIGCONT: number; - SIGSTOP: number; - SIGTSTP: number; - SIGTTIN: number; - SIGTTOU: number; - SIGURG: number; - SIGXCPU: number; - SIGXFSZ: number; - SIGVTALRM: number; - SIGPROF: number; - SIGWINCH: number; - SIGIO: number; - SIGPOLL: number; - SIGPWR: number; - SIGSYS: number; - SIGUNUSED: number; - }, - errno: { - E2BIG: number; - EACCES: number; - EADDRINUSE: number; - EADDRNOTAVAIL: number; - EAFNOSUPPORT: number; - EAGAIN: number; - EALREADY: number; - EBADF: number; - EBADMSG: number; - EBUSY: number; - ECANCELED: number; - ECHILD: number; - ECONNABORTED: number; - ECONNREFUSED: number; - ECONNRESET: number; - EDEADLK: number; - EDESTADDRREQ: number; - EDOM: number; - EDQUOT: number; - EEXIST: number; - EFAULT: number; - EFBIG: number; - EHOSTUNREACH: number; - EIDRM: number; - EILSEQ: number; - EINPROGRESS: number; - EINTR: number; - EINVAL: number; - EIO: number; - EISCONN: number; - EISDIR: number; - ELOOP: number; - EMFILE: number; - EMLINK: number; - EMSGSIZE: number; - EMULTIHOP: number; - ENAMETOOLONG: number; - ENETDOWN: number; - ENETRESET: number; - ENETUNREACH: number; - ENFILE: number; - ENOBUFS: number; - ENODATA: number; - ENODEV: number; - ENOENT: number; - ENOEXEC: number; - ENOLCK: number; - ENOLINK: number; - ENOMEM: number; - ENOMSG: number; - ENOPROTOOPT: number; - ENOSPC: number; - ENOSR: number; - ENOSTR: number; - ENOSYS: number; - ENOTCONN: number; - ENOTDIR: number; - ENOTEMPTY: number; - ENOTSOCK: number; - ENOTSUP: number; - ENOTTY: number; - ENXIO: number; - EOPNOTSUPP: number; - EOVERFLOW: number; - EPERM: number; - EPIPE: number; - EPROTO: number; - EPROTONOSUPPORT: number; - EPROTOTYPE: number; - ERANGE: number; - EROFS: number; - ESPIPE: number; - ESRCH: number; - ESTALE: number; - ETIME: number; - ETIMEDOUT: number; - ETXTBSY: number; - EWOULDBLOCK: number; - EXDEV: number; - }, - }; - export function arch(): string; - export function platform(): NodeJS.Platform; - export function tmpdir(): string; - export const EOL: string; - export function endianness(): "BE" | "LE"; -} - -declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; - import { URL } from "url"; - - export type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; - - export type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { - rejectUnauthorized?: boolean; // Defaults to true - servername?: string; // SNI TLS Extension - }; - - export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { - rejectUnauthorized?: boolean; - maxCachedSessions?: number; - } - - export class Agent extends http.Agent { - constructor(options?: AgentOptions); - options: AgentOptions; - } - - export class Server extends tls.Server { - setTimeout(callback: () => void): this; - setTimeout(msecs?: number, callback?: () => void): this; - timeout: number; - keepAliveTimeout: number; - } - - export function createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server; - export function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export var globalAgent: Agent; -} - -declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; -} - -declare module "repl" { - import { Interface, Completer, AsyncCompleter } from "readline"; - import { Context } from "vm"; - import { InspectOptions } from "util"; - - interface ReplOptions { - /** - * The input prompt to display. - * Default: `"> "` - */ - prompt?: string; - /** - * The `Readable` stream from which REPL input will be read. - * Default: `process.stdin` - */ - input?: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - * Default: `process.stdout` - */ - output?: NodeJS.WritableStream; - /** - * If `true`, specifies that the output should be treated as a TTY terminal, and have - * ANSI/VT100 escape codes written to it. - * Default: checking the value of the `isTTY` property on the output stream upon - * instantiation. - */ - terminal?: boolean; - /** - * The function to be used when evaluating each given line of input. - * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can - * error with `repl.Recoverable` to indicate the input was incomplete and prompt for - * additional lines. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions - */ - eval?: REPLEval; - /** - * If `true`, specifies that the default `writer` function should include ANSI color - * styling to REPL output. If a custom `writer` function is provided then this has no - * effect. - * Default: the REPL instance's `terminal` value. - */ - useColors?: boolean; - /** - * If `true`, specifies that the default evaluation function will use the JavaScript - * `global` as the context as opposed to creating a new separate context for the REPL - * instance. The node CLI REPL sets this value to `true`. - * Default: `false`. - */ - useGlobal?: boolean; - /** - * If `true`, specifies that the default writer will not output the return value of a - * command if it evaluates to `undefined`. - * Default: `false`. - */ - ignoreUndefined?: boolean; - /** - * The function to invoke to format the output of each command before writing to `output`. - * Default: a wrapper for `util.inspect`. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output - */ - writer?: REPLWriter; - /** - * An optional function used for custom Tab auto completion. - * - * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function - */ - completer?: Completer | AsyncCompleter; - /** - * A flag that specifies whether the default evaluator executes all JavaScript commands in - * strict mode or default (sloppy) mode. - * Accepted values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - /** - * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is - * pressed. This cannot be used together with a custom `eval` function. - * Default: `false`. - */ - breakEvalOnSigint?: boolean; - } - - type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; - type REPLWriter = (this: REPLServer, obj: any) => string; - - /** - * This is the default "writer" value, if none is passed in the REPL options, - * and it can be overridden by custom print functions. - */ - const writer: REPLWriter & { options: InspectOptions }; - - type REPLCommandAction = (this: REPLServer, text: string) => void; - - interface REPLCommand { - /** - * Help text to be displayed when `.help` is entered. - */ - help?: string; - /** - * The function to execute, optionally accepting a single string argument. - */ - action: REPLCommandAction; - } - - /** - * Provides a customizable Read-Eval-Print-Loop (REPL). - * - * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those - * according to a user-defined evaluation function, then output the result. Input and output - * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. - * - * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style - * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session - * state, error recovery, and customizable evaluation functions. - * - * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ - * be created directly using the JavaScript `new` keyword. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl - */ - class REPLServer extends Interface { - /** - * The `vm.Context` provided to the `eval` function to be used for JavaScript - * evaluation. - */ - readonly context: Context; - /** - * The `Readable` stream from which REPL input will be read. - */ - readonly inputStream: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - */ - readonly outputStream: NodeJS.WritableStream; - /** - * The commands registered via `replServer.defineCommand()`. - */ - readonly commands: { readonly [name: string]: REPLCommand | undefined }; - /** - * A value indicating whether the REPL is currently in "editor mode". - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys - */ - readonly editorMode: boolean; - /** - * A value indicating whether the `_` variable has been assigned. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreAssigned: boolean; - /** - * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly last: any; - /** - * A value indicating whether the `_error` variable has been assigned. - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreErrAssigned: boolean; - /** - * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly lastError: any; - /** - * Specified in the REPL options, this is the function to be used when evaluating each - * given line of input. If not specified in the REPL options, this is an async wrapper - * for the JavaScript `eval()` function. - */ - readonly eval: REPLEval; - /** - * Specified in the REPL options, this is a value indicating whether the default - * `writer` function should include ANSI color styling to REPL output. - */ - readonly useColors: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `eval` - * function will use the JavaScript `global` as the context as opposed to creating a new - * separate context for the REPL instance. - */ - readonly useGlobal: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `writer` - * function should output the result of a command if it evaluates to `undefined`. - */ - readonly ignoreUndefined: boolean; - /** - * Specified in the REPL options, this is the function to invoke to format the output of - * each command before writing to `outputStream`. If not specified in the REPL options, - * this will be a wrapper for `util.inspect`. - */ - readonly writer: REPLWriter; - /** - * Specified in the REPL options, this is the function to use for custom Tab auto-completion. - */ - readonly completer: Completer | AsyncCompleter; - /** - * Specified in the REPL options, this is a flag that specifies whether the default `eval` - * function should execute all JavaScript commands in strict mode or default (sloppy) mode. - * Possible values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - - /** - * NOTE: According to the documentation: - * - * > Instances of `repl.REPLServer` are created using the `repl.start()` method and - * > _should not_ be created directly using the JavaScript `new` keyword. - * - * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver - */ - private constructor(); - - /** - * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked - * by typing a `.` followed by the `keyword`. - * - * @param keyword The command keyword (_without_ a leading `.` character). - * @param cmd The function to invoke when the command is processed. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd - */ - defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; - /** - * Readies the REPL instance for input from the user, printing the configured `prompt` to a - * new line in the `output` and resuming the `input` to accept new input. - * - * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. - * - * This method is primarily intended to be called from within the action function for - * commands registered using the `replServer.defineCommand()` method. - * - * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. - */ - displayPrompt(preserveCursor?: boolean): void; - /** - * Clears any command that has been buffered but not yet executed. - * - * This method is primarily intended to be called from within the action function for - * commands registered using the `replServer.defineCommand()` method. - * - * @since v9.0.0 - */ - clearBufferedCommand(): void; - - /** - * events.EventEmitter - * 1. close - inherited from `readline.Interface` - * 2. line - inherited from `readline.Interface` - * 3. pause - inherited from `readline.Interface` - * 4. resume - inherited from `readline.Interface` - * 5. SIGCONT - inherited from `readline.Interface` - * 6. SIGINT - inherited from `readline.Interface` - * 7. SIGTSTP - inherited from `readline.Interface` - * 8. exit - * 9. reset - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: (context: Context) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - emit(event: "exit"): boolean; - emit(event: "reset", context: Context): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - on(event: "exit", listener: () => void): this; - on(event: "reset", listener: (context: Context) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - once(event: "exit", listener: () => void): this; - once(event: "reset", listener: (context: Context) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: (context: Context) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: (context: Context) => void): this; - } - - /** - * A flag passed in the REPL options. Evaluates expressions in sloppy mode. - */ - export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol - - /** - * A flag passed in the REPL options. Evaluates expressions in strict mode. - * This is equivalent to prefacing every repl statement with `'use strict'`. - */ - export const REPL_MODE_STRICT: symbol; // TODO: unique symbol - - /** - * Creates and starts a `repl.REPLServer` instance. - * - * @param options The options for the `REPLServer`. If `options` is a string, then it specifies - * the input prompt. - */ - function start(options?: string | ReplOptions): REPLServer; - - /** - * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors - */ - class Recoverable extends SyntaxError { - err: Error; - - constructor(err: Error); - } -} - -declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; - - interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } - - class Interface extends events.EventEmitter { - readonly terminal: boolean; - - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor(options: ReadLineOptions); - - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): this; - resume(): this; - close(): void; - write(data: string | Buffer, key?: Key): void; - - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 5. SIGCONT - * 6. SIGINT - * 7. SIGTSTP - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: any) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: any): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: any) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: any) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: any) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: any) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - } - - type ReadLine = Interface; // type forwarded for backwards compatiblity - - type Completer = (line: string) => CompleterResult; - type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; - - type CompleterResult = [string[], string]; - - interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer | AsyncCompleter; - terminal?: boolean; - historySize?: number; - prompt?: string; - crlfDelay?: number; - removeHistoryDuplicates?: boolean; - } - - function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; - function createInterface(options: ReadLineOptions): Interface; - - function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; - function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; - function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - function clearLine(stream: NodeJS.WritableStream, dir: number): void; - function clearScreenDown(stream: NodeJS.WritableStream): void; -} - -declare module "vm" { - export interface Context { - [key: string]: any; - } - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - export interface RunningScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - export class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - } - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; - /** @deprecated */ - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; - export function runInThisContext(code: string, options?: RunningScriptOptions | string): any; -} - -declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - import * as net from "net"; - - export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: StdioStreams; - killed: boolean; - pid: number; - kill(signal?: string): void; - send(message: any, callback?: (error: Error) => void): boolean; - send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; - send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; - connected: boolean; - disconnect(): void; - unref(): void; - ref(): void; - - /** - * events.EventEmitter - * 1. close - * 2. disconnect - * 3. error - * 4. exit - * 5. message - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (code: number, signal: string) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", code: number, signal: string): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (code: number, signal: string) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (code: number, signal: string) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (code: number, signal: string) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - } - - export interface StdioStreams extends ReadonlyArray { - 0: stream.Writable; // stdin - 1: stream.Readable; // stdout - 2: stream.Readable; // stderr - } - - export interface MessageOptions { - keepOpen?: boolean; - } - - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - windowsVerbatimArguments?: boolean; - windowsHide?: boolean; - } - - export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; - - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; - } - - export interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - - export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string | null; // specify `null`. - } - - // no `options` definitely means stdout/stderr are `string`. - export function exec(command: string, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; - - // `options` without an `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // fallback if nothing else matches. Worst case is always `string | Buffer`. - export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace exec { - export function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; - export function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - } - - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; - windowsVerbatimArguments?: boolean; - } - export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: 'buffer' | null; - } - export interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { - encoding: string; - } - - export function execFile(file: string): ChildProcess; - export function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; - - // no `options` definitely means stdout/stderr are `string`. - export function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - export function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - export function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - export function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding, callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; - - // `options` without an `encoding` means stdout/stderr are definitely `string`. - export function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; - - // fallback if nothing else matches. Worst case is always `string | Buffer`. - export function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null): ChildProcess; - export function execFile(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null): ChildProcess; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace execFile { - export function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; - export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; - export function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - export function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; - export function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - export function __promisify__(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; - } - - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - windowsVerbatimArguments?: boolean; - } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - shell?: boolean | string; - windowsHide?: boolean; - windowsVerbatimArguments?: boolean; - } - export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - windowsHide?: boolean; - } - export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; - - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - windowsHide?: boolean; - } - export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; -} - -declare module "url" { - import { ParsedUrlQuery } from 'querystring'; - - export interface UrlObjectCommon { - auth?: string; - hash?: string; - host?: string; - hostname?: string; - href?: string; - path?: string; - pathname?: string; - protocol?: string; - search?: string; - slashes?: boolean; - } - - // Input to `url.format` - export interface UrlObject extends UrlObjectCommon { - port?: string | number; - query?: string | null | { [key: string]: any }; - } - - // Output of `url.parse` - export interface Url extends UrlObjectCommon { - port?: string; - query?: string | null | ParsedUrlQuery; - } - - export interface UrlWithParsedQuery extends Url { - query: ParsedUrlQuery; - } - - export interface UrlWithStringQuery extends Url { - query: string | null; - } - - export function parse(urlStr: string): UrlWithStringQuery; - export function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; - export function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; - export function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; - - export function format(URL: URL, options?: URLFormatOptions): string; - export function format(urlObject: UrlObject | string): string; - export function resolve(from: string, to: string): string; - - export function domainToASCII(domain: string): string; - export function domainToUnicode(domain: string): string; - - export interface URLFormatOptions { - auth?: boolean; - fragment?: boolean; - search?: boolean; - unicode?: boolean; - } - - export class URLSearchParams implements Iterable<[string, string]> { - constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); - append(name: string, value: string): void; - delete(name: string): void; - entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string, searchParams: this) => void): void; - get(name: string): string | null; - getAll(name: string): string[]; - has(name: string): boolean; - keys(): IterableIterator; - set(name: string, value: string): void; - sort(): void; - toString(): string; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[string, string]>; - } - - export class URL { - constructor(input: string, base?: string | URL); - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toString(): string; - toJSON(): string; - } -} - -declare module "dns" { - // Supported getaddrinfo flags. - export const ADDRCONFIG: number; - export const V4MAPPED: number; - - export interface LookupOptions { - family?: number; - hints?: number; - all?: boolean; - } - - export interface LookupOneOptions extends LookupOptions { - all?: false; - } - - export interface LookupAllOptions extends LookupOptions { - all: true; - } - - export interface LookupAddress { - address: string; - family: number; - } - - export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; - export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; - export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; - export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; - export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lookup { - export function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; - export function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; - export function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; - } - - export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; - - export namespace lookupService { - export function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; - } - - export interface ResolveOptions { - ttl: boolean; - } - - export interface ResolveWithTtlOptions extends ResolveOptions { - ttl: true; - } - - export interface RecordWithTtl { - address: string; - ttl: number; - } - - export interface AnyARecord extends RecordWithTtl { - type: "A"; - } - - export interface AnyAaaaRecord extends RecordWithTtl { - type: "AAAA"; - } - - export interface MxRecord { - priority: number; - exchange: string; - } - - export interface AnyMxRecord extends MxRecord { - type: "MX"; - } - - export interface NaptrRecord { - flags: string; - service: string; - regexp: string; - replacement: string; - order: number; - preference: number; - } - - export interface AnyNaptrRecord extends NaptrRecord { - type: "NAPTR"; - } - - export interface SoaRecord { - nsname: string; - hostmaster: string; - serial: number; - refresh: number; - retry: number; - expire: number; - minttl: number; - } - - export interface AnySoaRecord extends SoaRecord { - type: "SOA"; - } - - export interface SrvRecord { - priority: number; - weight: number; - port: number; - name: string; - } - - export interface AnySrvRecord extends SrvRecord { - type: "SRV"; - } - - export interface AnyTxtRecord { - type: "TXT"; - entries: string[]; - } - - export interface AnyNsRecord { - type: "NS"; - value: string; - } - - export interface AnyPtrRecord { - type: "PTR"; - value: string; - } - - export interface AnyCnameRecord { - type: "CNAME"; - value: string; - } - - export type AnyRecord = AnyARecord | - AnyAaaaRecord | - AnyCnameRecord | - AnyMxRecord | - AnyNaptrRecord | - AnyNsRecord | - AnyPtrRecord | - AnySoaRecord | - AnySrvRecord | - AnyTxtRecord; - - export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; - export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; - export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; - export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; - export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; - export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; - export function resolve(hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace resolve { - export function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; - export function __promisify__(hostname: string, rrtype: "ANY"): Promise; - export function __promisify__(hostname: string, rrtype: "MX"): Promise; - export function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; - export function __promisify__(hostname: string, rrtype: "SOA"): Promise; - export function __promisify__(hostname: string, rrtype: "SRV"): Promise; - export function __promisify__(hostname: string, rrtype: "TXT"): Promise; - export function __promisify__(hostname: string, rrtype: string): Promise; - } - - export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; - export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace resolve4 { - export function __promisify__(hostname: string): Promise; - export function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - export function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - - export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; - export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace resolve6 { - export function __promisify__(hostname: string): Promise; - export function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - export function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - - export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export namespace resolveCname { - export function __promisify__(hostname: string): Promise; - } - - export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; - export namespace resolveMx { - export function __promisify__(hostname: string): Promise; - } - - export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; - export namespace resolveNaptr { - export function __promisify__(hostname: string): Promise; - } - - export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export namespace resolveNs { - export function __promisify__(hostname: string): Promise; - } - - export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; - export namespace resolvePtr { - export function __promisify__(hostname: string): Promise; - } - - export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; - export namespace resolveSoa { - export function __promisify__(hostname: string): Promise; - } - - export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; - export namespace resolveSrv { - export function __promisify__(hostname: string): Promise; - } - - export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; - export namespace resolveTxt { - export function __promisify__(hostname: string): Promise; - } - - export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; - export namespace resolveAny { - export function __promisify__(hostname: string): Promise; - } - - export function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; - export function setServers(servers: string[]): void; - export function getServers(): string[]; - - // Error codes - export var NODATA: string; - export var FORMERR: string; - export var SERVFAIL: string; - export var NOTFOUND: string; - export var NOTIMP: string; - export var REFUSED: string; - export var BADQUERY: string; - export var BADNAME: string; - export var BADFAMILY: string; - export var BADRESP: string; - export var CONNREFUSED: string; - export var TIMEOUT: string; - export var EOF: string; - export var FILE: string; - export var NOMEM: string; - export var DESTRUCTION: string; - export var BADSTR: string; - export var BADFLAGS: string; - export var NONAME: string; - export var BADHINTS: string; - export var NOTINITIALIZED: string; - export var LOADIPHLPAPI: string; - export var ADDRGETNETWORKPARAMS: string; - export var CANCELLED: string; - - export class Resolver { - getServers: typeof getServers; - setServers: typeof setServers; - resolve: typeof resolve; - resolve4: typeof resolve4; - resolve6: typeof resolve6; - resolveAny: typeof resolveAny; - resolveCname: typeof resolveCname; - resolveMx: typeof resolveMx; - resolveNaptr: typeof resolveNaptr; - resolveNs: typeof resolveNs; - resolvePtr: typeof resolvePtr; - resolveSoa: typeof resolveSoa; - resolveSrv: typeof resolveSrv; - resolveTxt: typeof resolveTxt; - reverse: typeof reverse; - cancel(): void; - } -} - -declare module "net" { - import * as stream from "stream"; - import * as events from "events"; - import * as dns from "dns"; - - type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; - - export interface AddressInfo { - address: string; - family: string; - port: number; - } - - export interface SocketConstructorOpts { - fd?: number; - allowHalfOpen?: boolean; - readable?: boolean; - writable?: boolean; - } - - export interface TcpSocketConnectOpts { - port: number; - host?: string; - localAddress?: string; - localPort?: number; - hints?: number; - family?: number; - lookup?: LookupFunction; - } - - export interface IpcSocketConnectOpts { - path: string; - } - - export type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; - - export class Socket extends stream.Duplex { - constructor(options?: SocketConstructorOpts); - - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(data: any, encoding?: string, callback?: Function): void; - - connect(options: SocketConnectOpts, connectionListener?: Function): this; - connect(port: number, host: string, connectionListener?: Function): this; - connect(port: number, connectionListener?: Function): this; - connect(path: string, connectionListener?: Function): this; - - bufferSize: number; - setEncoding(encoding?: string): this; - destroy(err?: any): void; - pause(): this; - resume(): this; - setTimeout(timeout: number, callback?: Function): this; - setNoDelay(noDelay?: boolean): this; - setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): AddressInfo | string; - unref(): void; - ref(): void; - - remoteAddress?: string; - remoteFamily?: string; - remotePort?: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; - connecting: boolean; - destroyed: boolean; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", had_error: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (had_error: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (had_error: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (had_error: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } - - // https://github.com/nodejs/node/blob/master/lib/net.js - export class Server extends events.EventEmitter { - constructor(connectionListener?: (socket: Socket) => void); - constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); - - listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; - listen(port?: number, hostname?: string, listeningListener?: Function): this; - listen(port?: number, backlog?: number, listeningListener?: Function): this; - listen(port?: number, listeningListener?: Function): this; - listen(path: string, backlog?: number, listeningListener?: Function): this; - listen(path: string, listeningListener?: Function): this; - listen(options: ListenOptions, listeningListener?: Function): this; - listen(handle: any, backlog?: number, listeningListener?: Function): this; - listen(handle: any, listeningListener?: Function): this; - close(callback?: Function): this; - address(): AddressInfo | string; - getConnections(cb: (error: Error | null, count: number) => void): void; - ref(): this; - unref(): this; - maxConnections: number; - connections: number; - listening: boolean; - - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - } - - export interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { - timeout?: number; - } - - export interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { - timeout?: number; - } - - export type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; - - export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: NetConnectOpts, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; -} - -declare module "dgram" { - import { AddressInfo } from "net"; - import * as dns from "dns"; - import * as events from "events"; - - export interface RemoteInfo { - address: string; - family: string; - port: number; - } - - export interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } - - type SocketType = "udp4" | "udp6"; - - export interface SocketOptions { - type: SocketType; - reuseAddr?: boolean; - recvBufferSize?: number; - sendBufferSize?: number; - lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; - } - - export function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - export class Socket extends events.EventEmitter { - send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - bind(port?: number, address?: string, callback?: () => void): void; - bind(port?: number, callback?: () => void): void; - bind(callback?: () => void): void; - bind(options: BindOptions, callback?: Function): void; - close(callback?: () => void): void; - address(): AddressInfo | string; - setBroadcast(flag: boolean): void; - setTTL(ttl: number): void; - setMulticastTTL(ttl: number): void; - setMulticastInterface(multicastInterface: string): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): this; - unref(): this; - setRecvBufferSize(size: number): void; - setSendBufferSize(size: number): void; - getRecvBufferSize(): number; - getSendBufferSize(): number; - - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - } -} - -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import { URL } from "url"; - - /** - * Valid types for path values in "fs". - */ - export type PathLike = string | Buffer | URL; - - export class Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atimeMs: number; - mtimeMs: number; - ctimeMs: number; - birthtimeMs: number; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - export interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - } - - export class ReadStream extends stream.Readable { - close(): void; - destroy(): void; - bytesRead: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - export class WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function renameSync(oldPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function __promisify__(path: PathLike, len?: number | null): Promise; - } - - /** - * Synchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function truncateSync(path: PathLike, len?: number | null): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function __promisify__(fd: number, len?: number | null): Promise; - } - - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function chownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function __promisify__(fd: number, uid: number, gid: number): Promise; - } - - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lchownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function chmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function __promisify__(fd: number, mode: string | number): Promise; - } - - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function fchmodSync(fd: number, mode: string | number): void; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function __promisify__(path: PathLike, mode: string | number): Promise; - } - - /** - * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function lchmodSync(path: PathLike, mode: string | number): void; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function statSync(path: PathLike): Stats; - - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function fstatSync(fd: number): Stats; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lstatSync(path: PathLike): Stats; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function link(existingPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function linkSync(existingPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - export function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - export type Type = "dir" | "file" | "junction"; - } - - /** - * Synchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - - export function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - export function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; - export function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; - export function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; - } - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - - export namespace realpathSync { - export function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - export function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; - export function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; - } - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function unlinkSync(path: PathLike): void; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function rmdirSync(path: PathLike): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, mode: number | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function __promisify__(path: PathLike, mode?: number | string | null): Promise; - } - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, mode?: number | string | null): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir(path: PathLike, options: { encoding: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer" }): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; - } - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): string[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[]; - - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function __promisify__(fd: number): Promise; - } - - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function closeSync(fd: number): void; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; - } - - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function fsyncSync(fd: number): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function write(fd: number, string: any, position: number | undefined | null, encoding: string | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - */ - export function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function __promisify__(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; - } - - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function writeSync(fd: number, buffer: Buffer | Uint8Array, offset?: number | null, length?: number | null, position?: number | null): number; - - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. If something other than a string is supplied it will be coerced to a string. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; - - /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function read(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - } - - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function readSync(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, position: number | null): number; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding?: string | null; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; - } - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function writeFile(path: PathLike | number, data: any, options: { encoding?: string | null; mode?: number | string; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function __promisify__(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): Promise; - } - - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function writeFileSync(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function appendFile(file: PathLike | number, data: any, options: { encoding?: string | null, mode?: string | number, flag?: string } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function __promisify__(file: PathLike | number, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string } | string | null): Promise; - } - - /** - * Synchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function appendFileSync(file: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - */ - export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch(filename: PathLike, options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, listener?: (event: string, filename: string) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch(filename: PathLike, options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, listener?: (event: string, filename: string | Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function existsSync(path: PathLike): boolean; - - export namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - export const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - export const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - export const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - export const X_OK: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - export const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - export const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - export const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - export const O_CREAT: number; - - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - export const O_EXCL: number; - - /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ - export const O_NOCTTY: number; - - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - export const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - export const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - export const O_DIRECTORY: number; - - /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ - export const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - export const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - export const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - export const O_DSYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - export const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - export const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - export const O_NONBLOCK: number; - - // File Type Constants - - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - export const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - export const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - export const S_IFDIR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - export const S_IFCHR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - export const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - export const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - export const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - export const S_IFSOCK: number; - - // File Mode Constants - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - export const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - export const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - export const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - export const S_IXUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - export const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - export const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - export const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - export const S_IXGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - export const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - export const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - export const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - export const S_IXOTH: number; - - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - export const COPYFILE_EXCL: number; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function __promisify__(path: PathLike, mode?: number): Promise; - } - - /** - * Synchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createReadStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - end?: number; - highWaterMark?: number; - }): ReadStream; - - /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createWriteStream(path: PathLike, options?: string | { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - }): WriteStream; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function fdatasyncSync(fd: number): void; - - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - */ - export function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; - } - - /** - * Synchronously copies src to dest. By default, dest is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; -} - -declare module "path" { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - export interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - export interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string; - /** - * The file extension (if any) such as '.html' - */ - ext?: string; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string; - } - - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ - export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths paths to join. - */ - export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} parameter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - export function resolve(...pathSegments: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - */ - export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ - export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ - export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ - export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - export var sep: '\\' | '/'; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - export var delimiter: ';' | ':'; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: FormatInputPathObject): string; - - export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: FormatInputPathObject): string; - } - - export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: FormatInputPathObject): string; - } -} - -declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - end(buffer?: Buffer): string; - } - export var StringDecoder: { - new(encoding?: string): NodeStringDecoder; - }; -} - -declare module "tls" { - import * as crypto from "crypto"; - import * as dns from "dns"; - import * as net from "net"; - import * as stream from "stream"; - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } - - export interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: { [index: string]: string[] | undefined }; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - ext_key_usage: string[]; - serialNumber: string; - raw: Buffer; - } - - export interface DetailedPeerCertificate extends PeerCertificate { - issuerCertificate: DetailedPeerCertificate; - } - - export interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } - - export class TLSSocket extends net.Socket { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket: net.Socket, options?: { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext, - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean, - /** - * An optional net.Server instance. - */ - server?: net.Server, - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean, - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. Defaults to false. - */ - rejectUnauthorized?: boolean, - /** - * An array of strings or a Buffer naming possible NPN protocols. - * (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) When the server - * receives both NPN and ALPN extensions from the client, ALPN takes - * precedence over NPN and the server does not send an NPN extension - * to the client. - */ - ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer, - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean - }); - - /** - * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. - */ - authorized: boolean; - /** - * The reason why the peer's certificate has not been verified. - * This property becomes available only when tlsSocket.authorized === false. - */ - authorizationError: Error; - /** - * Static boolean value, always true. - * May be used to distinguish TLS sockets from regular ones. - */ - encrypted: boolean; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the peer's certificate. - * The returned object has some properties corresponding to the field of the certificate. - * If detailed argument is true the full chain with issuer property will be returned, - * if false only the top certificate without issuer property. - * If the peer does not provide a certificate, it returns null or an empty object. - * @param detailed - If true; the full chain with issuer property will be returned. - * @returns An object representing the peer's certificate. - */ - getPeerCertificate(detailed: true): DetailedPeerCertificate; - getPeerCertificate(detailed?: false): PeerCertificate; - getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; - /** - * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. - * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. - * The value `null` will be returned for server sockets or disconnected client sockets. - * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. - * @returns negotiated SSL/TLS protocol version of the current connection - */ - getProtocol(): string | null; - /** - * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns ASN.1 encoded TLS session or undefined if none was negotiated. - */ - getSession(): any; - /** - * NOTE: Works only with client TLS sockets. - * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns TLS session ticket or undefined if none was negotiated. - */ - getTLSTicket(): any; - /** - * Initiate TLS renegotiation process. - * - * NOTE: Can be used to request peer's certificate after the secure connection has been established. - * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param options - The options may contain the following fields: rejectUnauthorized, - * requestCert (See tls.createServer() for details). - * @param callback - callback(err) will be executed with null as err, once the renegotiation - * is successfully completed. - */ - renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; - /** - * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by - * the TLS layer until the entire fragment is received and its integrity is verified; - * large fragments can span multiple roundtrips, and their processing can be delayed due to packet - * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, - * which may decrease overall server throughput. - * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns Returns true on success, false otherwise. - */ - setMaxSendFragment(size: number): boolean; - - /** - * events.EventEmitter - * 1. OCSPResponse - * 2. secureConnect - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - } - - export interface TlsOptions extends SecureContextOptions { - handshakeTimeout?: number; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - sessionTimeout?: number; - ticketKeys?: Buffer; - } - - export interface ConnectionOptions extends SecureContextOptions { - host?: string; - port?: number; - path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. - socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket - rejectUnauthorized?: boolean; // Defaults to true - NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; - checkServerIdentity?: typeof checkServerIdentity; - servername?: string; // SNI TLS Extension - session?: Buffer; - minDHSize?: number; - secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() - lookup?: net.LookupFunction; - } - - export class Server extends net.Server { - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; - emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; - emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export interface SecureContextOptions { - pfx?: string | Buffer | Array; - key?: string | Buffer | Array; - passphrase?: string; - cert?: string | Buffer | Array; - ca?: string | Buffer | Array; - ciphers?: string; - honorCipherOrder?: boolean; - ecdhCurve?: string; - clientCertEngine?: string; - crl?: string | Buffer | Array; - dhparam?: string | Buffer; - secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options - secureProtocol?: string; // SSL Method, e.g. SSLv23_method - sessionIdContext?: string; - } - - export interface SecureContext { - context: any; - } - - /* - * Verifies the certificate `cert` is issued to host `host`. - * @host The hostname to verify the certificate against - * @cert PeerCertificate representing the peer's certificate - * - * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. - */ - export function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; - export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; - export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - export function createSecureContext(details: SecureContextOptions): SecureContext; - export function getCiphers(): string[]; - - export var DEFAULT_ECDH_CURVE: string; -} - -declare module "crypto" { - export interface Certificate { - exportChallenge(spkac: string | Buffer): Buffer; - exportPublicKey(spkac: string | Buffer): Buffer; - verifySpkac(spkac: Buffer): boolean; - } - export var Certificate: { - new(): Certificate; - (): Certificate; - }; - - export var fips: boolean; - - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: string | string[]; - crl: string | string[]; - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string | Buffer): Hmac; - - type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; - type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; - type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; - type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - - export interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer | DataView): Hash; - update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Hash; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: string | Buffer | DataView): Hmac; - update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Hmac; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher extends NodeJS.ReadWriteStream { - update(data: Buffer | DataView): Buffer; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: Buffer | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): this; - getAuthTag(): Buffer; - setAAD(buffer: Buffer): this; - } - export function createDecipher(algorithm: string, password: any): Decipher; - export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - export interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer | DataView): Buffer; - update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; - update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): this; - setAuthTag(tag: Buffer): this; - setAAD(buffer: Buffer): this; - } - export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: string | Buffer | DataView): Signer; - update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase?: string }): Buffer; - sign(private_key: string | { key: string; passphrase?: string }, output_format: HexBase64Latin1Encoding): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: string | Buffer | DataView): Verify; - update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Verify; - verify(object: string | Object, signature: Buffer | DataView): boolean; - verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; - // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format - // The signature field accepts a TypedArray type, but it is only available starting ES2017 - } - export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; - export function createDiffieHellman(prime: Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; - export interface DiffieHellman { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrime(): Buffer; - getPrime(encoding: HexBase64Latin1Encoding): string; - getGenerator(): Buffer; - getGenerator(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: Buffer): void; - setPublicKey(public_key: string, encoding: string): void; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: string): void; - verifyError: number; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export function randomFillSync(buffer: Buffer | Uint8Array, offset?: number, size?: number): Buffer; - export function randomFill(buffer: Buffer, callback: (err: Error, buf: Buffer) => void): void; - export function randomFill(buffer: Uint8Array, callback: (err: Error, buf: Uint8Array) => void): void; - export function randomFill(buffer: Buffer, offset: number, callback: (err: Error, buf: Buffer) => void): void; - export function randomFill(buffer: Uint8Array, offset: number, callback: (err: Error, buf: Uint8Array) => void): void; - export function randomFill(buffer: Buffer, offset: number, size: number, callback: (err: Error, buf: Buffer) => void): void; - export function randomFill(buffer: Uint8Array, offset: number, size: number, callback: (err: Error, buf: Uint8Array) => void): void; - export interface RsaPublicKey { - key: string; - padding?: number; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string; - padding?: number; - } - export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer; - export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer; - export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer; - export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer; - export function getCiphers(): string[]; - export function getCurves(): string[]; - export function getHashes(): string[]; - export interface ECDH { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; - } - export function createECDH(curve_name: string): ECDH; - export function timingSafeEqual(a: Buffer, b: Buffer): boolean; - export var DEFAULT_ENCODING: string; -} - -declare module "stream" { - import * as events from "events"; - - class internal extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - namespace internal { - export class Stream extends internal { } - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (this: Readable, size?: number) => any; - destroy?: (error: Error | null, callback: (error?: Error) => void) => void; - } - - export class Readable extends Stream implements NodeJS.ReadableStream { - readable: boolean; - readonly readableHighWaterMark: number; - readonly readableLength: number; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - isPaused(): boolean; - unpipe(destination?: T): this; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): this; - push(chunk: any, encoding?: string): boolean; - _destroy(error: Error | null, callback: (error?: Error) => void): void; - destroy(error?: Error): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. readable - * 5. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - - removeListener(event: string, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: Array<{ chunk: string | Buffer, encoding: string }>, callback: Function) => any; - destroy?: (error: Error | null, callback: (error?: Error) => void) => void; - final?: (callback: (error?: Error) => void) => void; - } - - export class Writable extends Stream implements NodeJS.WritableStream { - writable: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(error: Error | null, callback: (error?: Error) => void): void; - _final(callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - setDefaultEncoding(encoding: string): this; - end(cb?: Function): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "drain", chunk: Buffer | string): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - - removeListener(event: string, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements Writable { - writable: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(error: Error | null, callback: (error?: Error) => void): void; - _final(callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - setDefaultEncoding(encoding: string): this; - end(cb?: Function): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - cork(): void; - uncork(): void; - } - - type TransformCallback = (err?: Error, data?: any) => void; - - export interface TransformOptions extends DuplexOptions { - transform?: (chunk: any, encoding: string, callback: TransformCallback) => any; - flush?: (callback: TransformCallback) => any; - } - - export class Transform extends Duplex { - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: TransformCallback): void; - destroy(error?: Error): void; - } - - export class PassThrough extends Transform { } - } - - export = internal; -} - -declare module "util" { - export interface InspectOptions extends NodeJS.InspectOptions { } - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export var inspect: { - (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - (object: any, options: InspectOptions): string; - colors: { - [color: string]: [number, number] | undefined - } - styles: { - [style: string]: string | undefined - } - defaultOptions: InspectOptions; - custom: symbol; - }; - export function isArray(object: any): object is any[]; - export function isRegExp(object: any): object is RegExp; - export function isDate(object: any): object is Date; - export function isError(object: any): object is Error; - export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key: string): (msg: string, ...param: any[]) => void; - export function isBoolean(object: any): object is boolean; - export function isBuffer(object: any): object is Buffer; - export function isFunction(object: any): boolean; - export function isNull(object: any): object is null; - export function isNullOrUndefined(object: any): object is null | undefined; - export function isNumber(object: any): object is number; - export function isObject(object: any): boolean; - export function isPrimitive(object: any): boolean; - export function isString(object: any): object is string; - export function isSymbol(object: any): object is symbol; - export function isUndefined(object: any): object is undefined; - export function deprecate(fn: T, message: string): T; - export function isDeepStrictEqual(val1: any, val2: any): boolean; - - export interface CustomPromisify extends Function { - __promisify__: TCustom; - } - - export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - - export function promisify(fn: CustomPromisify): TCustom; - export function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; - export function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; - export function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; - export function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - export function promisify(fn: Function): Function; - export namespace promisify { - const custom: symbol; - } - - export class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: - Int8Array - | Int16Array - | Int32Array - | Uint8Array - | Uint16Array - | Uint32Array - | Uint8ClampedArray - | Float32Array - | Float64Array - | DataView - | ArrayBuffer - | null, - options?: { stream?: boolean } - ): string; - } - - export class TextEncoder { - readonly encoding: string; - constructor(); - encode(input?: string): Uint8Array; - } -} - -declare module "assert" { - function internal(value: any, message?: string | Error): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - code: 'ERR_ASSERTION'; - - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFn?: Function - }); - } - - export function fail(message?: string | Error): never; - export function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; - export function ok(value: any, message?: string | Error): void; - export function equal(actual: any, expected: any, message?: string | Error): void; - export function notEqual(actual: any, expected: any, message?: string | Error): void; - export function deepEqual(actual: any, expected: any, message?: string | Error): void; - export function notDeepEqual(actual: any, expected: any, message?: string | Error): void; - export function strictEqual(actual: any, expected: any, message?: string | Error): void; - export function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - export function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - - export function throws(block: Function, message?: string | Error): void; - export function throws(block: Function, error: RegExp | Function, message?: string | Error): void; - export function doesNotThrow(block: Function, message?: string | Error): void; - export function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; - - export function ifError(value: any): void; - } - - export = internal; -} - -declare module "tty" { - import * as net from "net"; - - export function isatty(fd: number): boolean; - export class ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export class WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } -} - -declare module "domain" { - import * as events from "events"; - - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - members: any[]; - enter(): void; - exit(): void; - } - - export function create(): Domain; -} - -declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFBLK: number; - export var S_IFIFO: number; - export var S_IFSOCK: number; - export var S_IRWXU: number; - export var S_IRUSR: number; - export var S_IWUSR: number; - export var S_IXUSR: number; - export var S_IRWXG: number; - export var S_IRGRP: number; - export var S_IWGRP: number; - export var S_IXGRP: number; - export var S_IRWXO: number; - export var S_IROTH: number; - export var S_IWOTH: number; - export var S_IXOTH: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_NOCTTY: number; - export var O_DIRECTORY: number; - export var O_NOATIME: number; - export var O_NOFOLLOW: number; - export var O_SYNC: number; - export var O_DSYNC: number; - export var O_SYMLINK: number; - export var O_DIRECT: number; - export var O_NONBLOCK: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; - export var SIGQUIT: number; - export var SIGTRAP: number; - export var SIGIOT: number; - export var SIGBUS: number; - export var SIGUSR1: number; - export var SIGUSR2: number; - export var SIGPIPE: number; - export var SIGALRM: number; - export var SIGCHLD: number; - export var SIGSTKFLT: number; - export var SIGCONT: number; - export var SIGSTOP: number; - export var SIGTSTP: number; - export var SIGTTIN: number; - export var SIGTTOU: number; - export var SIGURG: number; - export var SIGXCPU: number; - export var SIGXFSZ: number; - export var SIGVTALRM: number; - export var SIGPROF: number; - export var SIGIO: number; - export var SIGPOLL: number; - export var SIGPWR: number; - export var SIGSYS: number; - export var SIGUNUSED: number; - export var defaultCoreCipherList: string; - export var defaultCipherList: string; - export var ENGINE_METHOD_RSA: number; - export var ALPN_ENABLED: number; -} - -declare module "module" { - export = NodeJS.Module; -} - -declare module "process" { - export = process; -} - -declare module "v8" { - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; - } - - // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ - type DoesZapCodeSpaceFlag = 0 | 1; - - interface HeapInfo { - total_heap_size: number; - total_heap_size_executable: number; - total_physical_size: number; - total_available_size: number; - used_heap_size: number; - heap_size_limit: number; - malloced_memory: number; - peak_malloced_memory: number; - does_zap_garbage: DoesZapCodeSpaceFlag; - } - - export function getHeapStatistics(): HeapInfo; - export function getHeapSpaceStatistics(): HeapSpaceInfo[]; - export function setFlagsFromString(flags: string): void; -} - -declare module "timers" { - export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export namespace setTimeout { - export function __promisify__(ms: number): Promise; - export function __promisify__(ms: number, value: T): Promise; - } - export function clearTimeout(timeoutId: NodeJS.Timer): void; - export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearInterval(intervalId: NodeJS.Timer): void; - export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; - export namespace setImmediate { - export function __promisify__(): Promise; - export function __promisify__(value: T): Promise; - } - export function clearImmediate(immediateId: any): void; -} - -declare module "console" { - export = console; -} - -/** - * Async Hooks module: https://nodejs.org/api/async_hooks.html - */ -declare module "async_hooks" { - /** - * Returns the asyncId of the current execution context. - */ - export function executionAsyncId(): number; - /// @deprecated - replaced by executionAsyncId() - export function currentId(): number; - - /** - * Returns the ID of the resource responsible for calling the callback that is currently being executed. - */ - export function triggerAsyncId(): number; - /// @deprecated - replaced by triggerAsyncId() - export function triggerId(): number; - - export interface HookCallbacks { - /** - * Called when a class is constructed that has the possibility to emit an asynchronous event. - * @param asyncId a unique ID for the async resource - * @param type the type of the async resource - * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created - * @param resource reference to the resource representing the async operation, needs to be released during destroy - */ - init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; - - /** - * When an asynchronous operation is initiated or completes a callback is called to notify the user. - * The before callback is called just before said callback is executed. - * @param asyncId the unique identifier assigned to the resource about to execute the callback. - */ - before?(asyncId: number): void; - - /** - * Called immediately after the callback specified in before is completed. - * @param asyncId the unique identifier assigned to the resource which has executed the callback. - */ - after?(asyncId: number): void; - - /** - * Called when a promise has resolve() called. This may not be in the same execution id - * as the promise itself. - * @param asyncId the unique id for the promise that was resolve()d. - */ - promiseResolve?(asyncId: number): void; - - /** - * Called after the resource corresponding to asyncId is destroyed - * @param asyncId a unique ID for the async resource - */ - destroy?(asyncId: number): void; - } - - export interface AsyncHook { - /** - * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. - */ - enable(): this; - - /** - * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. - */ - disable(): this; - } - - /** - * Registers functions to be called for different lifetime events of each async operation. - * @param options the callbacks to register - * @return an AsyncHooks instance used for disabling and enabling hooks - */ - export function createHook(options: HookCallbacks): AsyncHook; - - export interface AsyncResourceOptions { - /** - * The ID of the execution context that created this async event. - * Default: `executionAsyncId()` - */ - triggerAsyncId?: number; - - /** - * Disables automatic `emitDestroy` when the object is garbage collected. - * This usually does not need to be set (even if `emitDestroy` is called - * manually), unless the resource's `asyncId` is retrieved and the - * sensitive API's `emitDestroy` is called with it. - * Default: `false` - */ - requireManualDestroy?: boolean; - } - - /** - * The class AsyncResource was designed to be extended by the embedder's async resources. - * Using this users can easily trigger the lifetime events of their own resources. - */ - export class AsyncResource { - /** - * AsyncResource() is meant to be extended. Instantiating a - * new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * async_hook.executionAsyncId() is used. - * @param type The type of async event. - * @param triggerAsyncId The ID of the execution context that created - * this async event (default: `executionAsyncId()`), or an - * AsyncResourceOptions object (since 9.3) - */ - constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); - - /** - * Call AsyncHooks before callbacks. - * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. - */ - emitBefore(): void; - - /** - * Call AsyncHooks after callbacks. - * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. - */ - emitAfter(): void; - - /** - * Call the provided function with the provided arguments in the - * execution context of the async resource. This will establish the - * context, trigger the AsyncHooks before callbacks, call the function, - * trigger the AsyncHooks after callbacks, and then restore the original - * execution context. - * @param fn The function to call in the execution context of this - * async resource. - * @param thisArg The receiver to be used for the function call. - * @param args Optional arguments to pass to the function. - */ - runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; - - /** - * Call AsyncHooks destroy callbacks. - */ - emitDestroy(): void; - - /** - * @return the unique ID assigned to this AsyncResource instance. - */ - asyncId(): number; - - /** - * @return the trigger ID for this AsyncResource instance. - */ - triggerAsyncId(): number; - } -} - -declare module "http2" { - import * as events from "events"; - import * as fs from "fs"; - import * as net from "net"; - import * as stream from "stream"; - import * as tls from "tls"; - import * as url from "url"; - - import { IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; - export { IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; - - // Http2Stream - - export interface StreamPriorityOptions { - exclusive?: boolean; - parent?: number; - weight?: number; - silent?: boolean; - } - - export interface StreamState { - localWindowSize?: number; - state?: number; - streamLocalClose?: number; - streamRemoteClose?: number; - sumDependencyWeight?: number; - weight?: number; - } - - export interface ServerStreamResponseOptions { - endStream?: boolean; - getTrailers?: (trailers: OutgoingHttpHeaders) => void; - } - - export interface StatOptions { - offset: number; - length: number; - } - - export interface ServerStreamFileResponseOptions { - statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; - getTrailers?: (trailers: OutgoingHttpHeaders) => void; - offset?: number; - length?: number; - } - - export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { - onError?: (err: NodeJS.ErrnoException) => void; - } - - export interface Http2Stream extends stream.Duplex { - readonly aborted: boolean; - close(code: number, callback?: () => void): void; - readonly closed: boolean; - readonly destroyed: boolean; - readonly pending: boolean; - priority(options: StreamPriorityOptions): void; - readonly rstCode: number; - readonly session: Http2Session; - setTimeout(msecs: number, callback?: () => void): void; - readonly state: StreamState; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: () => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: "streamClosed", listener: (code: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted"): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "frameError", frameType: number, errorCode: number): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: "streamClosed", code: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: () => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: "streamClosed", listener: (code: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: () => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: "streamClosed", listener: (code: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: () => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "streamClosed", listener: (code: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: () => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - } - - export interface ClientHttp2Stream extends Http2Stream { - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "headers", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "response", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "headers", headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "response", headers: IncomingHttpHeaders, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "headers", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "response", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "headers", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "response", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "headers", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "response", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - } - - export interface ServerHttp2Stream extends Http2Stream { - additionalHeaders(headers: OutgoingHttpHeaders): void; - readonly headersSent: boolean; - readonly pushAllowed: boolean; - pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; - pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; - respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; - respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; - respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; - } - - // Http2Session - - export interface Settings { - headerTableSize?: number; - enablePush?: boolean; - initialWindowSize?: number; - maxFrameSize?: number; - maxConcurrentStreams?: number; - maxHeaderListSize?: number; - } - - export interface ClientSessionRequestOptions { - endStream?: boolean; - exclusive?: boolean; - parent?: number; - weight?: number; - getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; - } - - export interface SessionState { - effectiveLocalWindowSize?: number; - effectiveRecvDataLength?: number; - nextStreamID?: number; - localWindowSize?: number; - lastProcStreamID?: number; - remoteWindowSize?: number; - outboundQueueSize?: number; - deflateDynamicTableSize?: number; - inflateDynamicTableSize?: number; - } - - export interface Http2Session extends events.EventEmitter { - readonly alpnProtocol?: string; - close(callback?: () => void): void; - readonly closed: boolean; - destroy(error?: Error, code?: number): void; - readonly destroyed: boolean; - readonly encrypted?: boolean; - goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView /*| TypedArray*/): void; - readonly localSettings: Settings; - readonly originSet?: string[]; - readonly pendingSettingsAck: boolean; - ref(): void; - readonly remoteSettings: Settings; - rstStream(stream: Http2Stream, code?: number): void; - setTimeout(msecs: number, callback?: () => void): void; - readonly socket: net.Socket | tls.TLSSocket; - readonly state: SessionState; - priority(stream: Http2Stream, options: StreamPriorityOptions): void; - settings(settings: Settings): void; - readonly type: number; - unref(): void; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - addListener(event: "localSettings", listener: (settings: Settings) => void): this; - addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; - emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; - emit(event: "localSettings", settings: Settings): boolean; - emit(event: "remoteSettings", settings: Settings): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - on(event: "localSettings", listener: (settings: Settings) => void): this; - on(event: "remoteSettings", listener: (settings: Settings) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - once(event: "localSettings", listener: (settings: Settings) => void): this; - once(event: "remoteSettings", listener: (settings: Settings) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - export interface ClientHttp2Session extends Http2Session { - request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; - emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - } - - export interface AlternativeServiceOptions { - origin: number | string | url.URL; - } - - export interface ServerHttp2Session extends Http2Session { - altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; - readonly server: Http2Server | Http2SecureServer; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - } - - // Http2Server - - export interface SessionOptions { - maxDeflateDynamicTableSize?: number; - maxReservedRemoteStreams?: number; - maxSendHeaderBlockLength?: number; - paddingStrategy?: number; - peerMaxConcurrentStreams?: number; - selectPadding?: (frameLen: number, maxFrameLen: number) => number; - settings?: Settings; - } - - export type ClientSessionOptions = SessionOptions; - export type ServerSessionOptions = SessionOptions; - - export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } - export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } - - export interface ServerOptions extends ServerSessionOptions { - allowHTTP1?: boolean; - } - - export interface SecureServerOptions extends SecureServerSessionOptions { - allowHTTP1?: boolean; - } - - export interface Http2Server extends net.Server { - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - export interface Http2SecureServer extends tls.Server { - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - } - - export class Http2ServerRequest extends stream.Readable { - private constructor(); - headers: IncomingHttpHeaders; - httpVersion: string; - method: string; - rawHeaders: string[]; - rawTrailers: string[]; - setTimeout(msecs: number, callback?: () => void): void; - socket: net.Socket | tls.TLSSocket; - stream: ServerHttp2Stream; - trailers: IncomingHttpHeaders; - url: string; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted", hadError: boolean, code: number): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - } - - export class Http2ServerResponse extends events.EventEmitter { - private constructor(); - addTrailers(trailers: OutgoingHttpHeaders): void; - connection: net.Socket | tls.TLSSocket; - end(callback?: () => void): void; - end(data?: string | Buffer, callback?: () => void): void; - end(data?: string | Buffer, encoding?: string, callback?: () => void): void; - readonly finished: boolean; - getHeader(name: string): string; - getHeaderNames(): string[]; - getHeaders(): OutgoingHttpHeaders; - hasHeader(name: string): boolean; - readonly headersSent: boolean; - removeHeader(name: string): void; - sendDate: boolean; - setHeader(name: string, value: number | string | string[]): void; - setTimeout(msecs: number, callback?: () => void): void; - socket: net.Socket | tls.TLSSocket; - statusCode: number; - statusMessage: ''; - stream: ServerHttp2Stream; - write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; - write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; - writeContinue(): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; - createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted", hadError: boolean, code: number): boolean; - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "finish"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "finish", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "finish", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - } - - // Public API - - export namespace constants { - export const NGHTTP2_SESSION_SERVER: number; - export const NGHTTP2_SESSION_CLIENT: number; - export const NGHTTP2_STREAM_STATE_IDLE: number; - export const NGHTTP2_STREAM_STATE_OPEN: number; - export const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; - export const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; - export const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; - export const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; - export const NGHTTP2_STREAM_STATE_CLOSED: number; - export const NGHTTP2_NO_ERROR: number; - export const NGHTTP2_PROTOCOL_ERROR: number; - export const NGHTTP2_INTERNAL_ERROR: number; - export const NGHTTP2_FLOW_CONTROL_ERROR: number; - export const NGHTTP2_SETTINGS_TIMEOUT: number; - export const NGHTTP2_STREAM_CLOSED: number; - export const NGHTTP2_FRAME_SIZE_ERROR: number; - export const NGHTTP2_REFUSED_STREAM: number; - export const NGHTTP2_CANCEL: number; - export const NGHTTP2_COMPRESSION_ERROR: number; - export const NGHTTP2_CONNECT_ERROR: number; - export const NGHTTP2_ENHANCE_YOUR_CALM: number; - export const NGHTTP2_INADEQUATE_SECURITY: number; - export const NGHTTP2_HTTP_1_1_REQUIRED: number; - export const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; - export const NGHTTP2_FLAG_NONE: number; - export const NGHTTP2_FLAG_END_STREAM: number; - export const NGHTTP2_FLAG_END_HEADERS: number; - export const NGHTTP2_FLAG_ACK: number; - export const NGHTTP2_FLAG_PADDED: number; - export const NGHTTP2_FLAG_PRIORITY: number; - export const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; - export const DEFAULT_SETTINGS_ENABLE_PUSH: number; - export const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; - export const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; - export const MAX_MAX_FRAME_SIZE: number; - export const MIN_MAX_FRAME_SIZE: number; - export const MAX_INITIAL_WINDOW_SIZE: number; - export const NGHTTP2_DEFAULT_WEIGHT: number; - export const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; - export const NGHTTP2_SETTINGS_ENABLE_PUSH: number; - export const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; - export const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; - export const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; - export const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; - export const PADDING_STRATEGY_NONE: number; - export const PADDING_STRATEGY_MAX: number; - export const PADDING_STRATEGY_CALLBACK: number; - export const HTTP2_HEADER_STATUS: string; - export const HTTP2_HEADER_METHOD: string; - export const HTTP2_HEADER_AUTHORITY: string; - export const HTTP2_HEADER_SCHEME: string; - export const HTTP2_HEADER_PATH: string; - export const HTTP2_HEADER_ACCEPT_CHARSET: string; - export const HTTP2_HEADER_ACCEPT_ENCODING: string; - export const HTTP2_HEADER_ACCEPT_LANGUAGE: string; - export const HTTP2_HEADER_ACCEPT_RANGES: string; - export const HTTP2_HEADER_ACCEPT: string; - export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; - export const HTTP2_HEADER_AGE: string; - export const HTTP2_HEADER_ALLOW: string; - export const HTTP2_HEADER_AUTHORIZATION: string; - export const HTTP2_HEADER_CACHE_CONTROL: string; - export const HTTP2_HEADER_CONNECTION: string; - export const HTTP2_HEADER_CONTENT_DISPOSITION: string; - export const HTTP2_HEADER_CONTENT_ENCODING: string; - export const HTTP2_HEADER_CONTENT_LANGUAGE: string; - export const HTTP2_HEADER_CONTENT_LENGTH: string; - export const HTTP2_HEADER_CONTENT_LOCATION: string; - export const HTTP2_HEADER_CONTENT_MD5: string; - export const HTTP2_HEADER_CONTENT_RANGE: string; - export const HTTP2_HEADER_CONTENT_TYPE: string; - export const HTTP2_HEADER_COOKIE: string; - export const HTTP2_HEADER_DATE: string; - export const HTTP2_HEADER_ETAG: string; - export const HTTP2_HEADER_EXPECT: string; - export const HTTP2_HEADER_EXPIRES: string; - export const HTTP2_HEADER_FROM: string; - export const HTTP2_HEADER_HOST: string; - export const HTTP2_HEADER_IF_MATCH: string; - export const HTTP2_HEADER_IF_MODIFIED_SINCE: string; - export const HTTP2_HEADER_IF_NONE_MATCH: string; - export const HTTP2_HEADER_IF_RANGE: string; - export const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; - export const HTTP2_HEADER_LAST_MODIFIED: string; - export const HTTP2_HEADER_LINK: string; - export const HTTP2_HEADER_LOCATION: string; - export const HTTP2_HEADER_MAX_FORWARDS: string; - export const HTTP2_HEADER_PREFER: string; - export const HTTP2_HEADER_PROXY_AUTHENTICATE: string; - export const HTTP2_HEADER_PROXY_AUTHORIZATION: string; - export const HTTP2_HEADER_RANGE: string; - export const HTTP2_HEADER_REFERER: string; - export const HTTP2_HEADER_REFRESH: string; - export const HTTP2_HEADER_RETRY_AFTER: string; - export const HTTP2_HEADER_SERVER: string; - export const HTTP2_HEADER_SET_COOKIE: string; - export const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; - export const HTTP2_HEADER_TRANSFER_ENCODING: string; - export const HTTP2_HEADER_TE: string; - export const HTTP2_HEADER_UPGRADE: string; - export const HTTP2_HEADER_USER_AGENT: string; - export const HTTP2_HEADER_VARY: string; - export const HTTP2_HEADER_VIA: string; - export const HTTP2_HEADER_WWW_AUTHENTICATE: string; - export const HTTP2_HEADER_HTTP2_SETTINGS: string; - export const HTTP2_HEADER_KEEP_ALIVE: string; - export const HTTP2_HEADER_PROXY_CONNECTION: string; - export const HTTP2_METHOD_ACL: string; - export const HTTP2_METHOD_BASELINE_CONTROL: string; - export const HTTP2_METHOD_BIND: string; - export const HTTP2_METHOD_CHECKIN: string; - export const HTTP2_METHOD_CHECKOUT: string; - export const HTTP2_METHOD_CONNECT: string; - export const HTTP2_METHOD_COPY: string; - export const HTTP2_METHOD_DELETE: string; - export const HTTP2_METHOD_GET: string; - export const HTTP2_METHOD_HEAD: string; - export const HTTP2_METHOD_LABEL: string; - export const HTTP2_METHOD_LINK: string; - export const HTTP2_METHOD_LOCK: string; - export const HTTP2_METHOD_MERGE: string; - export const HTTP2_METHOD_MKACTIVITY: string; - export const HTTP2_METHOD_MKCALENDAR: string; - export const HTTP2_METHOD_MKCOL: string; - export const HTTP2_METHOD_MKREDIRECTREF: string; - export const HTTP2_METHOD_MKWORKSPACE: string; - export const HTTP2_METHOD_MOVE: string; - export const HTTP2_METHOD_OPTIONS: string; - export const HTTP2_METHOD_ORDERPATCH: string; - export const HTTP2_METHOD_PATCH: string; - export const HTTP2_METHOD_POST: string; - export const HTTP2_METHOD_PRI: string; - export const HTTP2_METHOD_PROPFIND: string; - export const HTTP2_METHOD_PROPPATCH: string; - export const HTTP2_METHOD_PUT: string; - export const HTTP2_METHOD_REBIND: string; - export const HTTP2_METHOD_REPORT: string; - export const HTTP2_METHOD_SEARCH: string; - export const HTTP2_METHOD_TRACE: string; - export const HTTP2_METHOD_UNBIND: string; - export const HTTP2_METHOD_UNCHECKOUT: string; - export const HTTP2_METHOD_UNLINK: string; - export const HTTP2_METHOD_UNLOCK: string; - export const HTTP2_METHOD_UPDATE: string; - export const HTTP2_METHOD_UPDATEREDIRECTREF: string; - export const HTTP2_METHOD_VERSION_CONTROL: string; - export const HTTP_STATUS_CONTINUE: number; - export const HTTP_STATUS_SWITCHING_PROTOCOLS: number; - export const HTTP_STATUS_PROCESSING: number; - export const HTTP_STATUS_OK: number; - export const HTTP_STATUS_CREATED: number; - export const HTTP_STATUS_ACCEPTED: number; - export const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; - export const HTTP_STATUS_NO_CONTENT: number; - export const HTTP_STATUS_RESET_CONTENT: number; - export const HTTP_STATUS_PARTIAL_CONTENT: number; - export const HTTP_STATUS_MULTI_STATUS: number; - export const HTTP_STATUS_ALREADY_REPORTED: number; - export const HTTP_STATUS_IM_USED: number; - export const HTTP_STATUS_MULTIPLE_CHOICES: number; - export const HTTP_STATUS_MOVED_PERMANENTLY: number; - export const HTTP_STATUS_FOUND: number; - export const HTTP_STATUS_SEE_OTHER: number; - export const HTTP_STATUS_NOT_MODIFIED: number; - export const HTTP_STATUS_USE_PROXY: number; - export const HTTP_STATUS_TEMPORARY_REDIRECT: number; - export const HTTP_STATUS_PERMANENT_REDIRECT: number; - export const HTTP_STATUS_BAD_REQUEST: number; - export const HTTP_STATUS_UNAUTHORIZED: number; - export const HTTP_STATUS_PAYMENT_REQUIRED: number; - export const HTTP_STATUS_FORBIDDEN: number; - export const HTTP_STATUS_NOT_FOUND: number; - export const HTTP_STATUS_METHOD_NOT_ALLOWED: number; - export const HTTP_STATUS_NOT_ACCEPTABLE: number; - export const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; - export const HTTP_STATUS_REQUEST_TIMEOUT: number; - export const HTTP_STATUS_CONFLICT: number; - export const HTTP_STATUS_GONE: number; - export const HTTP_STATUS_LENGTH_REQUIRED: number; - export const HTTP_STATUS_PRECONDITION_FAILED: number; - export const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; - export const HTTP_STATUS_URI_TOO_LONG: number; - export const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; - export const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; - export const HTTP_STATUS_EXPECTATION_FAILED: number; - export const HTTP_STATUS_TEAPOT: number; - export const HTTP_STATUS_MISDIRECTED_REQUEST: number; - export const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; - export const HTTP_STATUS_LOCKED: number; - export const HTTP_STATUS_FAILED_DEPENDENCY: number; - export const HTTP_STATUS_UNORDERED_COLLECTION: number; - export const HTTP_STATUS_UPGRADE_REQUIRED: number; - export const HTTP_STATUS_PRECONDITION_REQUIRED: number; - export const HTTP_STATUS_TOO_MANY_REQUESTS: number; - export const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; - export const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; - export const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; - export const HTTP_STATUS_NOT_IMPLEMENTED: number; - export const HTTP_STATUS_BAD_GATEWAY: number; - export const HTTP_STATUS_SERVICE_UNAVAILABLE: number; - export const HTTP_STATUS_GATEWAY_TIMEOUT: number; - export const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; - export const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; - export const HTTP_STATUS_INSUFFICIENT_STORAGE: number; - export const HTTP_STATUS_LOOP_DETECTED: number; - export const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; - export const HTTP_STATUS_NOT_EXTENDED: number; - export const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; - } - - export function getDefaultSettings(): Settings; - export function getPackedSettings(settings: Settings): Settings; - export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; - - export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - - export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - - export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; - export function connect(authority: string | url.URL, options?: ClientSessionOptions | SecureClientSessionOptions, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; -} - -declare module "perf_hooks" { - export interface PerformanceEntry { - /** - * The total number of milliseconds elapsed for this entry. - * This value will not be meaningful for all Performance Entry types. - */ - readonly duration: number; - - /** - * The name of the performance entry. - */ - readonly name: string; - - /** - * The high resolution millisecond timestamp marking the starting time of the Performance Entry. - */ - readonly startTime: number; - - /** - * The type of the performance entry. - * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. - */ - readonly entryType: string; - - /** - * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies - * the type of garbage collection operation that occurred. - * The value may be one of perf_hooks.constants. - */ - readonly kind?: number; - } - - export interface PerformanceNodeTiming extends PerformanceEntry { - /** - * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. - */ - readonly bootstrapComplete: number; - - /** - * The high resolution millisecond timestamp at which cluster processing ended. - */ - readonly clusterSetupEnd: number; - - /** - * The high resolution millisecond timestamp at which cluster processing started. - */ - readonly clusterSetupStart: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop exited. - */ - readonly loopExit: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop started. - */ - readonly loopStart: number; - - /** - * The high resolution millisecond timestamp at which main module load ended. - */ - readonly moduleLoadEnd: number; - - /** - * The high resolution millisecond timestamp at which main module load started. - */ - readonly moduleLoadStart: number; - - /** - * The high resolution millisecond timestamp at which the Node.js process was initialized. - */ - readonly nodeStart: number; - - /** - * The high resolution millisecond timestamp at which preload module load ended. - */ - readonly preloadModuleLoadEnd: number; - - /** - * The high resolution millisecond timestamp at which preload module load started. - */ - readonly preloadModuleLoadStart: number; - - /** - * The high resolution millisecond timestamp at which third_party_main processing ended. - */ - readonly thirdPartyMainEnd: number; - - /** - * The high resolution millisecond timestamp at which third_party_main processing started. - */ - readonly thirdPartyMainStart: number; - - /** - * The high resolution millisecond timestamp at which the V8 platform was initialized. - */ - readonly v8Start: number; - } - - export interface Performance { - /** - * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. - * If name is provided, removes entries with name. - * @param name - */ - clearFunctions(name?: string): void; - - /** - * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. - * If name is provided, removes only the named mark. - * @param name - */ - clearMarks(name?: string): void; - - /** - * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. - * If name is provided, removes only objects whose performanceEntry.name matches name. - */ - clearMeasures(name?: string): void; - - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. - * @return list of all PerformanceEntry objects - */ - getEntries(): PerformanceEntry[]; - - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. - * @param name - * @param type - * @return list of all PerformanceEntry objects - */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; - - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.entryType is equal to type. - * @param type - * @return list of all PerformanceEntry objects - */ - getEntriesByType(type: string): PerformanceEntry[]; - - /** - * Creates a new PerformanceMark entry in the Performance Timeline. - * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', - * and whose performanceEntry.duration is always 0. - * Performance marks are used to mark specific significant moments in the Performance Timeline. - * @param name - */ - mark(name?: string): void; - - /** - * Creates a new PerformanceMeasure entry in the Performance Timeline. - * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', - * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. - * - * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify - * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, - * then startMark is set to timeOrigin by default. - * - * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp - * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. - * @param name - * @param startMark - * @param endMark - */ - measure(name: string, startMark: string, endMark: string): void; - - /** - * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. - */ - readonly nodeTiming: PerformanceNodeTiming; - - /** - * @return the current high resolution millisecond timestamp - */ - now(): number; - - /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. - */ - readonly timeOrigin: number; - - /** - * Wraps a function within a new function that measures the running time of the wrapped function. - * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. - * @param fn - */ - timerify any>(fn: T): T; - } - - export interface PerformanceObserverEntryList { - /** - * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. - */ - getEntries(): PerformanceEntry[]; - - /** - * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. - */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; - - /** - * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.entryType is equal to type. - */ - getEntriesByType(type: string): PerformanceEntry[]; - } - - export type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; - - export class PerformanceObserver { - constructor(callback: PerformanceObserverCallback); - - /** - * Disconnects the PerformanceObserver instance from all notifications. - */ - disconnect(): void; - - /** - * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. - * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. - * Property buffered defaults to false. - * @param options - */ - observe(options: { entryTypes: string[], buffered?: boolean }): void; - } - - export namespace constants { - export const NODE_PERFORMANCE_GC_MAJOR: number; - export const NODE_PERFORMANCE_GC_MINOR: number; - export const NODE_PERFORMANCE_GC_INCREMENTAL: number; - export const NODE_PERFORMANCE_GC_WEAKCB: number; - } - - const performance: Performance; -} diff --git a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/inspector.d.ts b/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/inspector.d.ts deleted file mode 100644 index 7088455c..00000000 --- a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/inspector.d.ts +++ /dev/null @@ -1,2530 +0,0 @@ -// Type definitions for inspector - -// These definitions are auto-generated. -// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 -// for more information. - -/** - * The inspector module provides an API for interacting with the V8 inspector. - */ -declare module "inspector" { - import { EventEmitter } from 'events'; - - export interface InspectorNotification { - method: string; - params: T; - } - - export namespace Schema { - /** - * Description of the protocol domain. - */ - export interface Domain { - /** - * Domain name. - */ - name: string; - /** - * Domain version. - */ - version: string; - } - - export interface GetDomainsReturnType { - /** - * List of supported domains. - */ - domains: Schema.Domain[]; - } - } - - export namespace Runtime { - /** - * Unique script identifier. - */ - export type ScriptId = string; - - /** - * Unique object identifier. - */ - export type RemoteObjectId = string; - - /** - * Primitive value which cannot be JSON-stringified. - */ - export type UnserializableValue = string; - - /** - * Mirror object referencing original JavaScript object. - */ - export interface RemoteObject { - /** - * Object type. - */ - type: string; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string; - /** - * Object class (constructor) name. Specified for object type values only. - */ - className?: string; - /** - * Remote object value in case of primitive values or JSON values (if it was requested). - */ - value?: any; - /** - * Primitive value which can not be JSON-stringified does not have value, but gets this property. - */ - unserializableValue?: Runtime.UnserializableValue; - /** - * String representation of the object. - */ - description?: string; - /** - * Unique object identifier (for non-primitive values). - */ - objectId?: Runtime.RemoteObjectId; - /** - * Preview containing abbreviated property values. Specified for object type values only. - * @experimental - */ - preview?: Runtime.ObjectPreview; - /** - * @experimental - */ - customPreview?: Runtime.CustomPreview; - } - - /** - * @experimental - */ - export interface CustomPreview { - header: string; - hasBody: boolean; - formatterObjectId: Runtime.RemoteObjectId; - bindRemoteObjectFunctionId: Runtime.RemoteObjectId; - configObjectId?: Runtime.RemoteObjectId; - } - - /** - * Object containing abbreviated remote object value. - * @experimental - */ - export interface ObjectPreview { - /** - * Object type. - */ - type: string; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string; - /** - * String representation of the object. - */ - description?: string; - /** - * True iff some of the properties or entries of the original object did not fit. - */ - overflow: boolean; - /** - * List of the properties. - */ - properties: Runtime.PropertyPreview[]; - /** - * List of the entries. Specified for map and set subtype values only. - */ - entries?: Runtime.EntryPreview[]; - } - - /** - * @experimental - */ - export interface PropertyPreview { - /** - * Property name. - */ - name: string; - /** - * Object type. Accessor means that the property itself is an accessor property. - */ - type: string; - /** - * User-friendly property value string. - */ - value?: string; - /** - * Nested value preview. - */ - valuePreview?: Runtime.ObjectPreview; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string; - } - - /** - * @experimental - */ - export interface EntryPreview { - /** - * Preview of the key. Specified for map-like collection entries. - */ - key?: Runtime.ObjectPreview; - /** - * Preview of the value. - */ - value: Runtime.ObjectPreview; - } - - /** - * Object property descriptor. - */ - export interface PropertyDescriptor { - /** - * Property name or symbol description. - */ - name: string; - /** - * The value associated with the property. - */ - value?: Runtime.RemoteObject; - /** - * True if the value associated with the property may be changed (data descriptors only). - */ - writable?: boolean; - /** - * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). - */ - get?: Runtime.RemoteObject; - /** - * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). - */ - set?: Runtime.RemoteObject; - /** - * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - */ - configurable: boolean; - /** - * True if this property shows up during enumeration of the properties on the corresponding object. - */ - enumerable: boolean; - /** - * True if the result was thrown during the evaluation. - */ - wasThrown?: boolean; - /** - * True if the property is owned for the object. - */ - isOwn?: boolean; - /** - * Property symbol object, if the property is of the symbol type. - */ - symbol?: Runtime.RemoteObject; - } - - /** - * Object internal property descriptor. This property isn't normally visible in JavaScript code. - */ - export interface InternalPropertyDescriptor { - /** - * Conventional property name. - */ - name: string; - /** - * The value associated with the property. - */ - value?: Runtime.RemoteObject; - } - - /** - * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. - */ - export interface CallArgument { - /** - * Primitive value or serializable javascript object. - */ - value?: any; - /** - * Primitive value which can not be JSON-stringified. - */ - unserializableValue?: Runtime.UnserializableValue; - /** - * Remote object handle. - */ - objectId?: Runtime.RemoteObjectId; - } - - /** - * Id of an execution context. - */ - export type ExecutionContextId = number; - - /** - * Description of an isolated world. - */ - export interface ExecutionContextDescription { - /** - * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. - */ - id: Runtime.ExecutionContextId; - /** - * Execution context origin. - */ - origin: string; - /** - * Human readable name describing given context. - */ - name: string; - /** - * Embedder-specific auxiliary data. - */ - auxData?: {}; - } - - /** - * Detailed information about exception (or error) that was thrown during script compilation or execution. - */ - export interface ExceptionDetails { - /** - * Exception id. - */ - exceptionId: number; - /** - * Exception text, which should be used together with exception object when available. - */ - text: string; - /** - * Line number of the exception location (0-based). - */ - lineNumber: number; - /** - * Column number of the exception location (0-based). - */ - columnNumber: number; - /** - * Script ID of the exception location. - */ - scriptId?: Runtime.ScriptId; - /** - * URL of the exception location, to be used when the script was not reported. - */ - url?: string; - /** - * JavaScript stack trace if available. - */ - stackTrace?: Runtime.StackTrace; - /** - * Exception object if available. - */ - exception?: Runtime.RemoteObject; - /** - * Identifier of the context where exception happened. - */ - executionContextId?: Runtime.ExecutionContextId; - } - - /** - * Number of milliseconds since epoch. - */ - export type Timestamp = number; - - /** - * Stack entry for runtime errors and assertions. - */ - export interface CallFrame { - /** - * JavaScript function name. - */ - functionName: string; - /** - * JavaScript script id. - */ - scriptId: Runtime.ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * JavaScript script line number (0-based). - */ - lineNumber: number; - /** - * JavaScript script column number (0-based). - */ - columnNumber: number; - } - - /** - * Call frames for assertions or error messages. - */ - export interface StackTrace { - /** - * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. - */ - description?: string; - /** - * JavaScript function name. - */ - callFrames: Runtime.CallFrame[]; - /** - * Asynchronous JavaScript stack trace that preceded this stack, if available. - */ - parent?: Runtime.StackTrace; - /** - * Creation frame of the Promise which produced the next synchronous trace when resolved, if available. - * @experimental - */ - promiseCreationFrame?: Runtime.CallFrame; - } - - export interface EvaluateParameterType { - /** - * Expression to evaluate. - */ - expression: string; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string; - /** - * Determines whether Command Line API should be available during the evaluation. - */ - includeCommandLineAPI?: boolean; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - contextId?: Runtime.ExecutionContextId; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean; - /** - * Whether execution should be treated as initiated by user in the UI. - * @experimental - */ - userGesture?: boolean; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean; - } - - export interface AwaitPromiseParameterType { - /** - * Identifier of the promise. - */ - promiseObjectId: Runtime.RemoteObjectId; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - */ - generatePreview?: boolean; - } - - export interface CallFunctionOnParameterType { - /** - * Identifier of the object to call function on. - */ - objectId: Runtime.RemoteObjectId; - /** - * Declaration of the function to call. - */ - functionDeclaration: string; - /** - * Call arguments. All call arguments must belong to the same JavaScript world as the target object. - */ - arguments?: Runtime.CallArgument[]; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Whether the result is expected to be a JSON object which should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean; - /** - * Whether execution should be treated as initiated by user in the UI. - * @experimental - */ - userGesture?: boolean; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean; - } - - export interface GetPropertiesParameterType { - /** - * Identifier of the object to return properties for. - */ - objectId: Runtime.RemoteObjectId; - /** - * If true, returns properties belonging only to the element itself, not to its prototype chain. - */ - ownProperties?: boolean; - /** - * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. - * @experimental - */ - accessorPropertiesOnly?: boolean; - /** - * Whether preview should be generated for the results. - * @experimental - */ - generatePreview?: boolean; - } - - export interface ReleaseObjectParameterType { - /** - * Identifier of the object to release. - */ - objectId: Runtime.RemoteObjectId; - } - - export interface ReleaseObjectGroupParameterType { - /** - * Symbolic object group name. - */ - objectGroup: string; - } - - export interface SetCustomObjectFormatterEnabledParameterType { - enabled: boolean; - } - - export interface CompileScriptParameterType { - /** - * Expression to compile. - */ - expression: string; - /** - * Source url to be set for the script. - */ - sourceURL: string; - /** - * Specifies whether the compiled script should be persisted. - */ - persistScript: boolean; - /** - * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - executionContextId?: Runtime.ExecutionContextId; - } - - export interface RunScriptParameterType { - /** - * Id of the script to run. - */ - scriptId: Runtime.ScriptId; - /** - * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - executionContextId?: Runtime.ExecutionContextId; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Determines whether Command Line API should be available during the evaluation. - */ - includeCommandLineAPI?: boolean; - /** - * Whether the result is expected to be a JSON object which should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - */ - generatePreview?: boolean; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean; - } - - export interface QueryObjectsParameterType { - /** - * Identifier of the prototype to return objects for. - */ - prototypeObjectId: Runtime.RemoteObjectId; - } - - export interface GlobalLexicalScopeNamesParameterType { - /** - * Specifies in which execution context to lookup global scope variables. - */ - executionContextId?: Runtime.ExecutionContextId; - } - - export interface EvaluateReturnType { - /** - * Evaluation result. - */ - result: Runtime.RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface AwaitPromiseReturnType { - /** - * Promise result. Will contain rejected value if promise was rejected. - */ - result: Runtime.RemoteObject; - /** - * Exception details if stack strace is available. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface CallFunctionOnReturnType { - /** - * Call result. - */ - result: Runtime.RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface GetPropertiesReturnType { - /** - * Object properties. - */ - result: Runtime.PropertyDescriptor[]; - /** - * Internal object properties (only of the element itself). - */ - internalProperties?: Runtime.InternalPropertyDescriptor[]; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface CompileScriptReturnType { - /** - * Id of the script. - */ - scriptId?: Runtime.ScriptId; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface RunScriptReturnType { - /** - * Run result. - */ - result: Runtime.RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface QueryObjectsReturnType { - /** - * Array with objects. - */ - objects: Runtime.RemoteObject; - } - - export interface GlobalLexicalScopeNamesReturnType { - names: string[]; - } - - export interface ExecutionContextCreatedEventDataType { - /** - * A newly created execution context. - */ - context: Runtime.ExecutionContextDescription; - } - - export interface ExecutionContextDestroyedEventDataType { - /** - * Id of the destroyed context - */ - executionContextId: Runtime.ExecutionContextId; - } - - export interface ExceptionThrownEventDataType { - /** - * Timestamp of the exception. - */ - timestamp: Runtime.Timestamp; - exceptionDetails: Runtime.ExceptionDetails; - } - - export interface ExceptionRevokedEventDataType { - /** - * Reason describing why exception was revoked. - */ - reason: string; - /** - * The id of revoked exception, as reported in exceptionUnhandled. - */ - exceptionId: number; - } - - export interface ConsoleAPICalledEventDataType { - /** - * Type of the call. - */ - type: string; - /** - * Call arguments. - */ - args: Runtime.RemoteObject[]; - /** - * Identifier of the context where the call was made. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Call timestamp. - */ - timestamp: Runtime.Timestamp; - /** - * Stack trace captured when the call was made. - */ - stackTrace?: Runtime.StackTrace; - /** - * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. - * @experimental - */ - context?: string; - } - - export interface InspectRequestedEventDataType { - object: Runtime.RemoteObject; - hints: {}; - } - } - - export namespace Debugger { - /** - * Breakpoint identifier. - */ - export type BreakpointId = string; - - /** - * Call frame identifier. - */ - export type CallFrameId = string; - - /** - * Location in the source code. - */ - export interface Location { - /** - * Script identifier as reported in the Debugger.scriptParsed. - */ - scriptId: Runtime.ScriptId; - /** - * Line number in the script (0-based). - */ - lineNumber: number; - /** - * Column number in the script (0-based). - */ - columnNumber?: number; - } - - /** - * Location in the source code. - * @experimental - */ - export interface ScriptPosition { - lineNumber: number; - columnNumber: number; - } - - /** - * JavaScript call frame. Array of call frames form the call stack. - */ - export interface CallFrame { - /** - * Call frame identifier. This identifier is only valid while the virtual machine is paused. - */ - callFrameId: Debugger.CallFrameId; - /** - * Name of the JavaScript function called on this call frame. - */ - functionName: string; - /** - * Location in the source code. - * @experimental - */ - functionLocation?: Debugger.Location; - /** - * Location in the source code. - */ - location: Debugger.Location; - /** - * Scope chain for this call frame. - */ - scopeChain: Debugger.Scope[]; - /** - * this object for this call frame. - */ - this: Runtime.RemoteObject; - /** - * The value being returned, if the function is at return point. - */ - returnValue?: Runtime.RemoteObject; - } - - /** - * Scope description. - */ - export interface Scope { - /** - * Scope type. - */ - type: string; - /** - * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. - */ - object: Runtime.RemoteObject; - name?: string; - /** - * Location in the source code where scope starts - */ - startLocation?: Debugger.Location; - /** - * Location in the source code where scope ends - */ - endLocation?: Debugger.Location; - } - - /** - * Search match for resource. - * @experimental - */ - export interface SearchMatch { - /** - * Line number in resource content. - */ - lineNumber: number; - /** - * Line with match content. - */ - lineContent: string; - } - - /** - * @experimental - */ - export interface BreakLocation { - /** - * Script identifier as reported in the Debugger.scriptParsed. - */ - scriptId: Runtime.ScriptId; - /** - * Line number in the script (0-based). - */ - lineNumber: number; - /** - * Column number in the script (0-based). - */ - columnNumber?: number; - type?: string; - } - - export interface SetBreakpointsActiveParameterType { - /** - * New value for breakpoints active state. - */ - active: boolean; - } - - export interface SetSkipAllPausesParameterType { - /** - * New value for skip pauses state. - */ - skip: boolean; - } - - export interface SetBreakpointByUrlParameterType { - /** - * Line number to set breakpoint at. - */ - lineNumber: number; - /** - * URL of the resources to set breakpoint on. - */ - url?: string; - /** - * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. - */ - urlRegex?: string; - /** - * Offset in the line to set breakpoint at. - */ - columnNumber?: number; - /** - * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. - */ - condition?: string; - } - - export interface SetBreakpointParameterType { - /** - * Location to set breakpoint in. - */ - location: Debugger.Location; - /** - * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. - */ - condition?: string; - } - - export interface RemoveBreakpointParameterType { - breakpointId: Debugger.BreakpointId; - } - - export interface GetPossibleBreakpointsParameterType { - /** - * Start of range to search possible breakpoint locations in. - */ - start: Debugger.Location; - /** - * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. - */ - end?: Debugger.Location; - /** - * Only consider locations which are in the same (non-nested) function as start. - */ - restrictToFunction?: boolean; - } - - export interface ContinueToLocationParameterType { - /** - * Location to continue to. - */ - location: Debugger.Location; - /** - * @experimental - */ - targetCallFrames?: string; - } - - export interface SearchInContentParameterType { - /** - * Id of the script to search in. - */ - scriptId: Runtime.ScriptId; - /** - * String to search for. - */ - query: string; - /** - * If true, search is case sensitive. - */ - caseSensitive?: boolean; - /** - * If true, treats string parameter as regex. - */ - isRegex?: boolean; - } - - export interface SetScriptSourceParameterType { - /** - * Id of the script to edit. - */ - scriptId: Runtime.ScriptId; - /** - * New content of the script. - */ - scriptSource: string; - /** - * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. - */ - dryRun?: boolean; - } - - export interface RestartFrameParameterType { - /** - * Call frame identifier to evaluate on. - */ - callFrameId: Debugger.CallFrameId; - } - - export interface GetScriptSourceParameterType { - /** - * Id of the script to get source for. - */ - scriptId: Runtime.ScriptId; - } - - export interface SetPauseOnExceptionsParameterType { - /** - * Pause on exceptions mode. - */ - state: string; - } - - export interface EvaluateOnCallFrameParameterType { - /** - * Call frame identifier to evaluate on. - */ - callFrameId: Debugger.CallFrameId; - /** - * Expression to evaluate. - */ - expression: string; - /** - * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). - */ - objectGroup?: string; - /** - * Specifies whether command line API should be available to the evaluated expression, defaults to false. - */ - includeCommandLineAPI?: boolean; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean; - /** - * Whether to throw an exception if side effect cannot be ruled out during evaluation. - * @experimental - */ - throwOnSideEffect?: boolean; - } - - export interface SetVariableValueParameterType { - /** - * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. - */ - scopeNumber: number; - /** - * Variable name. - */ - variableName: string; - /** - * New variable value. - */ - newValue: Runtime.CallArgument; - /** - * Id of callframe that holds variable. - */ - callFrameId: Debugger.CallFrameId; - } - - export interface SetAsyncCallStackDepthParameterType { - /** - * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). - */ - maxDepth: number; - } - - export interface SetBlackboxPatternsParameterType { - /** - * Array of regexps that will be used to check script url for blackbox state. - */ - patterns: string[]; - } - - export interface SetBlackboxedRangesParameterType { - /** - * Id of the script. - */ - scriptId: Runtime.ScriptId; - positions: Debugger.ScriptPosition[]; - } - - export interface SetBreakpointByUrlReturnType { - /** - * Id of the created breakpoint for further reference. - */ - breakpointId: Debugger.BreakpointId; - /** - * List of the locations this breakpoint resolved into upon addition. - */ - locations: Debugger.Location[]; - } - - export interface SetBreakpointReturnType { - /** - * Id of the created breakpoint for further reference. - */ - breakpointId: Debugger.BreakpointId; - /** - * Location this breakpoint resolved into. - */ - actualLocation: Debugger.Location; - } - - export interface GetPossibleBreakpointsReturnType { - /** - * List of the possible breakpoint locations. - */ - locations: Debugger.BreakLocation[]; - } - - export interface SearchInContentReturnType { - /** - * List of search matches. - */ - result: Debugger.SearchMatch[]; - } - - export interface SetScriptSourceReturnType { - /** - * New stack trace in case editing has happened while VM was stopped. - */ - callFrames?: Debugger.CallFrame[]; - /** - * Whether current call stack was modified after applying the changes. - */ - stackChanged?: boolean; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace; - /** - * Exception details if any. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface RestartFrameReturnType { - /** - * New stack trace. - */ - callFrames: Debugger.CallFrame[]; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace; - } - - export interface GetScriptSourceReturnType { - /** - * Script source. - */ - scriptSource: string; - } - - export interface EvaluateOnCallFrameReturnType { - /** - * Object wrapper for the evaluation result. - */ - result: Runtime.RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - export interface ScriptParsedEventDataType { - /** - * Identifier of the script parsed. - */ - scriptId: Runtime.ScriptId; - /** - * URL or name of the script parsed (if any). - */ - url: string; - /** - * Line offset of the script within the resource with given URL (for script tags). - */ - startLine: number; - /** - * Column offset of the script within the resource with given URL. - */ - startColumn: number; - /** - * Last line of the script. - */ - endLine: number; - /** - * Length of the last line of the script. - */ - endColumn: number; - /** - * Specifies script creation context. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Content hash of the script. - */ - hash: string; - /** - * Embedder-specific auxiliary data. - */ - executionContextAuxData?: {}; - /** - * True, if this script is generated as a result of the live edit operation. - * @experimental - */ - isLiveEdit?: boolean; - /** - * URL of source map associated with script (if any). - */ - sourceMapURL?: string; - /** - * True, if this script has sourceURL. - * @experimental - */ - hasSourceURL?: boolean; - /** - * True, if this script is ES6 module. - * @experimental - */ - isModule?: boolean; - /** - * This script length. - * @experimental - */ - length?: number; - /** - * JavaScript top stack frame of where the script parsed event was triggered if available. - * @experimental - */ - stackTrace?: Runtime.StackTrace; - } - - export interface ScriptFailedToParseEventDataType { - /** - * Identifier of the script parsed. - */ - scriptId: Runtime.ScriptId; - /** - * URL or name of the script parsed (if any). - */ - url: string; - /** - * Line offset of the script within the resource with given URL (for script tags). - */ - startLine: number; - /** - * Column offset of the script within the resource with given URL. - */ - startColumn: number; - /** - * Last line of the script. - */ - endLine: number; - /** - * Length of the last line of the script. - */ - endColumn: number; - /** - * Specifies script creation context. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Content hash of the script. - */ - hash: string; - /** - * Embedder-specific auxiliary data. - */ - executionContextAuxData?: {}; - /** - * URL of source map associated with script (if any). - */ - sourceMapURL?: string; - /** - * True, if this script has sourceURL. - * @experimental - */ - hasSourceURL?: boolean; - /** - * True, if this script is ES6 module. - * @experimental - */ - isModule?: boolean; - /** - * This script length. - * @experimental - */ - length?: number; - /** - * JavaScript top stack frame of where the script parsed event was triggered if available. - * @experimental - */ - stackTrace?: Runtime.StackTrace; - } - - export interface BreakpointResolvedEventDataType { - /** - * Breakpoint unique identifier. - */ - breakpointId: Debugger.BreakpointId; - /** - * Actual breakpoint location. - */ - location: Debugger.Location; - } - - export interface PausedEventDataType { - /** - * Call stack the virtual machine stopped on. - */ - callFrames: Debugger.CallFrame[]; - /** - * Pause reason. - */ - reason: string; - /** - * Object containing break-specific auxiliary properties. - */ - data?: {}; - /** - * Hit breakpoints IDs - */ - hitBreakpoints?: string[]; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace; - } - } - - export namespace Console { - /** - * Console message. - */ - export interface ConsoleMessage { - /** - * Message source. - */ - source: string; - /** - * Message severity. - */ - level: string; - /** - * Message text. - */ - text: string; - /** - * URL of the message origin. - */ - url?: string; - /** - * Line number in the resource that generated this message (1-based). - */ - line?: number; - /** - * Column number in the resource that generated this message (1-based). - */ - column?: number; - } - - export interface MessageAddedEventDataType { - /** - * Console message that has been added. - */ - message: Console.ConsoleMessage; - } - } - - export namespace Profiler { - /** - * Profile node. Holds callsite information, execution statistics and child nodes. - */ - export interface ProfileNode { - /** - * Unique id of the node. - */ - id: number; - /** - * Function location. - */ - callFrame: Runtime.CallFrame; - /** - * Number of samples where this node was on top of the call stack. - * @experimental - */ - hitCount?: number; - /** - * Child node ids. - */ - children?: number[]; - /** - * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. - */ - deoptReason?: string; - /** - * An array of source position ticks. - * @experimental - */ - positionTicks?: Profiler.PositionTickInfo[]; - } - - /** - * Profile. - */ - export interface Profile { - /** - * The list of profile nodes. First item is the root node. - */ - nodes: Profiler.ProfileNode[]; - /** - * Profiling start timestamp in microseconds. - */ - startTime: number; - /** - * Profiling end timestamp in microseconds. - */ - endTime: number; - /** - * Ids of samples top nodes. - */ - samples?: number[]; - /** - * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. - */ - timeDeltas?: number[]; - } - - /** - * Specifies a number of samples attributed to a certain source position. - * @experimental - */ - export interface PositionTickInfo { - /** - * Source line number (1-based). - */ - line: number; - /** - * Number of samples attributed to the source line. - */ - ticks: number; - } - - /** - * Coverage data for a source range. - * @experimental - */ - export interface CoverageRange { - /** - * JavaScript script source offset for the range start. - */ - startOffset: number; - /** - * JavaScript script source offset for the range end. - */ - endOffset: number; - /** - * Collected execution count of the source range. - */ - count: number; - } - - /** - * Coverage data for a JavaScript function. - * @experimental - */ - export interface FunctionCoverage { - /** - * JavaScript function name. - */ - functionName: string; - /** - * Source ranges inside the function with coverage data. - */ - ranges: Profiler.CoverageRange[]; - /** - * Whether coverage data for this function has block granularity. - */ - isBlockCoverage: boolean; - } - - /** - * Coverage data for a JavaScript script. - * @experimental - */ - export interface ScriptCoverage { - /** - * JavaScript script id. - */ - scriptId: Runtime.ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Functions contained in the script that has coverage data. - */ - functions: Profiler.FunctionCoverage[]; - } - - export interface SetSamplingIntervalParameterType { - /** - * New sampling interval in microseconds. - */ - interval: number; - } - - export interface StartPreciseCoverageParameterType { - /** - * Collect accurate call counts beyond simple 'covered' or 'not covered'. - */ - callCount?: boolean; - /** - * Collect block-based coverage. - */ - detailed?: boolean; - } - - export interface StopReturnType { - /** - * Recorded profile. - */ - profile: Profiler.Profile; - } - - export interface TakePreciseCoverageReturnType { - /** - * Coverage data for the current isolate. - */ - result: Profiler.ScriptCoverage[]; - } - - export interface GetBestEffortCoverageReturnType { - /** - * Coverage data for the current isolate. - */ - result: Profiler.ScriptCoverage[]; - } - - export interface ConsoleProfileStartedEventDataType { - id: string; - /** - * Location of console.profile(). - */ - location: Debugger.Location; - /** - * Profile title passed as an argument to console.profile(). - */ - title?: string; - } - - export interface ConsoleProfileFinishedEventDataType { - id: string; - /** - * Location of console.profileEnd(). - */ - location: Debugger.Location; - profile: Profiler.Profile; - /** - * Profile title passed as an argument to console.profile(). - */ - title?: string; - } - } - - export namespace HeapProfiler { - /** - * Heap snapshot object id. - */ - export type HeapSnapshotObjectId = string; - - /** - * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. - */ - export interface SamplingHeapProfileNode { - /** - * Function location. - */ - callFrame: Runtime.CallFrame; - /** - * Allocations size in bytes for the node excluding children. - */ - selfSize: number; - /** - * Child nodes. - */ - children: HeapProfiler.SamplingHeapProfileNode[]; - } - - /** - * Profile. - */ - export interface SamplingHeapProfile { - head: HeapProfiler.SamplingHeapProfileNode; - } - - export interface StartTrackingHeapObjectsParameterType { - trackAllocations?: boolean; - } - - export interface StopTrackingHeapObjectsParameterType { - /** - * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. - */ - reportProgress?: boolean; - } - - export interface TakeHeapSnapshotParameterType { - /** - * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. - */ - reportProgress?: boolean; - } - - export interface GetObjectByHeapObjectIdParameterType { - objectId: HeapProfiler.HeapSnapshotObjectId; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string; - } - - export interface AddInspectedHeapObjectParameterType { - /** - * Heap snapshot object id to be accessible by means of $x command line API. - */ - heapObjectId: HeapProfiler.HeapSnapshotObjectId; - } - - export interface GetHeapObjectIdParameterType { - /** - * Identifier of the object to get heap object id for. - */ - objectId: Runtime.RemoteObjectId; - } - - export interface StartSamplingParameterType { - /** - * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. - */ - samplingInterval?: number; - } - - export interface GetObjectByHeapObjectIdReturnType { - /** - * Evaluation result. - */ - result: Runtime.RemoteObject; - } - - export interface GetHeapObjectIdReturnType { - /** - * Id of the heap snapshot object corresponding to the passed remote object id. - */ - heapSnapshotObjectId: HeapProfiler.HeapSnapshotObjectId; - } - - export interface StopSamplingReturnType { - /** - * Recorded sampling heap profile. - */ - profile: HeapProfiler.SamplingHeapProfile; - } - - export interface AddHeapSnapshotChunkEventDataType { - chunk: string; - } - - export interface ReportHeapSnapshotProgressEventDataType { - done: number; - total: number; - finished?: boolean; - } - - export interface LastSeenObjectIdEventDataType { - lastSeenObjectId: number; - timestamp: number; - } - - export interface HeapStatsUpdateEventDataType { - /** - * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. - */ - statsUpdate: number[]; - } - } - - /** - * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. - */ - export class Session extends EventEmitter { - /** - * Create a new instance of the inspector.Session class. The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. - */ - constructor(); - - /** - * Connects a session to the inspector back-end. An exception will be thrown if there is already a connected session established either through the API or by a front-end connected to the Inspector WebSocket port. - */ - connect(): void; - - /** - * Immediately close the session. All pending message callbacks will be called with an error. session.connect() will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. - */ - disconnect(): void; - - /** - * Posts a message to the inspector back-end. callback will be notified when a response is received. callback is a function that accepts two optional arguments - error and message-specific result. - */ - post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; - post(method: string, callback?: (err: Error | null, params?: {}) => void): void; - - /** - * Returns supported domains. - */ - post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; - /** - * Evaluates expression on global object. - */ - post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; - post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; - - /** - * Add handler to promise with given promise object id. - */ - post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; - post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; - - /** - * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. - */ - post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; - post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; - - /** - * Returns properties of a given object. Object group of the result is inherited from the target object. - */ - post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; - post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; - - /** - * Releases remote object with given id. - */ - post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; - post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; - - /** - * Releases all remote objects that belong to a given group. - */ - post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; - post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; - - /** - * Tells inspected instance to run if it was waiting for debugger to attach. - */ - post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; - - /** - * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. - */ - post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; - - /** - * Disables reporting of execution contexts creation. - */ - post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; - - /** - * Discards collected exceptions and console API calls. - */ - post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; - - /** - * @experimental - */ - post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; - post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; - - /** - * Compiles expression. - */ - post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; - post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; - - /** - * Runs script with given id in a given context. - */ - post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; - post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; - - /** - * @experimental - */ - post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; - post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; - - /** - * Returns all let, const and class variables from global scope. - * @experimental - */ - post(method: "Runtime.globalLexicalScopeNames", params?: Runtime.GlobalLexicalScopeNamesParameterType, callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; - post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; - /** - * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. - */ - post(method: "Debugger.enable", callback?: (err: Error | null) => void): void; - - /** - * Disables debugger for given page. - */ - post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; - - /** - * Activates / deactivates all breakpoints on the page. - */ - post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; - - /** - * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). - */ - post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; - - /** - * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. - */ - post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; - post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; - - /** - * Sets JavaScript breakpoint at a given location. - */ - post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; - post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; - - /** - * Removes JavaScript breakpoint. - */ - post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; - - /** - * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. - * @experimental - */ - post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType, callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; - post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; - - /** - * Continues execution until specific location is reached. - */ - post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; - - /** - * Steps over the statement. - */ - post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; - - /** - * Steps into the function call. - */ - post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; - - /** - * Steps out of the function call. - */ - post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; - - /** - * Stops on the next JavaScript statement. - */ - post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; - - /** - * Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. - * @experimental - */ - post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; - - /** - * Resumes JavaScript execution. - */ - post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; - - /** - * Searches for given string in script content. - * @experimental - */ - post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; - post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; - - /** - * Edits JavaScript source live. - */ - post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; - post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; - - /** - * Restarts particular call frame from the beginning. - */ - post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; - post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; - - /** - * Returns source for the script with given id. - */ - post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; - post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; - - /** - * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. - */ - post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; - - /** - * Evaluates expression on a given call frame. - */ - post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; - post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; - - /** - * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. - */ - post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; - - /** - * Enables or disables async call stacks tracking. - */ - post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; - - /** - * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. - * @experimental - */ - post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; - - /** - * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. - * @experimental - */ - post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; - /** - * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. - */ - post(method: "Console.enable", callback?: (err: Error | null) => void): void; - - /** - * Disables console domain, prevents further console messages from being reported to the client. - */ - post(method: "Console.disable", callback?: (err: Error | null) => void): void; - - /** - * Does nothing. - */ - post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; - post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; - - /** - * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. - */ - post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; - post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.start", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; - - /** - * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. - * @experimental - */ - post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; - post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; - - /** - * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. - * @experimental - */ - post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; - - /** - * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. - * @experimental - */ - post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; - - /** - * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. - * @experimental - */ - post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; - post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; - post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; - - /** - * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). - */ - post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; - post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; - - post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; - - // Events - - addListener(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - addListener(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; - addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; - emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; - emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; - emit(event: "Runtime.executionContextsCleared"): boolean; - emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; - emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; - emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; - emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; - emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; - emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; - emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; - emit(event: "Debugger.paused", message: InspectorNotification): boolean; - emit(event: "Debugger.resumed"): boolean; - emit(event: "Console.messageAdded", message: InspectorNotification): boolean; - emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; - emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.resetProfiles"): boolean; - emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - on(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - on(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - on(event: "HeapProfiler.resetProfiles", listener: () => void): this; - on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - once(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - once(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - once(event: "HeapProfiler.resetProfiles", listener: () => void): this; - once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - prependListener(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; - prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - prependOnceListener(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; - prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - } - - // Top Level API - - /** - * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. - * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. - * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. - * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. - * @param wait Block until a client has connected. Optional, defaults to false. - */ - export function open(port?: number, host?: string, wait?: boolean): void; - - /** - * Deactivate the inspector. Blocks until there are no active connections. - */ - export function close(): void; - - /** - * Return the URL of the active inspector, or undefined if there is none. - */ - export function url(): string; -} diff --git a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/package.json b/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/package.json deleted file mode 100644 index 82f28f4b..00000000 --- a/functions/node_modules/@grpc/proto-loader/node_modules/@types/node/package.json +++ /dev/null @@ -1,152 +0,0 @@ -{ - "_from": "@types/node@^9.4.6", - "_id": "@types/node@9.6.41", - "_inBundle": false, - "_integrity": "sha512-sPZWEbFMz6qAy9SLY7jh5cgepmsiwqUUHjvEm8lpU6kug2hmmcyuTnwhoGw/GWpI5Npue4EqvsiQQI0eWjW/ZA==", - "_location": "/@grpc/proto-loader/@types/node", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@types/node@^9.4.6", - "name": "@types/node", - "escapedName": "@types%2fnode", - "scope": "@types", - "rawSpec": "^9.4.6", - "saveSpec": null, - "fetchSpec": "^9.4.6" - }, - "_requiredBy": [ - "/@grpc/proto-loader" - ], - "_resolved": "https://registry.npmjs.org/@types/node/-/node-9.6.41.tgz", - "_shasum": "e57c3152eb2e7ec748c733cebd0c095b437c5d37", - "_spec": "@types/node@^9.4.6", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\@grpc\\proto-loader", - "bugs": { - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Microsoft TypeScript", - "url": "https://github.com/Microsoft" - }, - { - "name": "DefinitelyTyped", - "url": "https://github.com/DefinitelyTyped" - }, - { - "name": "Parambir Singh", - "url": "https://github.com/parambirs" - }, - { - "name": "Christian Vaagland Tellnes", - "url": "https://github.com/tellnes" - }, - { - "name": "Wilco Bakker", - "url": "https://github.com/WilcoBakker" - }, - { - "name": "Nicolas Voigt", - "url": "https://github.com/octo-sniffle" - }, - { - "name": "Chigozirim C.", - "url": "https://github.com/smac89" - }, - { - "name": "Flarna", - "url": "https://github.com/Flarna" - }, - { - "name": "Mariusz Wiktorczyk", - "url": "https://github.com/mwiktorczyk" - }, - { - "name": "wwwy3y3", - "url": "https://github.com/wwwy3y3" - }, - { - "name": "Deividas Bakanas", - "url": "https://github.com/DeividasBakanas" - }, - { - "name": "Kelvin Jin", - "url": "https://github.com/kjin" - }, - { - "name": "Alvis HT Tang", - "url": "https://github.com/alvis" - }, - { - "name": "Sebastian Silbermann", - "url": "https://github.com/eps1lon" - }, - { - "name": "Hannes Magnusson", - "url": "https://github.com/Hannes-Magnusson-CK" - }, - { - "name": "Alberto Schiabel", - "url": "https://github.com/jkomyno" - }, - { - "name": "Klaus Meinhardt", - "url": "https://github.com/ajafff" - }, - { - "name": "Huw", - "url": "https://github.com/hoo29" - }, - { - "name": "Nicolas Even", - "url": "https://github.com/n-e" - }, - { - "name": "Bruno Scheufler", - "url": "https://github.com/brunoscheufler" - }, - { - "name": "Mohsen Azimi", - "url": "https://github.com/mohsen1" - }, - { - "name": "Hoàng Văn Khải", - "url": "https://github.com/KSXGitHub" - }, - { - "name": "Alexander T.", - "url": "https://github.com/a-tarasyuk" - }, - { - "name": "Lishude", - "url": "https://github.com/islishude" - }, - { - "name": "Andrew Makarov", - "url": "https://github.com/r3nya" - }, - { - "name": "Eugene Y. Q. Shen", - "url": "https://github.com/eyqs" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "TypeScript definitions for Node.js", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", - "license": "MIT", - "main": "", - "name": "@types/node", - "repository": { - "type": "git", - "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" - }, - "scripts": {}, - "typeScriptVersion": "2.0", - "types": "index", - "typesPublisherContentHash": "159c257e6a57c0dd5acf840c15ba44d9373d0ee24e030485ba68ec05a145a907", - "version": "9.6.41" -} diff --git a/functions/node_modules/@grpc/proto-loader/package.json b/functions/node_modules/@grpc/proto-loader/package.json deleted file mode 100644 index 7b1598a0..00000000 --- a/functions/node_modules/@grpc/proto-loader/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_from": "@grpc/proto-loader@^0.3.0", - "_id": "@grpc/proto-loader@0.3.0", - "_inBundle": false, - "_integrity": "sha512-9b8S/V+3W4Gv7G/JKSZ48zApgyYbfIR7mAC9XNnaSWme3zj57MIESu0ELzm9j5oxNIpFG8DgO00iJMIUZ5luqw==", - "_location": "/@grpc/proto-loader", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@grpc/proto-loader@^0.3.0", - "name": "@grpc/proto-loader", - "escapedName": "@grpc%2fproto-loader", - "scope": "@grpc", - "rawSpec": "^0.3.0", - "saveSpec": null, - "fetchSpec": "^0.3.0" - }, - "_requiredBy": [ - "/google-gax" - ], - "_resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.3.0.tgz", - "_shasum": "c127d3859bff895f220453612ba04b923af0c584", - "_spec": "@grpc/proto-loader@^0.3.0", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\google-gax", - "author": { - "name": "Google Inc." - }, - "bugs": { - "url": "https://github.com/grpc/grpc-node/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Michael Lumish", - "email": "mlumish@google.com" - } - ], - "dependencies": { - "@types/lodash": "^4.14.104", - "@types/node": "^9.4.6", - "lodash": "^4.17.5", - "protobufjs": "^6.8.6" - }, - "deprecated": false, - "description": "gRPC utility library for loading .proto files", - "devDependencies": { - "clang-format": "^1.2.2", - "gts": "^0.5.3", - "typescript": "~2.7.2" - }, - "engines": { - "node": ">=6" - }, - "files": [ - "build/src/*.d.ts", - "build/src/*.js" - ], - "homepage": "https://grpc.io/", - "license": "Apache-2.0", - "main": "build/src/index.js", - "name": "@grpc/proto-loader", - "repository": { - "type": "git", - "url": "git+https://github.com/grpc/grpc-node.git" - }, - "scripts": { - "build": "npm run compile", - "check": "gts check", - "clean": "gts clean", - "compile": "tsc -p .", - "fix": "gts fix", - "format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts", - "lint": "tslint -c node_modules/google-ts-style/tslint.json -p . -t codeFrame --type-check", - "posttest": "npm run check", - "prepare": "npm run compile", - "pretest": "npm run compile", - "test": "gulp test" - }, - "typings": "build/src/index.d.ts", - "version": "0.3.0" -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/CHANGELOG.md b/functions/node_modules/@mrmlnc/readdir-enhanced/CHANGELOG.md deleted file mode 100644 index 6391ab67..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/CHANGELOG.md +++ /dev/null @@ -1,49 +0,0 @@ -# Change Log -All notable changes will be documented in this file. -`readdir-enhanced` adheres to [Semantic Versioning](http://semver.org/). - - -## [v2.2.0](https://github.com/BigstickCarpet/readdir-enhanced/tree/v2.2.0) (2018-01-09) - -- Refactored the codebase to use ES6 syntax (Node v4.x compatible) - -- You can now provide [your own implementation](https://github.com/BigstickCarpet/readdir-enhanced#custom-fs-methods) for the [filesystem module](https://nodejs.org/api/fs.html) that's used by `readdir-enhanced`. Just set the `fs` option to your implementation. Thanks to [@mrmlnc](https://github.com/mrmlnc) for the idea and [the PR](https://github.com/BigstickCarpet/readdir-enhanced/pull/10)! - -- [Better error handling](https://github.com/BigstickCarpet/readdir-enhanced/commit/0d330b68524bafbdeae11566a3e8af1bc3f184bf), especially around user-specified logic, such as `options.deep`, `options.filter`, and `options.fs` - -[Full Changelog](https://github.com/BigstickCarpet/readdir-enhanced/compare/v2.1.0...v2.2.0) - - -## [v2.1.0](https://github.com/BigstickCarpet/readdir-enhanced/tree/v2.1.0) (2017-12-01) - -- The `fs.Stats` objects now include a `depth` property, which indicates the number of subdirectories beneath the base path. Thanks to [@mrmlnc](https://github.com/mrmlnc) for [the PR](https://github.com/BigstickCarpet/readdir-enhanced/pull/8)! - -[Full Changelog](https://github.com/BigstickCarpet/readdir-enhanced/compare/v2.0.0...v2.1.0) - - -## [v2.0.0](https://github.com/BigstickCarpet/readdir-enhanced/tree/v2.0.0) (2017-11-15) - -- Dropped support for Node v0.x, which is no longer actively maintained. Please upgrade to Node 4 or newer. - -[Full Changelog](https://github.com/BigstickCarpet/readdir-enhanced/compare/v1.5.0...v2.0.0) - - -## [v1.5.0](https://github.com/BigstickCarpet/readdir-enhanced/tree/v1.5.0) (2017-04-10) - -The [`deep` option](README.md#deep) can now be set to a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), a [glob pattern](https://github.com/isaacs/node-glob#glob-primer), or a function, which allows you to customize which subdirectories get crawled. Of course, you can also still still set the `deep` option to `true` to crawl _all_ subdirectories, or a number if you just want to limit the recursion depth. - -[Full Changelog](https://github.com/BigstickCarpet/readdir-enhanced/compare/v1.4.0...v1.5.0) - - -## [v1.4.0](https://github.com/BigstickCarpet/readdir-enhanced/tree/v1.4.0) (2016-08-26) - -The [`filter` option](README.md#filter) can now be set to a regular expression or a glob pattern string, which simplifies filtering based on file names. Of course, you can still set the `filter` option to a function if you need to perform more advanced filtering based on the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) of each file. - -[Full Changelog](https://github.com/BigstickCarpet/readdir-enhanced/compare/v1.3.4...v1.4.0) - - -## [v1.3.4](https://github.com/BigstickCarpet/readdir-enhanced/tree/v1.3.4) (2016-08-26) - -As of this release, `readdir-enhanced` is fully tested on all major Node versions (0.x, 4.x, 5.x, 6.x) on [linux](https://travis-ci.org/BigstickCarpet/readdir-enhanced) and [Windows](https://ci.appveyor.com/project/BigstickCarpet/readdir-enhanced/branch/master), with [nearly 100% code coverage](https://coveralls.io/github/BigstickCarpet/readdir-enhanced?branch=master). I do all of my local development and testing on MacOS, so that's covered too. - -[Full Changelog](https://github.com/BigstickCarpet/readdir-enhanced/compare/v1.0.1...v1.3.4) diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/LICENSE b/functions/node_modules/@mrmlnc/readdir-enhanced/LICENSE deleted file mode 100644 index 9ff003fb..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 James Messinger - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -. \ No newline at end of file diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/README.md b/functions/node_modules/@mrmlnc/readdir-enhanced/README.md deleted file mode 100644 index bcf9b26f..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/README.md +++ /dev/null @@ -1,347 +0,0 @@ -Enhanced `fs.readdir()` -======================= - -> :warning: This is «fork» for original `readdir-enhanced` package but with some monkey fixes. - -[![Build Status](https://api.travis-ci.org/BigstickCarpet/readdir-enhanced.svg?branch=master)](https://travis-ci.org/BigstickCarpet/readdir-enhanced) -[![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/bigstickcarpet/readdir-enhanced?svg=true&branch=master&failingText=Windows%20build%20failing&passingText=Windows%20build%20passing)](https://ci.appveyor.com/project/BigstickCarpet/readdir-enhanced/branch/master) - -[![Coverage Status](https://coveralls.io/repos/github/BigstickCarpet/readdir-enhanced/badge.svg?branch=master)](https://coveralls.io/github/BigstickCarpet/readdir-enhanced?branch=master) -[![Codacy Score](https://api.codacy.com/project/badge/Grade/178a817b6c864de7813fef457c0ed5ae)](https://www.codacy.com/public/jamesmessinger/readdir-enhanced) -[![Inline docs](http://inch-ci.org/github/BigstickCarpet/readdir-enhanced.svg?branch=master&style=shields)](http://inch-ci.org/github/BigstickCarpet/readdir-enhanced) -[![Dependencies](https://david-dm.org/BigstickCarpet/readdir-enhanced.svg)](https://david-dm.org/BigstickCarpet/readdir-enhanced) - -[![npm](https://img.shields.io/npm/v/readdir-enhanced.svg?maxAge=43200)](https://www.npmjs.com/package/readdir-enhanced) -[![License](https://img.shields.io/npm/l/readdir-enhanced.svg?maxAge=2592000)](LICENSE) - -`readdir-enhanced` is a [backward-compatible](#backward-compatible) drop-in replacement for [`fs.readdir()`](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback) and [`fs.readdirSync()`](https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options) with tons of extra features ([filtering](#filter), [recursion](#deep), [absolute paths](#basepath), [stats](#stats), and more) as well as additional APIs for Promises, Streams, and EventEmitters. - - -Pick Your API ------------------ -`readdir-enhanced` has multiple APIs, so you can pick whichever one you prefer. There are three main APIs: - -- **Synchronous API**
-aliases: `readdir.sync`, `readdir.readdirSync`
-Blocks the thread until all directory contents are read, and then returns all the results. - -- **Async API**
-aliases: `readdir`, `readdir.async`, `readdir.readdirAsync`
-Reads the starting directory contents asynchronously and buffers all the results until all contents have been read. Supports callback or Promise syntax (see example below). - -- **Streaming API**
-aliases: `readdir.stream`, `readdir.readdirStream`
-The streaming API reads the starting directory asynchronously and returns the results in real-time as they are read. The results can be [piped](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) to other Node.js streams, or you can listen for specific events via the [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) interface. (see example below) - -```javascript -var readdir = require('readdir-enhanced'); -var through2 = require('through2'); - -// Synchronous API -var files = readdir.sync('my/directory'); - -// Callback API -readdir.async('my/directory', function(err, files) { ... }); - -// Promises API -readdir.async('my/directory') - .then(function(files) { ... }) - .catch(function(err) { ... }); - -// EventEmitter API -readdir.stream('my/directory') - .on('data', function(path) { ... }) - .on('file', function(path) { ... }) - .on('directory', function(path) { ... }) - .on('symlink', function(path) { ... }) - .on('error', function(err) { ... }); - -// Streaming API -var stream = readdir.stream('my/directory') - .pipe(through2.obj(function(data, enc, next) { - console.log(data); - this.push(data); - next(); - }); -``` - - - -Enhanced Features ------------------ -`readdir-enhanced` adds several features to the built-in `fs.readdir()` function. All of the enhanced features are opt-in, which makes `readdir-enhanced` [fully backward compatible by default](#backward-compatible). You can enable any of the features by passing-in an `options` argument as the second parameter. - - - -### Recursion -By default, `readdir-enhanced` will only return the top-level contents of the starting directory. But you can set the `deep` option to recursively traverse the subdirectories and return their contents as well. - -#### Crawl ALL subdirectories - -The `deep` option can be set to `true` to traverse the entire directory structure. - -```javascript -var readdir = require('readdir-enhanced'); - -readdir('my/directory', {deep: true}, function(err, files) { - console.log(files); - // => subdir1 - // => subdir1/file.txt - // => subdir1/subdir2 - // => subdir1/subdir2/file.txt - // => subdir1/subdir2/subdir3 - // => subdir1/subdir2/subdir3/file.txt -}); -``` - -#### Crawl to a specific depth -The `deep` option can be set to a number to only traverse that many levels deep. For example, calling `readdir('my/directory', {deep: 2})` will return `subdir1/file.txt` and `subdir1/subdir2/file.txt`, but it _won't_ return `subdir1/subdir2/subdir3/file.txt`. - -```javascript -var readdir = require('readdir-enhanced'); - -readdir('my/directory', {deep: 2}, function(err, files) { - console.log(files); - // => subdir1 - // => subdir1/file.txt - // => subdir1/subdir2 - // => subdir1/subdir2/file.txt - // => subdir1/subdir2/subdir3 -}); -``` - -#### Crawl subdirectories by name -For simple use-cases, you can use a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) or a [glob pattern](https://github.com/isaacs/node-glob#glob-primer) to crawl only the directories whose path matches the pattern. The path is relative to the starting directory by default, but you can customize this via [`options.basePath`](#basepath). - -> **NOTE:** Glob patterns [_always_ use forward-slashes](https://github.com/isaacs/node-glob#windows), even on Windows. This _does not_ apply to regular expressions though. Regular expressions should use the appropraite path separator for the environment. Or, you can match both types of separators using `[\\/]`. - -```javascript -var readdir = require('readdir-enhanced'); - -// Only crawl the "lib" and "bin" subdirectories -// (notice that the "node_modules" subdirectory does NOT get crawled) -readdir('my/directory', {deep: /lib|bin/}, function(err, files) { - console.log(files); - // => bin - // => bin/cli.js - // => lib - // => lib/index.js - // => node_modules - // => package.json -}); -``` - -#### Custom recursion logic -For more advanced recursion, you can set the `deep` option to a function that accepts an [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object and returns a truthy value if the starting directory should be crawled. - -> **NOTE:** The [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that's passed to the function has additional `path` and `depth` properties. The `path` is relative to the starting directory by default, but you can customize this via [`options.basePath`](#basepath). The `depth` is the number of subdirectories beneath the base path (see [`options.deep`](#deep)). - -```javascript -var readdir = require('readdir-enhanced'); - -// Crawl all subdirectories, except "node_modules" -function ignoreNodeModules (stats) { - return stats.path.indexOf('node_modules') === -1; -} - -readdir('my/directory', {deep: ignoreNodeModules}, function(err, files) { - console.log(files); - // => bin - // => bin/cli.js - // => lib - // => lib/index.js - // => node_modules - // => package.json -}); -``` - - - -### Filtering -The `filter` option lets you limit the results based on any criteria you want. - -#### Filter by name -For simple use-cases, you can use a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) or a [glob pattern](https://github.com/isaacs/node-glob#glob-primer) to filter items by their path. The path is relative to the starting directory by default, but you can customize this via [`options.basePath`](#basepath). - -> **NOTE:** Glob patterns [_always_ use forward-slashes](https://github.com/isaacs/node-glob#windows), even on Windows. This _does not_ apply to regular expressions though. Regular expressions should use the appropraite path separator for the environment. Or, you can match both types of separators using `[\\/]`. - -```javascript -var readdir = require('readdir-enhanced'); - -// Find all .txt files -readdir('my/directory', {filter: '*.txt'}); - -// Find all package.json files -readdir('my/directory', {filter: '**/package.json', deep: true}); - -// Find everything with at least one number in the name -readdir('my/directory', {filter: /\d+/}); -``` - -#### Custom filtering logic -For more advanced filtering, you can specify a filter function that accepts an [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object and returns a truthy value if the item should be included in the results. - -> **NOTE:** The [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that's passed to the filter function has additional `path` and `depth` properties. The `path` is relative to the starting directory by default, but you can customize this via [`options.basePath`](#basepath). The `depth` is the number of subdirectories beneath the base path (see [`options.deep`](#deep)). - -```javascript -var readdir = require('readdir-enhanced'); - -// Only return file names containing an underscore -function myFilter(stats) { - return stats.isFile() && stats.path.indexOf('_') >= 0; -} - -readdir('my/directory', {filter: myFilter}, function(err, files) { - console.log(files); - // => __myFile.txt - // => my_other_file.txt - // => img_1.jpg - // => node_modules -}); -``` - - - -### Base Path -By default all `readdir-enhanced` functions return paths that are relative to the starting directory. But you can use the `basePath` option to customize this. The `basePath` will be prepended to all of the returned paths. One common use-case for this is to set `basePath` to the absolute path of the starting directory, so that all of the returned paths will be absolute. - -```javascript -var readdir = require('readdir-enhanced'); -var path = require('path'); - -// Get absolute paths -var absPath = path.resolve('my/dir'); -readdir('my/directory', {basePath: absPath}, function(err, files) { - console.log(files); - // => /absolute/path/to/my/directory/file1.txt - // => /absolute/path/to/my/directory/file2.txt - // => /absolute/path/to/my/directory/subdir -}); - -// Get paths relative to the working directory -readdir('my/directory', {basePath: 'my/directory'}, function(err, files) { - console.log(files); - // => my/directory/file1.txt - // => my/directory/file2.txt - // => my/directory/subdir -}); -``` - - - -### Path Separator -By default, `readdir-enhanced` uses the correct path separator for your OS (`\` on Windows, `/` on Linux & MacOS). But you can set the `sep` option to any separator character(s) that you want to use instead. This is usually used to ensure consistent path separators across different OSes. - -```javascript -var readdir = require('readdir-enhanced'); - -// Always use Windows path separators -readdir('my/directory', {sep: '\\', deep: true}, function(err, files) { - console.log(files); - // => subdir1 - // => subdir1\file.txt - // => subdir1\subdir2 - // => subdir1\subdir2\file.txt - // => subdir1\subdir2\subdir3 - // => subdir1\subdir2\subdir3\file.txt -}); -``` - - -### Custom FS methods -By default, `readdir-enhanced` uses the default [Node.js FileSystem module](https://nodejs.org/api/fs.html) for methods like `fs.stat`, `fs.readdir` and `fs.lstat`. But in some situations, you can want to use your own FS methods (FTP, SSH, remote drive and etc). So you can provide your own implementation of FS methods by setting `options.fs` or specific methods, such as `options.fs.stat`. - -```javascript -var readdir = require('readdir-enhanced'); - -function myCustomReaddirMethod(dir, callback) { - callback(null, ['__myFile.txt']); -} - -var options = { - fs: { - readdir: myCustomReaddirMethod - } -}; - -readdir('my/directory', options, function(err, files) { - console.log(files); - // => __myFile.txt -}); -``` - - -Get `fs.Stats` objects instead of strings ------------------------- -All of the `readdir-enhanced` functions listed above return an array of strings (paths). But in some situations, the path isn't enough information. So, `readdir-enhanced` provides alternative versions of each function, which return an array of [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) objects instead of strings. The `fs.Stats` object contains all sorts of useful information, such as the size, the creation date/time, and helper methods such as `isFile()`, `isDirectory()`, `isSymbolicLink()`, etc. - -> **NOTE:** The [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) objects that are returned also have additional `path` and `depth` properties. The `path` is relative to the starting directory by default, but you can customize this via [`options.basePath`](#basepath). The `depth` is the number of subdirectories beneath the base path (see [`options.deep`](#deep)). - -To get `fs.Stats` objects instead of strings, just add the word "Stat" to the function name. As with the normal functions, each one is aliased (e.g. `readdir.async.stat` is the same as `readdir.readdirAsyncStat`), so you can use whichever naming style you prefer. - -```javascript -var readdir = require('readdir-enhanced'); - -// Synchronous API -var stats = readdir.sync.stat('my/directory'); -var stats = readdir.readdirSyncStat('my/directory'); - -// Async API -readdir.async.stat('my/directory', function(err, stats) { ... }); -readdir.readdirAsyncStat('my/directory', function(err, stats) { ... }); - -// Streaming API -readdir.stream.stat('my/directory') - .on('data', function(stat) { ... }) - .on('file', function(stat) { ... }) - .on('directory', function(stat) { ... }) - .on('symlink', function(stat) { ... }); - -readdir.readdirStreamStat('my/directory') - .on('data', function(stat) { ... }) - .on('file', function(stat) { ... }) - .on('directory', function(stat) { ... }) - .on('symlink', function(stat) { ... }); - -``` - - -Backward Compatible --------------------- -`readdir-enhanced` is fully backward-compatible with Node.js' built-in `fs.readdir()` and `fs.readdirSync()` functions, so you can use it as a drop-in replacement in existing projects without affecting existing functionality, while still being able to use the enhanced features as needed. - -```javascript -var readdir = require('readdir-enhanced'); -var readdirSync = readdir.sync; - -// Use it just like Node's built-in fs.readdir function -readdir('my/directory', function(err, files) { ... }); - -// Use it just like Node's built-in fs.readdirSync function -var files = readdirSync('my/directory'); -``` - - - -Contributing --------------------------- -I welcome any contributions, enhancements, and bug-fixes. [File an issue](https://github.com/BigstickCarpet/readdir-enhanced/issues) on GitHub and [submit a pull request](https://github.com/BigstickCarpet/readdir-enhanced/pulls). - -#### Building -To build the project locally on your computer: - -1. __Clone this repo__
-`git clone https://github.com/bigstickcarpet/readdir-enhanced.git` - -2. __Install dependencies__
-`npm install` - -3. __Run the tests__
-`npm test` - - - -License --------------------------- -`readdir-enhanced` is 100% free and open-source, under the [MIT license](LICENSE). Use it however you want. - diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/for-each.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/for-each.js deleted file mode 100644 index 1ac9b2fe..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/for-each.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -module.exports = asyncForEach; - -/** - * Simultaneously processes all items in the given array. - * - * @param {array} array - The array to iterate over - * @param {function} iterator - The function to call for each item in the array - * @param {function} done - The function to call when all iterators have completed - */ -function asyncForEach (array, iterator, done) { - if (array.length === 0) { - // NOTE: Normally a bad idea to mix sync and async, but it's safe here because - // of the way that this method is currently used by DirectoryReader. - done(); - return; - } - - // Simultaneously process all items in the array. - let pending = array.length; - array.forEach(item => { - iterator(item, () => { - if (--pending === 0) { - done(); - } - }); - }); -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/index.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/index.js deleted file mode 100644 index 677e0b65..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/async/index.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -module.exports = readdirAsync; - -const maybe = require('call-me-maybe'); -const DirectoryReader = require('../directory-reader'); - -let asyncFacade = { - fs: require('fs'), - forEach: require('./for-each'), - async: true -}; - -/** - * Returns the buffered output from an asynchronous {@link DirectoryReader}, - * via an error-first callback or a {@link Promise}. - * - * @param {string} dir - * @param {object} [options] - * @param {function} [callback] - * @param {object} internalOptions - */ -function readdirAsync (dir, options, callback, internalOptions) { - if (typeof options === 'function') { - callback = options; - options = undefined; - } - - return maybe(callback, new Promise(((resolve, reject) => { - let results = []; - - internalOptions.facade = asyncFacade; - - let reader = new DirectoryReader(dir, options, internalOptions); - let stream = reader.stream; - - stream.on('error', err => { - reject(err); - stream.pause(); - }); - stream.on('data', result => { - results.push(result); - }); - stream.on('end', () => { - resolve(results); - }); - }))); -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/call.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/call.js deleted file mode 100644 index 07e3d848..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/call.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -let call = module.exports = { - safe: safeCall, - once: callOnce, -}; - -/** - * Calls a function with the given arguments, and ensures that the error-first callback is _always_ - * invoked exactly once, even if the function throws an error. - * - * @param {function} fn - The function to invoke - * @param {...*} args - The arguments to pass to the function. The final argument must be a callback function. - */ -function safeCall (fn, args) { - // Get the function arguments as an array - args = Array.prototype.slice.call(arguments, 1); - - // Replace the callback function with a wrapper that ensures it will only be called once - let callback = call.once(args.pop()); - args.push(callback); - - try { - fn.apply(null, args); - } - catch (err) { - callback(err); - } -} - -/** - * Returns a wrapper function that ensures the given callback function is only called once. - * Subsequent calls are ignored, unless the first argument is an Error, in which case the - * error is thrown. - * - * @param {function} fn - The function that should only be called once - * @returns {function} - */ -function callOnce (fn) { - let fulfilled = false; - - return function onceWrapper (err) { - if (!fulfilled) { - fulfilled = true; - return fn.apply(this, arguments); - } - else if (err) { - // The callback has already been called, but now an error has occurred - // (most likely inside the callback function). So re-throw the error, - // so it gets handled further up the call stack - throw err; - } - }; -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/directory-reader.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/directory-reader.js deleted file mode 100644 index 569d7939..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/directory-reader.js +++ /dev/null @@ -1,380 +0,0 @@ -'use strict'; - -const Readable = require('stream').Readable; -const EventEmitter = require('events').EventEmitter; -const path = require('path'); -const normalizeOptions = require('./normalize-options'); -const stat = require('./stat'); -const call = require('./call'); - -/** - * Asynchronously reads the contents of a directory and streams the results - * via a {@link stream.Readable}. - */ -class DirectoryReader { - /** - * @param {string} dir - The absolute or relative directory path to read - * @param {object} [options] - User-specified options, if any (see {@link normalizeOptions}) - * @param {object} internalOptions - Internal options that aren't part of the public API - * @class - */ - constructor (dir, options, internalOptions) { - this.options = options = normalizeOptions(options, internalOptions); - - // Indicates whether we should keep reading - // This is set false if stream.Readable.push() returns false. - this.shouldRead = true; - - // The directories to read - // (initialized with the top-level directory) - this.queue = [{ - path: dir, - basePath: options.basePath, - posixBasePath: options.posixBasePath, - depth: 0 - }]; - - // The number of directories that are currently being processed - this.pending = 0; - - // The data that has been read, but not yet emitted - this.buffer = []; - - this.stream = new Readable({ objectMode: true }); - this.stream._read = () => { - // Start (or resume) reading - this.shouldRead = true; - - // If we have data in the buffer, then send the next chunk - if (this.buffer.length > 0) { - this.pushFromBuffer(); - } - - // If we have directories queued, then start processing the next one - if (this.queue.length > 0) { - if (this.options.facade.sync) { - while (this.queue.length > 0) { - this.readNextDirectory(); - } - } - else { - this.readNextDirectory(); - } - } - - this.checkForEOF(); - }; - } - - /** - * Reads the next directory in the queue - */ - readNextDirectory () { - let facade = this.options.facade; - let dir = this.queue.shift(); - this.pending++; - - // Read the directory listing - call.safe(facade.fs.readdir, dir.path, (err, items) => { - if (err) { - // fs.readdir threw an error - this.emit('error', err); - return this.finishedReadingDirectory(); - } - - try { - // Process each item in the directory (simultaneously, if async) - facade.forEach( - items, - this.processItem.bind(this, dir), - this.finishedReadingDirectory.bind(this, dir) - ); - } - catch (err2) { - // facade.forEach threw an error - // (probably because fs.readdir returned an invalid result) - this.emit('error', err2); - this.finishedReadingDirectory(); - } - }); - } - - /** - * This method is called after all items in a directory have been processed. - * - * NOTE: This does not necessarily mean that the reader is finished, since there may still - * be other directories queued or pending. - */ - finishedReadingDirectory () { - this.pending--; - - if (this.shouldRead) { - // If we have directories queued, then start processing the next one - if (this.queue.length > 0 && this.options.facade.async) { - this.readNextDirectory(); - } - - this.checkForEOF(); - } - } - - /** - * Determines whether the reader has finished processing all items in all directories. - * If so, then the "end" event is fired (via {@Readable#push}) - */ - checkForEOF () { - if (this.buffer.length === 0 && // The stuff we've already read - this.pending === 0 && // The stuff we're currently reading - this.queue.length === 0) { // The stuff we haven't read yet - // There's no more stuff! - this.stream.push(null); - } - } - - /** - * Processes a single item in a directory. - * - * If the item is a directory, and `option.deep` is enabled, then the item will be added - * to the directory queue. - * - * If the item meets the filter criteria, then it will be emitted to the reader's stream. - * - * @param {object} dir - A directory object from the queue - * @param {string} item - The name of the item (name only, no path) - * @param {function} done - A callback function that is called after the item has been processed - */ - processItem (dir, item, done) { - let stream = this.stream; - let options = this.options; - - let itemPath = dir.basePath + item; - let posixPath = dir.posixBasePath + item; - let fullPath = path.join(dir.path, item); - - // If `options.deep` is a number, and we've already recursed to the max depth, - // then there's no need to check fs.Stats to know if it's a directory. - // If `options.deep` is a function, then we'll need fs.Stats - let maxDepthReached = dir.depth >= options.recurseDepth; - - // Do we need to call `fs.stat`? - let needStats = - !maxDepthReached || // we need the fs.Stats to know if it's a directory - options.stats || // the user wants fs.Stats objects returned - options.recurseFn || // we need fs.Stats for the recurse function - options.filterFn || // we need fs.Stats for the filter function - EventEmitter.listenerCount(stream, 'file') || // we need the fs.Stats to know if it's a file - EventEmitter.listenerCount(stream, 'directory') || // we need the fs.Stats to know if it's a directory - EventEmitter.listenerCount(stream, 'symlink'); // we need the fs.Stats to know if it's a symlink - - // If we don't need stats, then exit early - if (!needStats) { - if (this.filter(itemPath, posixPath)) { - this.pushOrBuffer({ data: itemPath }); - } - return done(); - } - - // Get the fs.Stats object for this path - stat(options.facade.fs, fullPath, (err, stats) => { - if (err) { - // fs.stat threw an error - this.emit('error', err); - return done(); - } - - try { - // Add the item's path to the fs.Stats object - // The base of this path, and its separators are determined by the options - // (i.e. options.basePath and options.sep) - stats.path = itemPath; - - // Add depth of the path to the fs.Stats object for use this in the filter function - stats.depth = dir.depth; - - if (this.shouldRecurse(stats, posixPath, maxDepthReached)) { - // Add this subdirectory to the queue - this.queue.push({ - path: fullPath, - basePath: itemPath + options.sep, - posixBasePath: posixPath + '/', - depth: dir.depth + 1, - }); - } - - // Determine whether this item matches the filter criteria - if (this.filter(stats, posixPath)) { - this.pushOrBuffer({ - data: options.stats ? stats : itemPath, - file: stats.isFile(), - directory: stats.isDirectory(), - symlink: stats.isSymbolicLink(), - }); - } - - done(); - } - catch (err2) { - // An error occurred while processing the item - // (probably during a user-specified function, such as options.deep, options.filter, etc.) - this.emit('error', err2); - done(); - } - }); - } - - /** - * Pushes the given chunk of data to the stream, or adds it to the buffer, - * depending on the state of the stream. - * - * @param {object} chunk - */ - pushOrBuffer (chunk) { - // Add the chunk to the buffer - this.buffer.push(chunk); - - // If we're still reading, then immediately emit the next chunk in the buffer - // (which may or may not be the chunk that we just added) - if (this.shouldRead) { - this.pushFromBuffer(); - } - } - - /** - * Immediately pushes the next chunk in the buffer to the reader's stream. - * The "data" event will always be fired (via {@link Readable#push}). - * In addition, the "file", "directory", and/or "symlink" events may be fired, - * depending on the type of properties of the chunk. - */ - pushFromBuffer () { - let stream = this.stream; - let chunk = this.buffer.shift(); - - // Stream the data - try { - this.shouldRead = stream.push(chunk.data); - } - catch (err) { - this.emit('error', err); - } - - // Also emit specific events, based on the type of chunk - chunk.file && this.emit('file', chunk.data); - chunk.symlink && this.emit('symlink', chunk.data); - chunk.directory && this.emit('directory', chunk.data); - } - - /** - * Determines whether the given directory meets the user-specified recursion criteria. - * If the user didn't specify recursion criteria, then this function will default to true. - * - * @param {fs.Stats} stats - The directory's {@link fs.Stats} object - * @param {string} posixPath - The item's POSIX path (used for glob matching) - * @param {boolean} maxDepthReached - Whether we've already crawled the user-specified depth - * @returns {boolean} - */ - shouldRecurse (stats, posixPath, maxDepthReached) { - let options = this.options; - - if (maxDepthReached) { - // We've already crawled to the maximum depth. So no more recursion. - return false; - } - else if (!stats.isDirectory()) { - // It's not a directory. So don't try to crawl it. - return false; - } - else if (options.recurseGlob) { - // Glob patterns are always tested against the POSIX path, even on Windows - // https://github.com/isaacs/node-glob#windows - return options.recurseGlob.test(posixPath); - } - else if (options.recurseRegExp) { - // Regular expressions are tested against the normal path - // (based on the OS or options.sep) - return options.recurseRegExp.test(stats.path); - } - else if (options.recurseFn) { - try { - // Run the user-specified recursion criteria - return options.recurseFn.call(null, stats); - } - catch (err) { - // An error occurred in the user's code. - // In Sync and Async modes, this will return an error. - // In Streaming mode, we emit an "error" event, but continue processing - this.emit('error', err); - } - } - else { - // No recursion function was specified, and we're within the maximum depth. - // So crawl this directory. - return true; - } - } - - /** - * Determines whether the given item meets the user-specified filter criteria. - * If the user didn't specify a filter, then this function will always return true. - * - * @param {string|fs.Stats} value - Either the item's path, or the item's {@link fs.Stats} object - * @param {string} posixPath - The item's POSIX path (used for glob matching) - * @returns {boolean} - */ - filter (value, posixPath) { - let options = this.options; - - if (options.filterGlob) { - // Glob patterns are always tested against the POSIX path, even on Windows - // https://github.com/isaacs/node-glob#windows - return options.filterGlob.test(posixPath); - } - else if (options.filterRegExp) { - // Regular expressions are tested against the normal path - // (based on the OS or options.sep) - return options.filterRegExp.test(value.path || value); - } - else if (options.filterFn) { - try { - // Run the user-specified filter function - return options.filterFn.call(null, value); - } - catch (err) { - // An error occurred in the user's code. - // In Sync and Async modes, this will return an error. - // In Streaming mode, we emit an "error" event, but continue processing - this.emit('error', err); - } - } - else { - // No filter was specified, so match everything - return true; - } - } - - /** - * Emits an event. If one of the event listeners throws an error, - * then an "error" event is emitted. - * - * @param {string} eventName - * @param {*} data - */ - emit (eventName, data) { - let stream = this.stream; - - try { - stream.emit(eventName, data); - } - catch (err) { - if (eventName === 'error') { - // Don't recursively emit "error" events. - // If the first one fails, then just throw - throw err; - } - else { - stream.emit('error', err); - } - } - } -} - -module.exports = DirectoryReader; diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/index.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/index.js deleted file mode 100644 index f77d2c6a..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/index.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -const readdirSync = require('./sync'); -const readdirAsync = require('./async'); -const readdirStream = require('./stream'); - -module.exports = exports = readdirAsyncPath; -exports.readdir = exports.readdirAsync = exports.async = readdirAsyncPath; -exports.readdirAsyncStat = exports.async.stat = readdirAsyncStat; -exports.readdirStream = exports.stream = readdirStreamPath; -exports.readdirStreamStat = exports.stream.stat = readdirStreamStat; -exports.readdirSync = exports.sync = readdirSyncPath; -exports.readdirSyncStat = exports.sync.stat = readdirSyncStat; - -/** - * Synchronous readdir that returns an array of string paths. - * - * @param {string} dir - * @param {object} [options] - * @returns {string[]} - */ -function readdirSyncPath (dir, options) { - return readdirSync(dir, options, {}); -} - -/** - * Synchronous readdir that returns results as an array of {@link fs.Stats} objects - * - * @param {string} dir - * @param {object} [options] - * @returns {fs.Stats[]} - */ -function readdirSyncStat (dir, options) { - return readdirSync(dir, options, { stats: true }); -} - -/** - * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). - * Results are an array of path strings. - * - * @param {string} dir - * @param {object} [options] - * @param {function} [callback] - * @returns {Promise} - */ -function readdirAsyncPath (dir, options, callback) { - return readdirAsync(dir, options, callback, {}); -} - -/** - * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). - * Results are an array of {@link fs.Stats} objects. - * - * @param {string} dir - * @param {object} [options] - * @param {function} [callback] - * @returns {Promise} - */ -function readdirAsyncStat (dir, options, callback) { - return readdirAsync(dir, options, callback, { stats: true }); -} - -/** - * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}). - * All stream data events ("data", "file", "directory", "symlink") are passed a path string. - * - * @param {string} dir - * @param {object} [options] - * @returns {stream.Readable} - */ -function readdirStreamPath (dir, options) { - return readdirStream(dir, options, {}); -} - -/** - * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}) - * All stream data events ("data", "file", "directory", "symlink") are passed an {@link fs.Stats} object. - * - * @param {string} dir - * @param {object} [options] - * @returns {stream.Readable} - */ -function readdirStreamStat (dir, options) { - return readdirStream(dir, options, { stats: true }); -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/normalize-options.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/normalize-options.js deleted file mode 100644 index 66f11581..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/normalize-options.js +++ /dev/null @@ -1,177 +0,0 @@ -'use strict'; - -const path = require('path'); -const globToRegExp = require('glob-to-regexp'); - -module.exports = normalizeOptions; - -let isWindows = /^win/.test(process.platform); - -/** - * @typedef {Object} FSFacade - * @property {fs.readdir} readdir - * @property {fs.stat} stat - * @property {fs.lstat} lstat - */ - -/** - * Validates and normalizes the options argument - * - * @param {object} [options] - User-specified options, if any - * @param {object} internalOptions - Internal options that aren't part of the public API - * - * @param {number|boolean|function} [options.deep] - * The number of directories to recursively traverse. Any falsy value or negative number will - * default to zero, so only the top-level contents will be returned. Set to `true` or `Infinity` - * to traverse all subdirectories. Or provide a function that accepts a {@link fs.Stats} object - * and returns a truthy value if the directory's contents should be crawled. - * - * @param {function|string|RegExp} [options.filter] - * A function that accepts a {@link fs.Stats} object and returns a truthy value if the data should - * be returned. Or a RegExp or glob string pattern, to filter by file name. - * - * @param {string} [options.sep] - * The path separator to use. By default, the OS-specific separator will be used, but this can be - * set to a specific value to ensure consistency across platforms. - * - * @param {string} [options.basePath] - * The base path to prepend to each result. If empty, then all results will be relative to `dir`. - * - * @param {FSFacade} [options.fs] - * Synchronous or asynchronous facades for Node.js File System module - * - * @param {object} [internalOptions.facade] - * Synchronous or asynchronous facades for various methods, including for the Node.js File System module - * - * @param {boolean} [internalOptions.emit] - * Indicates whether the reader should emit "file", "directory", and "symlink" events - * - * @param {boolean} [internalOptions.stats] - * Indicates whether the reader should emit {@link fs.Stats} objects instead of path strings - * - * @returns {object} - */ -function normalizeOptions (options, internalOptions) { - if (options === null || options === undefined) { - options = {}; - } - else if (typeof options !== 'object') { - throw new TypeError('options must be an object'); - } - - let recurseDepth, recurseFn, recurseRegExp, recurseGlob, deep = options.deep; - if (deep === null || deep === undefined) { - recurseDepth = 0; - } - else if (typeof deep === 'boolean') { - recurseDepth = deep ? Infinity : 0; - } - else if (typeof deep === 'number') { - if (deep < 0 || isNaN(deep)) { - throw new Error('options.deep must be a positive number'); - } - else if (Math.floor(deep) !== deep) { - throw new Error('options.deep must be an integer'); - } - else { - recurseDepth = deep; - } - } - else if (typeof deep === 'function') { - recurseDepth = Infinity; - recurseFn = deep; - } - else if (deep instanceof RegExp) { - recurseDepth = Infinity; - recurseRegExp = deep; - } - else if (typeof deep === 'string' && deep.length > 0) { - recurseDepth = Infinity; - recurseGlob = globToRegExp(deep, { extended: true, globstar: true }); - } - else { - throw new TypeError('options.deep must be a boolean, number, function, regular expression, or glob pattern'); - } - - let filterFn, filterRegExp, filterGlob, filter = options.filter; - if (filter !== null && filter !== undefined) { - if (typeof filter === 'function') { - filterFn = filter; - } - else if (filter instanceof RegExp) { - filterRegExp = filter; - } - else if (typeof filter === 'string' && filter.length > 0) { - filterGlob = globToRegExp(filter, { extended: true, globstar: true }); - } - else { - throw new TypeError('options.filter must be a function, regular expression, or glob pattern'); - } - } - - let sep = options.sep; - if (sep === null || sep === undefined) { - sep = path.sep; - } - else if (typeof sep !== 'string') { - throw new TypeError('options.sep must be a string'); - } - - let basePath = options.basePath; - if (basePath === null || basePath === undefined) { - basePath = ''; - } - else if (typeof basePath === 'string') { - // Append a path separator to the basePath, if necessary - if (basePath && basePath.substr(-1) !== sep) { - basePath += sep; - } - } - else { - throw new TypeError('options.basePath must be a string'); - } - - // Convert the basePath to POSIX (forward slashes) - // so that glob pattern matching works consistently, even on Windows - let posixBasePath = basePath; - if (posixBasePath && sep !== '/') { - posixBasePath = posixBasePath.replace(new RegExp('\\' + sep, 'g'), '/'); - - /* istanbul ignore if */ - if (isWindows) { - // Convert Windows root paths (C:\) and UNCs (\\) to POSIX root paths - posixBasePath = posixBasePath.replace(/^([a-zA-Z]\:\/|\/\/)/, '/'); - } - } - - // Determine which facade methods to use - let facade; - if (options.fs === null || options.fs === undefined) { - // The user didn't provide their own facades, so use our internal ones - facade = internalOptions.facade; - } - else if (typeof options.fs === 'object') { - // Merge the internal facade methods with the user-provided `fs` facades - facade = Object.assign({}, internalOptions.facade); - facade.fs = Object.assign({}, internalOptions.facade.fs, options.fs); - } - else { - throw new TypeError('options.fs must be an object'); - } - - return { - recurseDepth, - recurseFn, - recurseRegExp, - recurseGlob, - filterFn, - filterRegExp, - filterGlob, - sep, - basePath, - posixBasePath, - facade, - emit: !!internalOptions.emit, - stats: !!internalOptions.stats, - }; -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/stat.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/stat.js deleted file mode 100644 index e338693f..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/stat.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; - -const call = require('./call'); - -module.exports = stat; - -/** - * Retrieves the {@link fs.Stats} for the given path. If the path is a symbolic link, - * then the Stats of the symlink's target are returned instead. If the symlink is broken, - * then the Stats of the symlink itself are returned. - * - * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module - * @param {string} path - The path to return stats for - * @param {function} callback - */ -function stat (fs, path, callback) { - let isSymLink = false; - - call.safe(fs.lstat, path, (err, lstats) => { - if (err) { - // fs.lstat threw an eror - return callback(err); - } - - try { - isSymLink = lstats.isSymbolicLink(); - } - catch (err2) { - // lstats.isSymbolicLink() threw an error - // (probably because fs.lstat returned an invalid result) - return callback(err2); - } - - if (isSymLink) { - // Try to resolve the symlink - symlinkStat(fs, path, lstats, callback); - } - else { - // It's not a symlink, so return the stats as-is - callback(null, lstats); - } - }); -} - -/** - * Retrieves the {@link fs.Stats} for the target of the given symlink. - * If the symlink is broken, then the Stats of the symlink itself are returned. - * - * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module - * @param {string} path - The path of the symlink to return stats for - * @param {object} lstats - The stats of the symlink - * @param {function} callback - */ -function symlinkStat (fs, path, lstats, callback) { - call.safe(fs.stat, path, (err, stats) => { - if (err) { - // The symlink is broken, so return the stats for the link itself - return callback(null, lstats); - } - - try { - // Return the stats for the resolved symlink target, - // and override the `isSymbolicLink` method to indicate that it's a symlink - stats.isSymbolicLink = () => true; - } - catch (err2) { - // Setting stats.isSymbolicLink threw an error - // (probably because fs.stat returned an invalid result) - return callback(err2); - } - - callback(null, stats); - }); -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/stream/index.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/stream/index.js deleted file mode 100644 index 22a96094..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/stream/index.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -module.exports = readdirStream; - -const DirectoryReader = require('../directory-reader'); - -let streamFacade = { - fs: require('fs'), - forEach: require('../async/for-each'), - async: true -}; - -/** - * Returns the {@link stream.Readable} of an asynchronous {@link DirectoryReader}. - * - * @param {string} dir - * @param {object} [options] - * @param {object} internalOptions - */ -function readdirStream (dir, options, internalOptions) { - internalOptions.facade = streamFacade; - - let reader = new DirectoryReader(dir, options, internalOptions); - return reader.stream; -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/for-each.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/for-each.js deleted file mode 100644 index c5ec088b..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/for-each.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -module.exports = syncForEach; - -/** - * A facade that allows {@link Array.forEach} to be called as though it were asynchronous. - * - * @param {array} array - The array to iterate over - * @param {function} iterator - The function to call for each item in the array - * @param {function} done - The function to call when all iterators have completed - */ -function syncForEach (array, iterator, done) { - array.forEach(item => { - iterator(item, () => { - // Note: No error-handling here because this is currently only ever called - // by DirectoryReader, which never passes an `error` parameter to the callback. - // Instead, DirectoryReader emits an "error" event if an error occurs. - }); - }); - - done(); -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/fs.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/fs.js deleted file mode 100644 index 3aada777..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/fs.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const call = require('../call'); - -/** - * A facade around {@link fs.readdirSync} that allows it to be called - * the same way as {@link fs.readdir}. - * - * @param {string} dir - * @param {function} callback - */ -exports.readdir = function (dir, callback) { - // Make sure the callback is only called once - callback = call.once(callback); - - try { - let items = fs.readdirSync(dir); - callback(null, items); - } - catch (err) { - callback(err); - } -}; - -/** - * A facade around {@link fs.statSync} that allows it to be called - * the same way as {@link fs.stat}. - * - * @param {string} path - * @param {function} callback - */ -exports.stat = function (path, callback) { - // Make sure the callback is only called once - callback = call.once(callback); - - try { - let stats = fs.statSync(path); - callback(null, stats); - } - catch (err) { - callback(err); - } -}; - -/** - * A facade around {@link fs.lstatSync} that allows it to be called - * the same way as {@link fs.lstat}. - * - * @param {string} path - * @param {function} callback - */ -exports.lstat = function (path, callback) { - // Make sure the callback is only called once - callback = call.once(callback); - - try { - let stats = fs.lstatSync(path); - callback(null, stats); - } - catch (err) { - callback(err); - } -}; diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/index.js b/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/index.js deleted file mode 100644 index 60243a1a..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/lib/sync/index.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -module.exports = readdirSync; - -const DirectoryReader = require('../directory-reader'); - -let syncFacade = { - fs: require('./fs'), - forEach: require('./for-each'), - sync: true -}; - -/** - * Returns the buffered output from a synchronous {@link DirectoryReader}. - * - * @param {string} dir - * @param {object} [options] - * @param {object} internalOptions - */ -function readdirSync (dir, options, internalOptions) { - internalOptions.facade = syncFacade; - - let reader = new DirectoryReader(dir, options, internalOptions); - let stream = reader.stream; - - let results = []; - let data = stream.read(); - while (data !== null) { - results.push(data); - data = stream.read(); - } - - return results; -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/package.json b/functions/node_modules/@mrmlnc/readdir-enhanced/package.json deleted file mode 100644 index 41615d7d..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/package.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "_from": "@mrmlnc/readdir-enhanced@^2.2.1", - "_id": "@mrmlnc/readdir-enhanced@2.2.1", - "_inBundle": false, - "_integrity": "sha512-bPHp6Ji8b41szTOcaP63VlnbbO5Ny6dwAATtY6JTjh5N2OLrb5Qk/Th5cRkRQhkWCt+EJsYrNB0MiL+Gpn6e3g==", - "_location": "/@mrmlnc/readdir-enhanced", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@mrmlnc/readdir-enhanced@^2.2.1", - "name": "@mrmlnc/readdir-enhanced", - "escapedName": "@mrmlnc%2freaddir-enhanced", - "scope": "@mrmlnc", - "rawSpec": "^2.2.1", - "saveSpec": null, - "fetchSpec": "^2.2.1" - }, - "_requiredBy": [ - "/fast-glob" - ], - "_resolved": "https://registry.npmjs.org/@mrmlnc/readdir-enhanced/-/readdir-enhanced-2.2.1.tgz", - "_shasum": "524af240d1a360527b730475ecfa1344aa540dde", - "_spec": "@mrmlnc/readdir-enhanced@^2.2.1", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\fast-glob", - "author": { - "name": "James Messinger", - "url": "http://bigstickcarpet.com" - }, - "bugs": { - "url": "https://github.com/bigstickcarpet/readdir-enhanced/issues" - }, - "bundleDependencies": false, - "dependencies": { - "call-me-maybe": "^1.0.1", - "glob-to-regexp": "^0.3.0" - }, - "deprecated": false, - "description": "fs.readdir with sync, async, and streaming APIs + filtering, recursion, absolute paths, etc.", - "devDependencies": { - "chai": "^4.1.2", - "codacy-coverage": "^2.0.3", - "coveralls": "^3.0.0", - "del": "^3.0.0", - "eslint": "^4.15.0", - "eslint-config-modular": "^4.1.1", - "istanbul": "^0.4.5", - "mkdirp": "^0.5.1", - "mocha": "^4.1.0", - "npm-check": "^5.5.2", - "through2": "^2.0.3", - "version-bump-prompt": "^4.0.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "lib", - "types.d.ts" - ], - "homepage": "https://github.com/bigstickcarpet/readdir-enhanced", - "keywords": [ - "fs", - "readdir", - "stream", - "event", - "recursive", - "deep", - "filter", - "absolute" - ], - "license": "MIT", - "main": "lib/index.js", - "name": "@mrmlnc/readdir-enhanced", - "repository": { - "type": "git", - "url": "git+https://github.com/bigstickcarpet/readdir-enhanced.git" - }, - "scripts": { - "bump": "bump --prompt --tag --push --all", - "cover": "istanbul cover _mocha", - "lint": "eslint lib test --fix", - "release": "npm run upgrade && npm test && npm run bump && npm publish", - "test": "mocha && npm run lint", - "upgrade": "npm-check -u" - }, - "typings": "types.d.ts", - "version": "2.2.1" -} diff --git a/functions/node_modules/@mrmlnc/readdir-enhanced/types.d.ts b/functions/node_modules/@mrmlnc/readdir-enhanced/types.d.ts deleted file mode 100644 index 2f4e6223..00000000 --- a/functions/node_modules/@mrmlnc/readdir-enhanced/types.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -/// - -import fs = require('fs'); - -declare namespace re { - interface Entry extends fs.Stats { - path: string; - depth: number; - } - - type FilterFunction = (stat: Entry) => boolean; - type Callback = (err: NodeJS.ErrnoException, result: T) => void; - type CallbackString = Callback; - type CallbackEntry = Callback; - - interface FileSystem { - readdir?: (path: string, callback: Callback) => void; - lstat?: (path: string, callback: Callback) => void; - stat?: (path: string, callback: Callback) => void; - } - - interface Options { - filter?: string | RegExp | FilterFunction; - deep?: boolean | number | RegExp | FilterFunction; - sep?: string; - basePath?: string; - fs?: FileSystem; - } - - function stat(root: string, options?: Options): Promise; - function stat(root: string, callback: CallbackEntry): void; - function stat(root: string, options: Options, callback: CallbackEntry): void; - - function async(root: string, options?: Options): Promise; - function async(root: string, callback: CallbackString): void; - function async(root: string, options: Options, callback: CallbackString): void; - - function readdirAsyncStat(root: string, options?: Options): Promise; - function readdirAsyncStat(root: string, callback: CallbackEntry): void; - function readdirAsyncStat(root: string, options: Options, callback: CallbackEntry): void; - - namespace async { - function stat(root: string, options?: Options): Promise; - function stat(root: string, callback: CallbackEntry): void; - function stat(root: string, options: Options, callback: CallbackEntry): void; - } - - function stream(root: string, options?: Options): NodeJS.ReadableStream; - function readdirStreamStat(root: string, options?: Options): NodeJS.ReadableStream; - - namespace stream { - function stat(root: string, options?: Options): NodeJS.ReadableStream; - } - - function sync(root: string, options?: Options): string[]; - function readdirSyncStat(root: string, options?: Options): Entry[]; - - namespace sync { - function stat(root: string, options?: Options): Entry[]; - } -} - -declare function re(root: string, options?: re.Options): Promise; -declare function re(root: string, callback: re.CallbackString): void; -declare function re(root: string, options: re.Options, callback: re.CallbackString): void; - -export = re; diff --git a/functions/node_modules/@nodelib/fs.stat/package.json b/functions/node_modules/@nodelib/fs.stat/package.json deleted file mode 100644 index b5edeaa0..00000000 --- a/functions/node_modules/@nodelib/fs.stat/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "@nodelib/fs.stat@^1.1.2", - "_id": "@nodelib/fs.stat@1.1.3", - "_inBundle": false, - "_integrity": "sha512-shAmDyaQC4H92APFoIaVDHCx5bStIocgvbwQyxPRrbUY20V1EYTbSDchWbuwlMG3V17cprZhA6+78JfB+3DTPw==", - "_location": "/@nodelib/fs.stat", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@nodelib/fs.stat@^1.1.2", - "name": "@nodelib/fs.stat", - "escapedName": "@nodelib%2ffs.stat", - "scope": "@nodelib", - "rawSpec": "^1.1.2", - "saveSpec": null, - "fetchSpec": "^1.1.2" - }, - "_requiredBy": [ - "/fast-glob" - ], - "_resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-1.1.3.tgz", - "_shasum": "2b5a3ab3f918cca48a8c754c08168e3f03eba61b", - "_spec": "@nodelib/fs.stat@^1.1.2", - "_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\fast-glob", - "bundleDependencies": false, - "deprecated": false, - "description": "Get the status of a file with some features", - "engines": { - "node": ">= 6" - }, - "keywords": [ - "NodeLib", - "fs", - "FileSystem", - "file system", - "stat" - ], - "license": "MIT", - "main": "out/index.js", - "name": "@nodelib/fs.stat", - "repository": { - "type": "git", - "url": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat" - }, - "scripts": { - "build": "npm run clean && npm run lint && npm run compile && npm test", - "clean": "rimraf out", - "compile": "tsc -b .", - "compile:watch": "tsc -p . --watch --sourceMap", - "lint": "tslint \"src/**/*.ts\" -p . -t stylish", - "test": "mocha \"out/**/*.spec.js\" -s 0", - "watch": "npm run clean && npm run compile:watch" - }, - "typings": "out/index.d.ts", - "version": "1.1.3" -} diff --git a/functions/package-lock.json b/functions/package-lock.json deleted file mode 100644 index f6268398..00000000 --- a/functions/package-lock.json +++ /dev/null @@ -1,3878 +0,0 @@ -{ - "name": "functions", - "requires": true, - "lockfileVersion": 1, - "dependencies": { - "@firebase/app": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.3.5.tgz", - "integrity": "sha512-DaAlb74yzwXbkFXvfsUVFeurSETPJAvKNtVpAKlS6RThyD+Y+ci1/8JVw4INm2hihbj/edxlAUelg9eoOZNCKA==", - "requires": { - "@firebase/app-types": "0.3.2", - "@firebase/util": "0.2.3", - "dom-storage": "2.1.0", - "tslib": "1.9.0", - "xmlhttprequest": "1.8.0" - } - }, - "@firebase/app-types": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.3.2.tgz", - "integrity": "sha512-ZD8lTgW07NGgo75bTyBJA8Lt9+NweNzot7lrsBtIvfciwUzaFJLsv2EShqjBeuhF7RpG6YFucJ6m67w5buCtzw==" - }, - "@firebase/database": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/@firebase/database/-/database-0.3.8.tgz", - "integrity": "sha512-y+QJjxC62triL1g6e58sapkGKegvbNIp3hOttE6olYG/zzb+U4Q7lUbYjtMkVpGWKYSsQOPu8JkH3FNhFvX95Q==", - "requires": { - "@firebase/database-types": "0.3.2", - "@firebase/logger": "0.1.2", - "@firebase/util": "0.2.3", - "faye-websocket": "0.11.1", - "tslib": "1.9.0" - } - }, - "@firebase/database-types": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-0.3.2.tgz", - "integrity": "sha512-9ZYdvYQ6r3aaHJarhUM5Hf6lQWu3ZJme+RR0o8qfBb9L04TL3uNjt+AJFku1ysVPntTn+9GqJjiIB2/OC3JtwA==" - }, - "@firebase/logger": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.1.2.tgz", - "integrity": "sha512-4NHGRIbZChg9vDUxynzYrw14G/U/71v0pea+jXPicrpflL0N0PSCULXGGSTmzn9fqZ5W5djEwVLBCVwKndXG8w==" - }, - "@firebase/util": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@firebase/util/-/util-0.2.3.tgz", - "integrity": "sha512-ngAG4qYpcnnshUKbBlEiR9+j37U7dTrTVJlS4v7ahW1ROuyLT9xj6cWyHQANzcTR2yKLmEv3yfwoZwedz7V0oQ==", - "requires": { - "tslib": "1.9.0" - } - }, - "@google-cloud/common": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/@google-cloud/common/-/common-0.17.0.tgz", - "integrity": "sha512-HRZLSU762E6HaKoGfJGa8W95yRjb9rY7LePhjaHK9ILAnFacMuUGVamDbTHu1csZomm1g3tZTtXfX/aAhtie/Q==", - "optional": true, - "requires": { - "array-uniq": "1.0.3", - "arrify": "1.0.1", - "concat-stream": "1.6.2", - "create-error-class": "3.0.2", - "duplexify": "3.6.1", - "ent": "2.2.0", - "extend": "3.0.2", - "google-auto-auth": "0.10.1", - "is": "3.3.0", - "log-driver": "1.2.7", - "methmeth": "1.1.0", - "modelo": "4.2.3", - "request": "2.88.0", - "retry-request": "3.3.2", - "split-array-stream": "1.0.3", - "stream-events": "1.0.5", - "string-format-obj": "1.1.1", - "through2": "2.0.5" - }, - "dependencies": { - "retry-request": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-3.3.2.tgz", - "integrity": "sha512-WIiGp37XXDC6e7ku3LFoi7LCL/Gs9luGeeqvbPRb+Zl6OQMw4RCRfSaW+aLfE6lhz1R941UavE6Svl3Dm5xGIQ==", - "optional": true, - "requires": { - "request": "2.88.0", - "through2": "2.0.5" - } - } - } - }, - "@google-cloud/firestore": { - "version": "0.16.1", - "resolved": "https://registry.npmjs.org/@google-cloud/firestore/-/firestore-0.16.1.tgz", - "integrity": "sha512-xHb4OdRb0OP0x/8w58WJERtCi9Pr+CsloiUlVAq6fFjSyEcmxgL0V+swE8A/2rI5NGQGwtrN57xwDcis5UM/cQ==", - "optional": true, - "requires": { - "@google-cloud/projectify": "0.3.2", - "bun": "0.0.12", - "deep-equal": "1.0.1", - "extend": "3.0.2", - "functional-red-black-tree": "1.0.1", - "google-gax": "0.18.0", - "google-proto-files": "0.16.1", - "is": "3.3.0", - "lodash.merge": "4.6.1", - "protobufjs": "6.8.8", - "through2": "2.0.5" - } - }, - "@google-cloud/projectify": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-0.3.2.tgz", - "integrity": "sha512-t1bs5gE105IpgikX7zPCJZzVyXM5xZ/1kJomUPim2E2pNp4OUUFNyvKm/T2aM6GBP2F30o8abCD+/wbOhHWYYA==", - "optional": true - }, - "@google-cloud/storage": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-1.7.0.tgz", - "integrity": "sha512-QaAxzCkbhspwajoaEnT0GcnQcpjPRcBrHYuQsXtD05BtOJgVnHCLXSsfUiRdU0nVpK+Thp7+sTkQ0fvk5PanKg==", - "optional": true, - "requires": { - "@google-cloud/common": "0.17.0", - "arrify": "1.0.1", - "async": "2.6.1", - "compressible": "2.0.15", - "concat-stream": "1.6.2", - "create-error-class": "3.0.2", - "duplexify": "3.6.1", - "extend": "3.0.2", - "gcs-resumable-upload": "0.10.2", - "hash-stream-validation": "0.2.1", - "is": "3.3.0", - "mime": "2.4.0", - "mime-types": "2.1.21", - "once": "1.4.0", - "pumpify": "1.5.1", - "request": "2.88.0", - "safe-buffer": "5.1.2", - "snakeize": "0.1.0", - "stream-events": "1.0.5", - "through2": "2.0.5", - "xdg-basedir": "3.0.0" - } - }, - "@grpc/proto-loader": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.3.0.tgz", - "integrity": "sha512-9b8S/V+3W4Gv7G/JKSZ48zApgyYbfIR7mAC9XNnaSWme3zj57MIESu0ELzm9j5oxNIpFG8DgO00iJMIUZ5luqw==", - "optional": true, - "requires": { - "@types/lodash": "4.14.119", - "@types/node": "9.6.41", - "lodash": "4.17.11", - "protobufjs": "6.8.8" - }, - "dependencies": { - "@types/node": { - "version": "9.6.41", - "resolved": "https://registry.npmjs.org/@types/node/-/node-9.6.41.tgz", - "integrity": "sha512-sPZWEbFMz6qAy9SLY7jh5cgepmsiwqUUHjvEm8lpU6kug2hmmcyuTnwhoGw/GWpI5Npue4EqvsiQQI0eWjW/ZA==", - "optional": true - } - } - }, - "@mrmlnc/readdir-enhanced": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@mrmlnc/readdir-enhanced/-/readdir-enhanced-2.2.1.tgz", - "integrity": "sha512-bPHp6Ji8b41szTOcaP63VlnbbO5Ny6dwAATtY6JTjh5N2OLrb5Qk/Th5cRkRQhkWCt+EJsYrNB0MiL+Gpn6e3g==", - "requires": { - "call-me-maybe": "1.0.1", - "glob-to-regexp": "0.3.0" - } - }, - "@nodelib/fs.stat": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-1.1.3.tgz", - "integrity": "sha512-shAmDyaQC4H92APFoIaVDHCx5bStIocgvbwQyxPRrbUY20V1EYTbSDchWbuwlMG3V17cprZhA6+78JfB+3DTPw==" - }, - "@protobufjs/aspromise": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", - "integrity": "sha1-m4sMxmPWaafY9vXQiToU00jzD78=" - }, - "@protobufjs/base64": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", - "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" - }, - "@protobufjs/codegen": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", - "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" - }, - "@protobufjs/eventemitter": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", - "integrity": "sha1-NVy8mLr61ZePntCV85diHx0Ga3A=" - }, - "@protobufjs/fetch": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", - "integrity": "sha1-upn7WYYUr2VwDBYZ/wbUVLDYTEU=", - "requires": { - "@protobufjs/aspromise": "1.1.2", - "@protobufjs/inquire": "1.1.0" - } - }, - "@protobufjs/float": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", - "integrity": "sha1-Xp4avctz/Ap8uLKR33jIy9l7h9E=" - }, - "@protobufjs/inquire": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", - "integrity": "sha1-/yAOPnzyQp4tyvwRQIKOjMY48Ik=" - }, - "@protobufjs/path": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", - "integrity": "sha1-bMKyDFya1q0NzP0hynZz2Nf79o0=" - }, - "@protobufjs/pool": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", - "integrity": "sha1-Cf0V8tbTq/qbZbw2ZQbWrXhG/1Q=" - }, - "@protobufjs/utf8": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", - "integrity": "sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=" - }, - "@types/body-parser": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.17.0.tgz", - "integrity": "sha512-a2+YeUjPkztKJu5aIF2yArYFQQp8d51wZ7DavSHjFuY1mqVgidGyzEQ41JIVNy82fXj8yPgy2vJmfIywgESW6w==", - "requires": { - "@types/connect": "3.4.32", - "@types/node": "8.10.39" - } - }, - "@types/caseless": { - "version": "0.12.1", - "resolved": "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.1.tgz", - "integrity": "sha512-FhlMa34NHp9K5MY1Uz8yb+ZvuX0pnvn3jScRSNAb75KHGB8d3rEU6hqMs3Z2vjuytcMfRg6c5CHMc3wtYyD2/A==", - "optional": true - }, - "@types/connect": { - "version": "3.4.32", - "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.32.tgz", - "integrity": "sha512-4r8qa0quOvh7lGD0pre62CAb1oni1OO6ecJLGCezTmhQ8Fz50Arx9RUszryR8KlgK6avuSXvviL6yWyViQABOg==", - "requires": { - "@types/node": "8.10.39" - } - }, - "@types/cors": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.4.tgz", - "integrity": "sha512-ipZjBVsm2tF/n8qFGOuGBkUij9X9ZswVi9G3bx/6dz7POpVa6gVHcj1wsX/LVEn9MMF41fxK/PnZPPoTD1UFPw==", - "requires": { - "@types/express": "4.16.0" - } - }, - "@types/events": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@types/events/-/events-1.2.0.tgz", - "integrity": "sha512-KEIlhXnIutzKwRbQkGWb/I4HFqBuUykAdHgDED6xqwXJfONCjF5VoE0cXEiurh3XauygxzeDzgtXUqvLkxFzzA==" - }, - "@types/express": { - "version": "4.16.0", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.16.0.tgz", - "integrity": "sha512-TtPEYumsmSTtTetAPXlJVf3kEqb6wZK0bZojpJQrnD/djV4q1oB6QQ8aKvKqwNPACoe02GNiy5zDzcYivR5Z2w==", - "requires": { - "@types/body-parser": "1.17.0", - "@types/express-serve-static-core": "4.16.0", - "@types/serve-static": "1.13.2" - } - }, - "@types/express-serve-static-core": { - "version": "4.16.0", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.16.0.tgz", - "integrity": "sha512-lTeoCu5NxJU4OD9moCgm0ESZzweAx0YqsAcab6OB0EB3+As1OaHtKnaGJvcngQxYsi9UNv0abn4/DRavrRxt4w==", - "requires": { - "@types/events": "1.2.0", - "@types/node": "8.10.39", - "@types/range-parser": "1.2.3" - } - }, - "@types/form-data": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@types/form-data/-/form-data-2.2.1.tgz", - "integrity": "sha512-JAMFhOaHIciYVh8fb5/83nmuO/AHwmto+Hq7a9y8FzLDcC1KCU344XDOMEmahnrTFlHjgh4L0WJFczNIX2GxnQ==", - "optional": true, - "requires": { - "@types/node": "8.10.39" - } - }, - "@types/google-cloud__storage": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/@types/google-cloud__storage/-/google-cloud__storage-1.7.2.tgz", - "integrity": "sha512-RaQJ7+Ht20MRYJu7mgKBpbVNZIPneztKIl/DUKacRC6A8mXRsJfgDdPA7indHmJGIgm+hzUTj44+A3RyuuYZhg==", - "optional": true, - "requires": { - "@types/node": "8.10.39", - "@types/request": "2.48.1" - } - }, - "@types/jsonwebtoken": { - "version": "7.2.8", - "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-7.2.8.tgz", - "integrity": "sha512-XENN3YzEB8D6TiUww0O8SRznzy1v+77lH7UmuN54xq/IHIsyWjWOzZuFFTtoiRuaE782uAoRwBe/wwow+vQXZw==", - "requires": { - "@types/node": "8.10.39" - } - }, - "@types/lodash": { - "version": "4.14.119", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.119.tgz", - "integrity": "sha512-Z3TNyBL8Vd/M9D9Ms2S3LmFq2sSMzahodD6rCS9V2N44HUMINb75jNkSuwAx7eo2ufqTdfOdtGQpNbieUjPQmw==" - }, - "@types/long": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.0.tgz", - "integrity": "sha512-1w52Nyx4Gq47uuu0EVcsHBxZFJgurQ+rTKS3qMHxR1GY2T8c2AJYd6vZoZ9q1rupaDjU0yT+Jc2XTyXkjeMA+Q==" - }, - "@types/mime": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@types/mime/-/mime-2.0.0.tgz", - "integrity": "sha512-A2TAGbTFdBw9azHbpVd+/FkdW2T6msN1uct1O9bH3vTerEHKZhTXJUQXy+hNq1B0RagfU8U+KBdqiZpxjhOUQA==" - }, - "@types/node": { - "version": "8.10.39", - "resolved": "https://registry.npmjs.org/@types/node/-/node-8.10.39.tgz", - "integrity": "sha512-rE7fktr02J8ybFf6eysife+WF+L4sAHWzw09DgdCebEu+qDwMvv4zl6Bc+825ttGZP73kCKxa3dhJOoGJ8+5mA==" - }, - "@types/range-parser": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.3.tgz", - "integrity": "sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA==" - }, - "@types/request": { - "version": "2.48.1", - "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.1.tgz", - "integrity": "sha512-ZgEZ1TiD+KGA9LiAAPPJL68Id2UWfeSO62ijSXZjFJArVV+2pKcsVHmrcu+1oiE3q6eDGiFiSolRc4JHoerBBg==", - "optional": true, - "requires": { - "@types/caseless": "0.12.1", - "@types/form-data": "2.2.1", - "@types/node": "8.10.39", - "@types/tough-cookie": "2.3.4" - } - }, - "@types/serve-static": { - "version": "1.13.2", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.13.2.tgz", - "integrity": "sha512-/BZ4QRLpH/bNYgZgwhKEh+5AsboDBcUdlBYgzoLX0fpj3Y2gp6EApyOlM3bK53wQS/OE1SrdSYBAbux2D1528Q==", - "requires": { - "@types/express-serve-static-core": "4.16.0", - "@types/mime": "2.0.0" - } - }, - "@types/tough-cookie": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-2.3.4.tgz", - "integrity": "sha512-Set5ZdrAaKI/qHdFlVMgm/GsAv/wkXhSTuZFkJ+JI7HK+wIkIlOaUXSXieIvJ0+OvGIqtREFoE+NHJtEq0gtEw==", - "optional": true - }, - "accepts": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", - "integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=", - "requires": { - "mime-types": "2.1.21", - "negotiator": "0.6.1" - } - }, - "acorn": { - "version": "5.7.3", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.3.tgz", - "integrity": "sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw==" - }, - "acorn-es7-plugin": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/acorn-es7-plugin/-/acorn-es7-plugin-1.1.7.tgz", - "integrity": "sha1-8u4fMiipDurRJF+asZIusucdM2s=" - }, - "ajv": { - "version": "6.6.2", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.6.2.tgz", - "integrity": "sha512-FBHEW6Jf5TB9MGBgUUA9XHkTbjXYfAUjY43ACMfmdMRHniyoMHjHjzD50OK8LGDWQwp4rWEsIq5kEqq7rvIM1g==", - "requires": { - "fast-deep-equal": "2.0.1", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.4.1", - "uri-js": "4.2.2" - } - }, - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" - }, - "arr-diff": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=" - }, - "arr-flatten": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", - "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==" - }, - "arr-union": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", - "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=" - }, - "array-filter": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/array-filter/-/array-filter-1.0.0.tgz", - "integrity": "sha1-uveeYubvTCpMC4MSMtr/7CUfnYM=" - }, - "array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" - }, - "array-union": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", - "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", - "requires": { - "array-uniq": "1.0.3" - } - }, - "array-uniq": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", - "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=" - }, - "array-unique": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", - "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=" - }, - "arrify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", - "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=" - }, - "ascli": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/ascli/-/ascli-1.0.1.tgz", - "integrity": "sha1-vPpZdKYvGOgcq660lzKrSoj5Brw=", - "optional": true, - "requires": { - "colour": "0.7.1", - "optjs": "3.2.2" - } - }, - "asn1": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", - "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", - "requires": { - "safer-buffer": "2.1.2" - } - }, - "assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" - }, - "assign-symbols": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", - "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=" - }, - "async": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", - "integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", - "requires": { - "lodash": "4.17.11" - } - }, - "asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" - }, - "atob": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", - "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==" - }, - "aws-sign2": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", - "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=" - }, - "aws4": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", - "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==" - }, - "axios": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.18.0.tgz", - "integrity": "sha1-MtU+SFHv3AoRmTts0AB4nXDAUQI=", - "requires": { - "follow-redirects": "1.6.1", - "is-buffer": "1.1.6" - } - }, - "balanced-match": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" - }, - "base": { - "version": "0.11.2", - "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", - "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", - "requires": { - "cache-base": "1.0.1", - "class-utils": "0.3.6", - "component-emitter": "1.2.1", - "define-property": "1.0.0", - "isobject": "3.0.1", - "mixin-deep": "1.3.1", - "pascalcase": "0.1.1" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "requires": { - "is-descriptor": "1.0.2" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" - } - } - } - }, - "bcrypt-pbkdf": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", - "requires": { - "tweetnacl": "0.14.5" - } - }, - "body-parser": { - "version": "1.18.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz", - "integrity": "sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=", - "requires": { - "bytes": "3.0.0", - "content-type": "1.0.4", - "debug": "2.6.9", - "depd": "1.1.2", - "http-errors": "1.6.3", - "iconv-lite": "0.4.23", - "on-finished": "2.3.0", - "qs": "6.5.2", - "raw-body": "2.3.3", - "type-is": "1.6.16" - } - }, - "brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "braces": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", - "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", - "requires": { - "arr-flatten": "1.1.0", - "array-unique": "0.3.2", - "extend-shallow": "2.0.1", - "fill-range": "4.0.0", - "isobject": "3.0.1", - "repeat-element": "1.1.3", - "snapdragon": "0.8.2", - "snapdragon-node": "2.1.1", - "split-string": "3.1.0", - "to-regex": "3.0.2" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "buffer-equal-constant-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" - }, - "buffer-from": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", - "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==" - }, - "bun": { - "version": "0.0.12", - "resolved": "https://registry.npmjs.org/bun/-/bun-0.0.12.tgz", - "integrity": "sha512-Toms18J9DqnT+IfWkwxVTB2EaBprHvjlMWrTIsfX4xbu3ZBqVBwrERU0em1IgtRe04wT+wJxMlKHZok24hrcSQ==", - "optional": true, - "requires": { - "readable-stream": "1.0.34" - } - }, - "bytebuffer": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/bytebuffer/-/bytebuffer-5.0.1.tgz", - "integrity": "sha1-WC7qSxqHO20CCkjVjfhfC7ps/d0=", - "optional": true, - "requires": { - "long": "3.2.0" - }, - "dependencies": { - "long": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/long/-/long-3.2.0.tgz", - "integrity": "sha1-2CG3E4yhy1gcFymQ7xTbIAtcR0s=", - "optional": true - } - } - }, - "bytes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", - "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=" - }, - "cache-base": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", - "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", - "requires": { - "collection-visit": "1.0.0", - "component-emitter": "1.2.1", - "get-value": "2.0.6", - "has-value": "1.0.0", - "isobject": "3.0.1", - "set-value": "2.0.0", - "to-object-path": "0.3.0", - "union-value": "1.0.0", - "unset-value": "1.0.0" - } - }, - "call-me-maybe": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.1.tgz", - "integrity": "sha1-JtII6onje1y95gJQoV8DHBak1ms=" - }, - "call-signature": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/call-signature/-/call-signature-0.0.2.tgz", - "integrity": "sha1-qEq8glpV70yysCi9dOIFpluaSZY=" - }, - "camelcase": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz", - "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=", - "optional": true - }, - "capture-stack-trace": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/capture-stack-trace/-/capture-stack-trace-1.0.1.tgz", - "integrity": "sha512-mYQLZnx5Qt1JgB1WEiMCf2647plpGeQ2NMR/5L0HNZzGQo4fuSPnK+wjfPnKZV0aiJDgzmWqqkV/g7JD+DW0qw==" - }, - "caseless": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", - "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" - }, - "class-utils": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", - "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", - "requires": { - "arr-union": "3.1.0", - "define-property": "0.2.5", - "isobject": "3.0.1", - "static-extend": "0.1.2" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "requires": { - "is-descriptor": "0.1.6" - } - } - } - }, - "cliui": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", - "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", - "optional": true, - "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wrap-ansi": "2.1.0" - } - }, - "code-point-at": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", - "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=" - }, - "collection-visit": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", - "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", - "requires": { - "map-visit": "1.0.0", - "object-visit": "1.0.1" - } - }, - "colour": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/colour/-/colour-0.7.1.tgz", - "integrity": "sha1-nLFpkX7F0SwHNtPoaFdG3xyt93g=", - "optional": true - }, - "combined-stream": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", - "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", - "requires": { - "delayed-stream": "1.0.0" - } - }, - "component-emitter": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", - "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=" - }, - "compressible": { - "version": "2.0.15", - "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.15.tgz", - "integrity": "sha512-4aE67DL33dSW9gw4CI2H/yTxqHLNcxp0yS6jB+4h+wr3e43+1z7vm0HU9qXOH8j+qjKuL8+UtkOxYQSMq60Ylw==", - "optional": true, - "requires": { - "mime-db": "1.37.0" - } - }, - "concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" - }, - "concat-stream": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "requires": { - "buffer-from": "1.1.1", - "inherits": "2.0.3", - "readable-stream": "2.3.6", - "typedarray": "0.0.6" - }, - "dependencies": { - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "readable-stream": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "2.0.0", - "safe-buffer": "5.1.2", - "string_decoder": "1.1.1", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "requires": { - "safe-buffer": "5.1.2" - } - } - } - }, - "configstore": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.2.tgz", - "integrity": "sha512-vtv5HtGjcYUgFrXc6Kx747B83MRRVS5R1VTEQoXvuP+kMI+if6uywV0nDGoiydJRy4yk7h9od5Og0kxx4zUXmw==", - "optional": true, - "requires": { - "dot-prop": "4.2.0", - "graceful-fs": "4.1.15", - "make-dir": "1.3.0", - "unique-string": "1.0.0", - "write-file-atomic": "2.3.0", - "xdg-basedir": "3.0.0" - } - }, - "content-disposition": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", - "integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=" - }, - "content-type": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" - }, - "cookie": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", - "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=" - }, - "cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" - }, - "copy-descriptor": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", - "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=" - }, - "core-js": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.1.tgz", - "integrity": "sha512-L72mmmEayPJBejKIWe2pYtGis5r0tQ5NaJekdhyXgeMQTpJoBsH0NL4ElY2LfSoV15xeQWKQ+XTTOZdyero5Xg==" - }, - "core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" - }, - "cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "requires": { - "object-assign": "4.1.1", - "vary": "1.1.2" - } - }, - "create-error-class": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz", - "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", - "requires": { - "capture-stack-trace": "1.0.1" - } - }, - "crypto-random-string": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-1.0.0.tgz", - "integrity": "sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4=", - "optional": true - }, - "dashdash": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", - "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", - "requires": { - "assert-plus": "1.0.0" - } - }, - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "requires": { - "ms": "2.0.0" - } - }, - "decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", - "optional": true - }, - "decode-uri-component": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", - "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=" - }, - "deep-equal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", - "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=", - "optional": true - }, - "define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "requires": { - "object-keys": "1.0.12" - } - }, - "define-property": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", - "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", - "requires": { - "is-descriptor": "1.0.2", - "isobject": "3.0.1" - }, - "dependencies": { - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" - } - } - } - }, - "delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" - }, - "depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" - }, - "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" - }, - "diff-match-patch": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.4.tgz", - "integrity": "sha512-Uv3SW8bmH9nAtHKaKSanOQmj2DnlH65fUpcrMdfdaOxUG02QQ4YGZ8AE7kKOMisF7UqvOlGKVYWRvezdncW9lg==" - }, - "dir-glob": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-2.0.0.tgz", - "integrity": "sha512-37qirFDz8cA5fimp9feo43fSuRo2gHwaIn6dXL8Ber1dGwUosDrGZeCCXq57WnIqE4aQ+u3eQZzsk1yOzhdwag==", - "requires": { - "arrify": "1.0.1", - "path-type": "3.0.0" - } - }, - "dom-storage": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/dom-storage/-/dom-storage-2.1.0.tgz", - "integrity": "sha512-g6RpyWXzl0RR6OTElHKBl7nwnK87GUyZMYC7JWsB/IA73vpqK2K6LT39x4VepLxlSsWBFrPVLnsSR5Jyty0+2Q==" - }, - "dot-prop": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-4.2.0.tgz", - "integrity": "sha512-tUMXrxlExSW6U2EXiiKGSBVdYgtV8qlHL+C10TsW4PURY/ic+eaysnSkwB4kA/mBlCyy/IKDJ+Lc3wbWeaXtuQ==", - "optional": true, - "requires": { - "is-obj": "1.0.1" - } - }, - "duplexify": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.6.1.tgz", - "integrity": "sha512-vM58DwdnKmty+FSPzT14K9JXb90H+j5emaR4KYbr2KTIz00WHGbWOe5ghQTx233ZCLZtrGDALzKwcjEtSt35mA==", - "requires": { - "end-of-stream": "1.4.1", - "inherits": "2.0.3", - "readable-stream": "2.3.6", - "stream-shift": "1.0.0" - }, - "dependencies": { - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "readable-stream": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "2.0.0", - "safe-buffer": "5.1.2", - "string_decoder": "1.1.1", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "requires": { - "safe-buffer": "5.1.2" - } - } - } - }, - "eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" - }, - "ecc-jsbn": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", - "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", - "requires": { - "jsbn": "0.1.1", - "safer-buffer": "2.1.2" - } - }, - "ecdsa-sig-formatter": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.10.tgz", - "integrity": "sha1-HFlQAPBKiJffuFAAiSoPTDOvhsM=", - "requires": { - "safe-buffer": "5.1.2" - } - }, - "ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" - }, - "empower": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/empower/-/empower-1.3.1.tgz", - "integrity": "sha512-uB6/ViBaawOO/uujFADTK3SqdYlxYNn+N4usK9MRKZ4Hbn/1QSy8k2PezxCA2/+JGbF8vd/eOfghZ90oOSDZCA==", - "requires": { - "core-js": "2.6.1", - "empower-core": "1.2.0" - } - }, - "empower-core": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/empower-core/-/empower-core-1.2.0.tgz", - "integrity": "sha512-g6+K6Geyc1o6FdXs9HwrXleCFan7d66G5xSCfSF7x1mJDCes6t0om9lFQG3zOrzh3Bkb/45N0cZ5Gqsf7YrzGQ==", - "requires": { - "call-signature": "0.0.2", - "core-js": "2.6.1" - } - }, - "encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" - }, - "end-of-stream": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", - "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", - "requires": { - "once": "1.4.0" - } - }, - "ent": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz", - "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=", - "optional": true - }, - "escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" - }, - "espurify": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/espurify/-/espurify-1.8.1.tgz", - "integrity": "sha512-ZDko6eY/o+D/gHCWyHTU85mKDgYcS4FJj7S+YD6WIInm7GQ6AnOjmcL4+buFV/JOztVLELi/7MmuGU5NHta0Mg==", - "requires": { - "core-js": "2.6.1" - } - }, - "estraverse": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", - "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=" - }, - "etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" - }, - "expand-brackets": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", - "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", - "requires": { - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "posix-character-classes": "0.1.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "requires": { - "is-descriptor": "0.1.6" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "express": { - "version": "4.16.4", - "resolved": "https://registry.npmjs.org/express/-/express-4.16.4.tgz", - "integrity": "sha512-j12Uuyb4FMrd/qQAm6uCHAkPtO8FDTRJZBDd5D2KOL2eLaz1yUNdUB/NOIyq0iU4q4cFarsUCrnFDPBcnksuOg==", - "requires": { - "accepts": "1.3.5", - "array-flatten": "1.1.1", - "body-parser": "1.18.3", - "content-disposition": "0.5.2", - "content-type": "1.0.4", - "cookie": "0.3.1", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "1.1.2", - "encodeurl": "1.0.2", - "escape-html": "1.0.3", - "etag": "1.8.1", - "finalhandler": "1.1.1", - "fresh": "0.5.2", - "merge-descriptors": "1.0.1", - "methods": "1.1.2", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "path-to-regexp": "0.1.7", - "proxy-addr": "2.0.4", - "qs": "6.5.2", - "range-parser": "1.2.0", - "safe-buffer": "5.1.2", - "send": "0.16.2", - "serve-static": "1.13.2", - "setprototypeof": "1.1.0", - "statuses": "1.4.0", - "type-is": "1.6.16", - "utils-merge": "1.0.1", - "vary": "1.1.2" - } - }, - "extend": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", - "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" - }, - "extend-shallow": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", - "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", - "requires": { - "assign-symbols": "1.0.0", - "is-extendable": "1.0.1" - }, - "dependencies": { - "is-extendable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", - "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", - "requires": { - "is-plain-object": "2.0.4" - } - } - } - }, - "extglob": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", - "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", - "requires": { - "array-unique": "0.3.2", - "define-property": "1.0.0", - "expand-brackets": "2.1.4", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "requires": { - "is-descriptor": "1.0.2" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" - } - } - } - }, - "extsprintf": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", - "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" - }, - "fast-deep-equal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", - "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=" - }, - "fast-glob": { - "version": "2.2.4", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-2.2.4.tgz", - "integrity": "sha512-FjK2nCGI/McyzgNtTESqaWP3trPvHyRyoyY70hxjc3oKPNmDe8taohLZpoVKoUjW85tbU5txaYUZCNtVzygl1g==", - "requires": { - "@mrmlnc/readdir-enhanced": "2.2.1", - "@nodelib/fs.stat": "1.1.3", - "glob-parent": "3.1.0", - "is-glob": "4.0.0", - "merge2": "1.2.3", - "micromatch": "3.1.10" - } - }, - "fast-json-stable-stringify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", - "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=" - }, - "faye-websocket": { - "version": "0.11.1", - "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.1.tgz", - "integrity": "sha1-8O/hjE9W5PQK/H4Gxxn9XuYYjzg=", - "requires": { - "websocket-driver": "0.7.0" - } - }, - "fill-range": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", - "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", - "requires": { - "extend-shallow": "2.0.1", - "is-number": "3.0.0", - "repeat-string": "1.6.1", - "to-regex-range": "2.1.1" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "finalhandler": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz", - "integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==", - "requires": { - "debug": "2.6.9", - "encodeurl": "1.0.2", - "escape-html": "1.0.3", - "on-finished": "2.3.0", - "parseurl": "1.3.2", - "statuses": "1.4.0", - "unpipe": "1.0.0" - } - }, - "firebase-admin": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/firebase-admin/-/firebase-admin-6.0.0.tgz", - "integrity": "sha512-ai7ensTAZx9iF6z/lMn7JzFJYSl6+uXYm53GGhWlph+npnQli10FF9YB97OjcVUghapDEWzmb6J0VMtB965nsw==", - "requires": { - "@firebase/app": "0.3.5", - "@firebase/database": "0.3.8", - "@google-cloud/firestore": "0.16.1", - "@google-cloud/storage": "1.7.0", - "@types/google-cloud__storage": "1.7.2", - "@types/node": "8.10.39", - "jsonwebtoken": "8.1.0", - "node-forge": "0.7.4" - } - }, - "firebase-functions": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/firebase-functions/-/firebase-functions-2.1.0.tgz", - "integrity": "sha512-gvWjfIu/q0jXSE/4JY+6XZyJWVzk0TeGLJAfKE4Y7W/cUxkycogc7EIBJSEMdHnxFAD3GE6VgCrhtTTmUud6Sw==", - "requires": { - "@types/cors": "2.8.4", - "@types/express": "4.16.0", - "@types/jsonwebtoken": "7.2.8", - "@types/lodash": "4.14.119", - "cors": "2.8.5", - "express": "4.16.4", - "jsonwebtoken": "8.4.0", - "lodash": "4.17.11" - }, - "dependencies": { - "jsonwebtoken": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.4.0.tgz", - "integrity": "sha512-coyXjRTCy0pw5WYBpMvWOMN+Kjaik2MwTUIq9cna/W7NpO9E+iYbumZONAz3hcr+tXFJECoQVrtmIoC3Oz0gvg==", - "requires": { - "jws": "3.1.5", - "lodash.includes": "4.3.0", - "lodash.isboolean": "3.0.3", - "lodash.isinteger": "4.0.4", - "lodash.isnumber": "3.0.3", - "lodash.isplainobject": "4.0.6", - "lodash.isstring": "4.0.1", - "lodash.once": "4.1.1", - "ms": "2.1.1" - } - }, - "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" - } - } - }, - "follow-redirects": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.6.1.tgz", - "integrity": "sha512-t2JCjbzxQpWvbhts3l6SH1DKzSrx8a+SsaVf4h6bG4kOXUuPYS/kg2Lr4gQSb7eemaHqJkOThF1BGyjlUkO1GQ==", - "requires": { - "debug": "3.1.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - } - } - }, - "for-in": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", - "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=" - }, - "forever-agent": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", - "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=" - }, - "form-data": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", - "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", - "requires": { - "asynckit": "0.4.0", - "combined-stream": "1.0.7", - "mime-types": "2.1.21" - } - }, - "forwarded": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", - "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" - }, - "fragment-cache": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", - "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", - "requires": { - "map-cache": "0.2.2" - } - }, - "fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" - }, - "fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" - }, - "functional-red-black-tree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", - "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", - "optional": true - }, - "gcp-metadata": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-0.6.3.tgz", - "integrity": "sha512-MSmczZctbz91AxCvqp9GHBoZOSbJKAICV7Ow/AIWSJZRrRchUd5NL1b2P4OfP+4m490BEUPhhARfpHdqCxuCvg==", - "requires": { - "axios": "0.18.0", - "extend": "3.0.2", - "retry-axios": "0.3.2" - } - }, - "gcs-resumable-upload": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/gcs-resumable-upload/-/gcs-resumable-upload-0.10.2.tgz", - "integrity": "sha1-fymz7iPc7EFwNnwHEUGCScZgVF8=", - "optional": true, - "requires": { - "configstore": "3.1.2", - "google-auto-auth": "0.10.1", - "pumpify": "1.5.1", - "request": "2.88.0", - "stream-events": "1.0.5" - } - }, - "get-value": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", - "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=" - }, - "getpass": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", - "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", - "requires": { - "assert-plus": "1.0.0" - } - }, - "glob": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", - "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - }, - "glob-parent": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", - "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", - "requires": { - "is-glob": "3.1.0", - "path-dirname": "1.0.2" - }, - "dependencies": { - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "requires": { - "is-extglob": "2.1.1" - } - } - } - }, - "glob-to-regexp": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.3.0.tgz", - "integrity": "sha1-jFoUlNIGbFcMw7/kSWF1rMTVAqs=" - }, - "globby": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-8.0.1.tgz", - "integrity": "sha512-oMrYrJERnKBLXNLVTqhm3vPEdJ/b2ZE28xN4YARiix1NOIOBPEpOUnm844K1iu/BkphCaf2WNFwMszv8Soi1pw==", - "requires": { - "array-union": "1.0.2", - "dir-glob": "2.0.0", - "fast-glob": "2.2.4", - "glob": "7.1.3", - "ignore": "3.3.10", - "pify": "3.0.0", - "slash": "1.0.0" - } - }, - "google-auth-library": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-1.6.1.tgz", - "integrity": "sha512-jYiWC8NA9n9OtQM7ANn0Tk464do9yhKEtaJ72pKcaBiEwn4LwcGYIYOfwtfsSm3aur/ed3tlSxbmg24IAT6gAg==", - "requires": { - "axios": "0.18.0", - "gcp-metadata": "0.6.3", - "gtoken": "2.3.0", - "jws": "3.1.5", - "lodash.isstring": "4.0.1", - "lru-cache": "4.1.5", - "retry-axios": "0.3.2" - } - }, - "google-auto-auth": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/google-auto-auth/-/google-auto-auth-0.10.1.tgz", - "integrity": "sha512-iIqSbY7Ypd32mnHGbYctp80vZzXoDlvI9gEfvtl3kmyy5HzOcrZCIGCBdSlIzRsg7nHpQiHE3Zl6Ycur6TSodQ==", - "requires": { - "async": "2.6.1", - "gcp-metadata": "0.6.3", - "google-auth-library": "1.6.1", - "request": "2.88.0" - } - }, - "google-gax": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-0.18.0.tgz", - "integrity": "sha512-cF2s3aTw1cWDHsjaYfIizJZT0KJF0FSM3laiCX4O/K0ZcdmeE9PitG2bxRH+dY+Sz094//m+JoH1hBtSyOf67A==", - "optional": true, - "requires": { - "@grpc/proto-loader": "0.3.0", - "duplexify": "3.6.1", - "extend": "3.0.2", - "globby": "8.0.1", - "google-auth-library": "1.6.1", - "google-proto-files": "0.16.1", - "grpc": "1.17.0", - "is-stream-ended": "0.1.4", - "lodash": "4.17.11", - "protobufjs": "6.8.8", - "retry-request": "4.0.0", - "through2": "2.0.5" - } - }, - "google-p12-pem": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-1.0.3.tgz", - "integrity": "sha512-KGnAiMMWaJp4j4tYVvAjfP3wCKZRLv9M1Nir2wRRNWUYO7j1aX8O9Qgz+a8/EQ5rAvuo4SIu79n6SIdkNl7Msg==", - "requires": { - "node-forge": "0.7.6", - "pify": "4.0.1" - }, - "dependencies": { - "node-forge": { - "version": "0.7.6", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.7.6.tgz", - "integrity": "sha512-sol30LUpz1jQFBjOKwbjxijiE3b6pjd74YwfD0fJOKPjF+fONKb2Yg8rYgS6+bK6VDl+/wfr4IYpC7jDzLUIfw==" - }, - "pify": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", - "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==" - } - } - }, - "google-proto-files": { - "version": "0.16.1", - "resolved": "https://registry.npmjs.org/google-proto-files/-/google-proto-files-0.16.1.tgz", - "integrity": "sha512-ykdhaYDiU/jlyrkzZDPemraKwVIgLT31XMHVNSJW//R9VED56hqSDRMx1Jlxbf0O4iDZnBWQ0JQLHbM2r5+wuA==", - "requires": { - "globby": "8.0.1", - "power-assert": "1.6.1", - "protobufjs": "6.8.8" - } - }, - "graceful-fs": { - "version": "4.1.15", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", - "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==" - }, - "grpc": { - "version": "1.17.0", - "resolved": "https://registry.npmjs.org/grpc/-/grpc-1.17.0.tgz", - "integrity": "sha512-5zb5ilwHlsiWfE2Abq/IN5SkHQ2zi4QF/u9Gewcw5DO3y+hGTtzZUiMK52MX3YZHAIRjqxDcO3fx0jLhPjT8Zw==", - "optional": true, - "requires": { - "lodash.camelcase": "4.3.0", - "lodash.clone": "4.5.0", - "nan": "2.12.1", - "node-pre-gyp": "0.12.0", - "protobufjs": "5.0.3" - }, - "dependencies": { - "abbrev": { - "version": "1.1.1", - "bundled": true, - "optional": true - }, - "ansi-regex": { - "version": "2.1.1", - "bundled": true - }, - "aproba": { - "version": "1.2.0", - "bundled": true, - "optional": true - }, - "are-we-there-yet": { - "version": "1.1.5", - "bundled": true, - "optional": true, - "requires": { - "delegates": "1.0.0", - "readable-stream": "2.3.6" - } - }, - "balanced-match": { - "version": "1.0.0", - "bundled": true - }, - "brace-expansion": { - "version": "1.1.11", - "bundled": true, - "requires": { - "balanced-match": "1.0.0", - "concat-map": "0.0.1" - } - }, - "chownr": { - "version": "1.1.1", - "bundled": true, - "optional": true - }, - "code-point-at": { - "version": "1.1.0", - "bundled": true - }, - "concat-map": { - "version": "0.0.1", - "bundled": true - }, - "console-control-strings": { - "version": "1.1.0", - "bundled": true - }, - "core-util-is": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "debug": { - "version": "2.6.9", - "bundled": true, - "optional": true, - "requires": { - "ms": "2.0.0" - } - }, - "deep-extend": { - "version": "0.6.0", - "bundled": true, - "optional": true - }, - "delegates": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "detect-libc": { - "version": "1.0.3", - "bundled": true, - "optional": true - }, - "fs-minipass": { - "version": "1.2.5", - "bundled": true, - "optional": true, - "requires": { - "minipass": "2.3.5" - } - }, - "fs.realpath": { - "version": "1.0.0", - "bundled": true - }, - "gauge": { - "version": "2.7.4", - "bundled": true, - "optional": true, - "requires": { - "aproba": "1.2.0", - "console-control-strings": "1.1.0", - "has-unicode": "2.0.1", - "object-assign": "4.1.1", - "signal-exit": "3.0.1", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wide-align": "1.1.3" - } - }, - "glob": { - "version": "7.1.3", - "bundled": true, - "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" - } - }, - "has-unicode": { - "version": "2.0.1", - "bundled": true, - "optional": true - }, - "iconv-lite": { - "version": "0.4.24", - "bundled": true, - "optional": true, - "requires": { - "safer-buffer": "2.1.2" - } - }, - "ignore-walk": { - "version": "3.0.1", - "bundled": true, - "optional": true, - "requires": { - "minimatch": "3.0.4" - } - }, - "inflight": { - "version": "1.0.6", - "bundled": true, - "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" - } - }, - "inherits": { - "version": "2.0.3", - "bundled": true - }, - "ini": { - "version": "1.3.5", - "bundled": true, - "optional": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "bundled": true, - "requires": { - "number-is-nan": "1.0.1" - } - }, - "isarray": { - "version": "1.0.0", - "bundled": true, - "optional": true - }, - "minimatch": { - "version": "3.0.4", - "bundled": true, - "requires": { - "brace-expansion": "1.1.11" - } - }, - "minimist": { - "version": "1.2.0", - "bundled": true, - "optional": true - }, - "minipass": { - "version": "2.3.5", - "bundled": true, - "requires": { - "safe-buffer": "5.1.2", - "yallist": "3.0.3" - } - }, - "minizlib": { - "version": "1.2.1", - "bundled": true, - "optional": true, - "requires": { - "minipass": "2.3.5" - } - }, - "mkdirp": { - "version": "0.5.1", - "bundled": true, - "requires": { - "minimist": "0.0.8" - }, - "dependencies": { - "minimist": { - "version": "0.0.8", - "bundled": true - } - } - }, - "ms": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "needle": { - "version": "2.2.4", - "bundled": true, - "optional": true, - "requires": { - "debug": "2.6.9", - "iconv-lite": "0.4.24", - "sax": "1.2.4" - } - }, - "node-pre-gyp": { - "version": "0.12.0", - "bundled": true, - "optional": true, - "requires": { - "detect-libc": "1.0.3", - "mkdirp": "0.5.1", - "needle": "2.2.4", - "nopt": "4.0.1", - "npm-packlist": "1.1.12", - "npmlog": "4.1.2", - "rc": "1.2.8", - "rimraf": "2.6.2", - "semver": "5.6.0", - "tar": "4.4.8" - } - }, - "nopt": { - "version": "4.0.1", - "bundled": true, - "optional": true, - "requires": { - "abbrev": "1.1.1", - "osenv": "0.1.5" - } - }, - "npm-bundled": { - "version": "1.0.5", - "bundled": true, - "optional": true - }, - "npm-packlist": { - "version": "1.1.12", - "bundled": true, - "optional": true, - "requires": { - "ignore-walk": "3.0.1", - "npm-bundled": "1.0.5" - } - }, - "npmlog": { - "version": "4.1.2", - "bundled": true, - "optional": true, - "requires": { - "are-we-there-yet": "1.1.5", - "console-control-strings": "1.1.0", - "gauge": "2.7.4", - "set-blocking": "2.0.0" - } - }, - "number-is-nan": { - "version": "1.0.1", - "bundled": true - }, - "object-assign": { - "version": "4.1.1", - "bundled": true, - "optional": true - }, - "once": { - "version": "1.4.0", - "bundled": true, - "requires": { - "wrappy": "1.0.2" - } - }, - "os-homedir": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "os-tmpdir": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "osenv": { - "version": "0.1.5", - "bundled": true, - "optional": true, - "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" - } - }, - "path-is-absolute": { - "version": "1.0.1", - "bundled": true - }, - "process-nextick-args": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "protobufjs": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-5.0.3.tgz", - "integrity": "sha512-55Kcx1MhPZX0zTbVosMQEO5R6/rikNXd9b6RQK4KSPcrSIIwoXTtebIczUrXlwaSrbz4x8XUVThGPob1n8I4QA==", - "optional": true, - "requires": { - "ascli": "1.0.1", - "bytebuffer": "5.0.1", - "glob": "7.1.3", - "yargs": "3.32.0" - } - }, - "rc": { - "version": "1.2.8", - "bundled": true, - "optional": true, - "requires": { - "deep-extend": "0.6.0", - "ini": "1.3.5", - "minimist": "1.2.0", - "strip-json-comments": "2.0.1" - } - }, - "readable-stream": { - "version": "2.3.6", - "bundled": true, - "optional": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "2.0.0", - "safe-buffer": "5.1.2", - "string_decoder": "1.1.1", - "util-deprecate": "1.0.2" - } - }, - "rimraf": { - "version": "2.6.2", - "bundled": true, - "optional": true, - "requires": { - "glob": "7.1.3" - } - }, - "safe-buffer": { - "version": "5.1.2", - "bundled": true - }, - "safer-buffer": { - "version": "2.1.2", - "bundled": true, - "optional": true - }, - "sax": { - "version": "1.2.4", - "bundled": true, - "optional": true - }, - "semver": { - "version": "5.6.0", - "bundled": true, - "optional": true - }, - "set-blocking": { - "version": "2.0.0", - "bundled": true, - "optional": true - }, - "signal-exit": { - "version": "3.0.1", - "bundled": true, - "optional": true - }, - "string-width": { - "version": "1.0.2", - "bundled": true, - "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" - } - }, - "string_decoder": { - "version": "1.1.1", - "bundled": true, - "optional": true, - "requires": { - "safe-buffer": "5.1.2" - } - }, - "strip-ansi": { - "version": "3.0.1", - "bundled": true, - "requires": { - "ansi-regex": "2.1.1" - } - }, - "strip-json-comments": { - "version": "2.0.1", - "bundled": true, - "optional": true - }, - "tar": { - "version": "4.4.8", - "bundled": true, - "optional": true, - "requires": { - "chownr": "1.1.1", - "fs-minipass": "1.2.5", - "minipass": "2.3.5", - "minizlib": "1.2.1", - "mkdirp": "0.5.1", - "safe-buffer": "5.1.2", - "yallist": "3.0.3" - } - }, - "util-deprecate": { - "version": "1.0.2", - "bundled": true, - "optional": true - }, - "wide-align": { - "version": "1.1.3", - "bundled": true, - "optional": true, - "requires": { - "string-width": "1.0.2" - } - }, - "wrappy": { - "version": "1.0.2", - "bundled": true - }, - "yallist": { - "version": "3.0.3", - "bundled": true - } - } - }, - "gtoken": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-2.3.0.tgz", - "integrity": "sha512-Jc9/8mV630cZE9FC5tIlJCZNdUjwunvlwOtCz6IDlaiB4Sz68ki29a1+q97sWTnTYroiuF9B135rod9zrQdHLw==", - "requires": { - "axios": "0.18.0", - "google-p12-pem": "1.0.3", - "jws": "3.1.5", - "mime": "2.4.0", - "pify": "3.0.0" - } - }, - "har-schema": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", - "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=" - }, - "har-validator": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", - "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", - "requires": { - "ajv": "6.6.2", - "har-schema": "2.0.0" - } - }, - "has-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", - "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", - "requires": { - "get-value": "2.0.6", - "has-values": "1.0.0", - "isobject": "3.0.1" - } - }, - "has-values": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", - "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", - "requires": { - "is-number": "3.0.0", - "kind-of": "4.0.0" - }, - "dependencies": { - "kind-of": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", - "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "hash-stream-validation": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/hash-stream-validation/-/hash-stream-validation-0.2.1.tgz", - "integrity": "sha1-7Mm5l7IYvluzEphii7gHhptz3NE=", - "optional": true, - "requires": { - "through2": "2.0.5" - } - }, - "http-errors": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", - "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", - "requires": { - "depd": "1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.0", - "statuses": "1.4.0" - } - }, - "http-parser-js": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.0.tgz", - "integrity": "sha512-cZdEF7r4gfRIq7ezX9J0T+kQmJNOub71dWbgAXVHDct80TKP4MCETtZQ31xyv38UwgzkWPYF/Xc0ge55dW9Z9w==" - }, - "http-signature": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", - "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", - "requires": { - "assert-plus": "1.0.0", - "jsprim": "1.4.1", - "sshpk": "1.16.0" - } - }, - "iconv-lite": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz", - "integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==", - "requires": { - "safer-buffer": "2.1.2" - } - }, - "ignore": { - "version": "3.3.10", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", - "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==" - }, - "imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", - "optional": true - }, - "indexof": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", - "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=" - }, - "inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", - "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" - } - }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, - "invert-kv": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz", - "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", - "optional": true - }, - "ipaddr.js": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz", - "integrity": "sha1-6qM9bd16zo9/b+DJygRA5wZzix4=" - }, - "is": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/is/-/is-3.3.0.tgz", - "integrity": "sha512-nW24QBoPcFGGHJGUwnfpI7Yc5CdqWNdsyHQszVE/z2pKHXzh7FZ5GWhJqSyaQ9wMkQnsTx+kAI8bHlCX4tKdbg==" - }, - "is-accessor-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", - "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" - }, - "is-data-descriptor": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", - "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-descriptor": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", - "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", - "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" - }, - "dependencies": { - "kind-of": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", - "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==" - } - } - }, - "is-extendable": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", - "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=" - }, - "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "requires": { - "number-is-nan": "1.0.1" - } - }, - "is-glob": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.0.tgz", - "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", - "requires": { - "is-extglob": "2.1.1" - } - }, - "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "is-obj": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", - "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", - "optional": true - }, - "is-plain-object": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", - "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", - "requires": { - "isobject": "3.0.1" - } - }, - "is-stream-ended": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/is-stream-ended/-/is-stream-ended-0.1.4.tgz", - "integrity": "sha512-xj0XPvmr7bQFTvirqnFr50o0hQIh6ZItDqloxt5aJrR4NQsYeSsyFQERYGCAzfindAcnKjINnwEEgLx4IqVzQw==", - "optional": true - }, - "is-typedarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", - "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" - }, - "is-windows": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", - "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==" - }, - "isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "optional": true - }, - "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" - }, - "isstream": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", - "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" - }, - "jsbn": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", - "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" - }, - "json-schema": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", - "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=" - }, - "json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" - }, - "json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" - }, - "jsonwebtoken": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.1.0.tgz", - "integrity": "sha1-xjl80uX9WD1lwAeoPce7eOaYK4M=", - "requires": { - "jws": "3.1.5", - "lodash.includes": "4.3.0", - "lodash.isboolean": "3.0.3", - "lodash.isinteger": "4.0.4", - "lodash.isnumber": "3.0.3", - "lodash.isplainobject": "4.0.6", - "lodash.isstring": "4.0.1", - "lodash.once": "4.1.1", - "ms": "2.0.0", - "xtend": "4.0.1" - } - }, - "jsprim": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", - "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", - "requires": { - "assert-plus": "1.0.0", - "extsprintf": "1.3.0", - "json-schema": "0.2.3", - "verror": "1.10.0" - } - }, - "jwa": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.1.6.tgz", - "integrity": "sha512-tBO/cf++BUsJkYql/kBbJroKOgHWEigTKBAjjBEmrMGYd1QMBC74Hr4Wo2zCZw6ZrVhlJPvoMrkcOnlWR/DJfw==", - "requires": { - "buffer-equal-constant-time": "1.0.1", - "ecdsa-sig-formatter": "1.0.10", - "safe-buffer": "5.1.2" - } - }, - "jws": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/jws/-/jws-3.1.5.tgz", - "integrity": "sha512-GsCSexFADNQUr8T5HPJvayTjvPIfoyJPtLQBwn5a4WZQchcrPMPMAWcC1AzJVRDKyD6ZPROPAxgv6rfHViO4uQ==", - "requires": { - "jwa": "1.1.6", - "safe-buffer": "5.1.2" - } - }, - "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==" - }, - "lcid": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz", - "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", - "optional": true, - "requires": { - "invert-kv": "1.0.0" - } - }, - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==" - }, - "lodash.camelcase": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", - "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=", - "optional": true - }, - "lodash.clone": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.clone/-/lodash.clone-4.5.0.tgz", - "integrity": "sha1-GVhwRQ9aExkkeN9Lw9I9LeoZB7Y=", - "optional": true - }, - "lodash.includes": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" - }, - "lodash.isboolean": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" - }, - "lodash.isinteger": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" - }, - "lodash.isnumber": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" - }, - "lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" - }, - "lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" - }, - "lodash.merge": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.1.tgz", - "integrity": "sha512-AOYza4+Hf5z1/0Hztxpm2/xiPZgi/cjMqdnKTUWTBSKchJlxXXuUSxCCl8rJlf4g6yww/j6mA8nC8Hw/EZWxKQ==", - "optional": true - }, - "lodash.once": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" - }, - "log-driver": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/log-driver/-/log-driver-1.2.7.tgz", - "integrity": "sha512-U7KCmLdqsGHBLeWqYlFA0V0Sl6P08EE1ZrmA9cxjUE0WVqT9qnyVDPz1kzpFEP0jdJuFnasWIfSd7fsaNXkpbg==", - "optional": true - }, - "long": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", - "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" - }, - "lru-cache": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", - "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", - "requires": { - "pseudomap": "1.0.2", - "yallist": "2.1.2" - } - }, - "make-dir": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", - "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", - "optional": true, - "requires": { - "pify": "3.0.0" - } - }, - "map-cache": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", - "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=" - }, - "map-visit": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", - "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", - "requires": { - "object-visit": "1.0.1" - } - }, - "media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" - }, - "merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" - }, - "merge2": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.2.3.tgz", - "integrity": "sha512-gdUU1Fwj5ep4kplwcmftruWofEFt6lfpkkr3h860CXbAB9c3hGb55EOL2ali0Td5oebvW0E1+3Sr+Ur7XfKpRA==" - }, - "methmeth": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/methmeth/-/methmeth-1.1.0.tgz", - "integrity": "sha1-6AomYY5S9cQiKGG7dIUQvRDikIk=", - "optional": true - }, - "methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" - }, - "micromatch": { - "version": "3.1.10", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", - "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", - "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "braces": "2.3.2", - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "extglob": "2.0.4", - "fragment-cache": "0.2.1", - "kind-of": "6.0.2", - "nanomatch": "1.2.13", - "object.pick": "1.3.0", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - } - }, - "mime": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.0.tgz", - "integrity": "sha512-ikBcWwyqXQSHKtciCcctu9YfPbFYZ4+gbHEmE0Q8jzcTYQg5dHCr3g2wwAZjPoJfQVXZq6KXAjpXOTf5/cjT7w==" - }, - "mime-db": { - "version": "1.37.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.37.0.tgz", - "integrity": "sha512-R3C4db6bgQhlIhPU48fUtdVmKnflq+hRdad7IyKhtFj06VPNVdk2RhiYL3UjQIlso8L+YxAtFkobT0VK+S/ybg==" - }, - "mime-types": { - "version": "2.1.21", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.21.tgz", - "integrity": "sha512-3iL6DbwpyLzjR3xHSFNFeb9Nz/M8WDkX33t1GFQnFOllWk8pOrh/LSrB5OXlnlW5P9LH73X6loW/eogc+F5lJg==", - "requires": { - "mime-db": "1.37.0" - } - }, - "minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", - "requires": { - "brace-expansion": "1.1.11" - } - }, - "mixin-deep": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", - "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", - "requires": { - "for-in": "1.0.2", - "is-extendable": "1.0.1" - }, - "dependencies": { - "is-extendable": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", - "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", - "requires": { - "is-plain-object": "2.0.4" - } - } - } - }, - "modelo": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/modelo/-/modelo-4.2.3.tgz", - "integrity": "sha512-9DITV2YEMcw7XojdfvGl3gDD8J9QjZTJ7ZOUuSAkP+F3T6rDbzMJuPktxptsdHYEvZcmXrCD3LMOhdSAEq6zKA==", - "optional": true - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - }, - "nan": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.12.1.tgz", - "integrity": "sha512-JY7V6lRkStKcKTvHO5NVSQRv+RV+FIL5pvDoLiAtSL9pKlC5x9PKQcZDsq7m4FO4d57mkhC6Z+QhAh3Jdk5JFw==", - "optional": true - }, - "nanomatch": { - "version": "1.2.13", - "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", - "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", - "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "fragment-cache": "0.2.1", - "is-windows": "1.0.2", - "kind-of": "6.0.2", - "object.pick": "1.3.0", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - } - }, - "negotiator": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", - "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=" - }, - "node-forge": { - "version": "0.7.4", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.7.4.tgz", - "integrity": "sha512-8Df0906+tq/omxuCZD6PqhPaQDYuyJ1d+VITgxoIA8zvQd1ru+nMJcDChHH324MWitIgbVkAkQoGEEVJNpn/PA==" - }, - "number-is-nan": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" - }, - "oauth-sign": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", - "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" - }, - "object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" - }, - "object-copy": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", - "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", - "requires": { - "copy-descriptor": "0.1.1", - "define-property": "0.2.5", - "kind-of": "3.2.2" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "requires": { - "is-descriptor": "0.1.6" - } - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "object-keys": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.12.tgz", - "integrity": "sha512-FTMyFUm2wBcGHnH2eXmz7tC6IwlqQZ6mVZ+6dm6vZ4IQIHjs6FdNsQBuKGPuUUUY6NfJw2PshC08Tn6LzLDOag==" - }, - "object-visit": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", - "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", - "requires": { - "isobject": "3.0.1" - } - }, - "object.pick": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", - "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", - "requires": { - "isobject": "3.0.1" - } - }, - "on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", - "requires": { - "ee-first": "1.1.1" - } - }, - "once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "requires": { - "wrappy": "1.0.2" - } - }, - "optjs": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/optjs/-/optjs-3.2.2.tgz", - "integrity": "sha1-aabOicRCpEQDFBrS+bNwvVu29O4=", - "optional": true - }, - "os-locale": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz", - "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=", - "optional": true, - "requires": { - "lcid": "1.0.0" - } - }, - "parseurl": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", - "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=" - }, - "pascalcase": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", - "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=" - }, - "path-dirname": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", - "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=" - }, - "path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" - }, - "path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" - }, - "path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", - "requires": { - "pify": "3.0.0" - } - }, - "performance-now": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", - "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=" - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=" - }, - "posix-character-classes": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", - "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=" - }, - "power-assert": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/power-assert/-/power-assert-1.6.1.tgz", - "integrity": "sha512-VWkkZV6Y+W8qLX/PtJu2Ur2jDPIs0a5vbP0TpKeybNcIXmT4vcKoVkyTp5lnQvTpY/DxacAZ4RZisHRHLJcAZQ==", - "requires": { - "define-properties": "1.1.3", - "empower": "1.3.1", - "power-assert-formatter": "1.4.1", - "universal-deep-strict-equal": "1.2.2", - "xtend": "4.0.1" - } - }, - "power-assert-context-formatter": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-context-formatter/-/power-assert-context-formatter-1.2.0.tgz", - "integrity": "sha512-HLNEW8Bin+BFCpk/zbyKwkEu9W8/zThIStxGo7weYcFkKgMuGCHUJhvJeBGXDZf0Qm2xis4pbnnciGZiX0EpSg==", - "requires": { - "core-js": "2.6.1", - "power-assert-context-traversal": "1.2.0" - } - }, - "power-assert-context-reducer-ast": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-context-reducer-ast/-/power-assert-context-reducer-ast-1.2.0.tgz", - "integrity": "sha512-EgOxmZ/Lb7tw4EwSKX7ZnfC0P/qRZFEG28dx/690qvhmOJ6hgThYFm5TUWANDLK5NiNKlPBi5WekVGd2+5wPrw==", - "requires": { - "acorn": "5.7.3", - "acorn-es7-plugin": "1.1.7", - "core-js": "2.6.1", - "espurify": "1.8.1", - "estraverse": "4.2.0" - } - }, - "power-assert-context-traversal": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-context-traversal/-/power-assert-context-traversal-1.2.0.tgz", - "integrity": "sha512-NFoHU6g2umNajiP2l4qb0BRWD773Aw9uWdWYH9EQsVwIZnog5bd2YYLFCVvaxWpwNzWeEfZIon2xtyc63026pQ==", - "requires": { - "core-js": "2.6.1", - "estraverse": "4.2.0" - } - }, - "power-assert-formatter": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/power-assert-formatter/-/power-assert-formatter-1.4.1.tgz", - "integrity": "sha1-XcEl7VCj37HdomwZNH879Y7CiEo=", - "requires": { - "core-js": "2.6.1", - "power-assert-context-formatter": "1.2.0", - "power-assert-context-reducer-ast": "1.2.0", - "power-assert-renderer-assertion": "1.2.0", - "power-assert-renderer-comparison": "1.2.0", - "power-assert-renderer-diagram": "1.2.0", - "power-assert-renderer-file": "1.2.0" - } - }, - "power-assert-renderer-assertion": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-renderer-assertion/-/power-assert-renderer-assertion-1.2.0.tgz", - "integrity": "sha512-3F7Q1ZLmV2ZCQv7aV7NJLNK9G7QsostrhOU7U0RhEQS/0vhEqrRg2jEJl1jtUL4ZyL2dXUlaaqrmPv5r9kRvIg==", - "requires": { - "power-assert-renderer-base": "1.1.1", - "power-assert-util-string-width": "1.2.0" - } - }, - "power-assert-renderer-base": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/power-assert-renderer-base/-/power-assert-renderer-base-1.1.1.tgz", - "integrity": "sha1-lqZQxv0F7hvB9mtUrWFELIs/Y+s=" - }, - "power-assert-renderer-comparison": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-renderer-comparison/-/power-assert-renderer-comparison-1.2.0.tgz", - "integrity": "sha512-7c3RKPDBKK4E3JqdPtYRE9cM8AyX4LC4yfTvvTYyx8zSqmT5kJnXwzR0yWQLOavACllZfwrAGQzFiXPc5sWa+g==", - "requires": { - "core-js": "2.6.1", - "diff-match-patch": "1.0.4", - "power-assert-renderer-base": "1.1.1", - "stringifier": "1.4.0", - "type-name": "2.0.2" - } - }, - "power-assert-renderer-diagram": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-renderer-diagram/-/power-assert-renderer-diagram-1.2.0.tgz", - "integrity": "sha512-JZ6PC+DJPQqfU6dwSmpcoD7gNnb/5U77bU5KgNwPPa+i1Pxiz6UuDeM3EUBlhZ1HvH9tMjI60anqVyi5l2oNdg==", - "requires": { - "core-js": "2.6.1", - "power-assert-renderer-base": "1.1.1", - "power-assert-util-string-width": "1.2.0", - "stringifier": "1.4.0" - } - }, - "power-assert-renderer-file": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-renderer-file/-/power-assert-renderer-file-1.2.0.tgz", - "integrity": "sha512-/oaVrRbeOtGoyyd7e4IdLP/jIIUFJdqJtsYzP9/88R39CMnfF/S/rUc8ZQalENfUfQ/wQHu+XZYRMaCEZmEesg==", - "requires": { - "power-assert-renderer-base": "1.1.1" - } - }, - "power-assert-util-string-width": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/power-assert-util-string-width/-/power-assert-util-string-width-1.2.0.tgz", - "integrity": "sha512-lX90G0igAW0iyORTILZ/QjZWsa1MZ6VVY3L0K86e2eKun3S4LKPH4xZIl8fdeMYLfOjkaszbNSzf1uugLeAm2A==", - "requires": { - "eastasianwidth": "0.2.0" - } - }, - "process-nextick-args": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", - "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" - }, - "protobufjs": { - "version": "6.8.8", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.8.8.tgz", - "integrity": "sha512-AAmHtD5pXgZfi7GMpllpO3q1Xw1OYldr+dMUlAnffGTAhqkg72WdmSY71uKBF/JuyiKs8psYbtKrhi0ASCD8qw==", - "requires": { - "@protobufjs/aspromise": "1.1.2", - "@protobufjs/base64": "1.1.2", - "@protobufjs/codegen": "2.0.4", - "@protobufjs/eventemitter": "1.1.0", - "@protobufjs/fetch": "1.1.0", - "@protobufjs/float": "1.0.2", - "@protobufjs/inquire": "1.1.0", - "@protobufjs/path": "1.1.2", - "@protobufjs/pool": "1.1.0", - "@protobufjs/utf8": "1.1.0", - "@types/long": "4.0.0", - "@types/node": "10.12.18", - "long": "4.0.0" - }, - "dependencies": { - "@types/node": { - "version": "10.12.18", - "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.18.tgz", - "integrity": "sha512-fh+pAqt4xRzPfqA6eh3Z2y6fyZavRIumvjhaCL753+TVkGKGhpPeyrJG2JftD0T9q4GF00KjefsQ+PQNDdWQaQ==" - } - } - }, - "proxy-addr": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz", - "integrity": "sha512-5erio2h9jp5CHGwcybmxmVqHmnCBZeewlfJ0pex+UW7Qny7OOZXTtH56TGNyBizkgiOwhJtMKrVzDTeKcySZwA==", - "requires": { - "forwarded": "0.1.2", - "ipaddr.js": "1.8.0" - } - }, - "pseudomap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=" - }, - "psl": { - "version": "1.1.31", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", - "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==" - }, - "pump": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", - "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", - "requires": { - "end-of-stream": "1.4.1", - "once": "1.4.0" - } - }, - "pumpify": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", - "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", - "requires": { - "duplexify": "3.6.1", - "inherits": "2.0.3", - "pump": "2.0.1" - } - }, - "punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" - }, - "qs": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", - "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==" - }, - "range-parser": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", - "integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=" - }, - "raw-body": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.3.tgz", - "integrity": "sha512-9esiElv1BrZoI3rCDuOuKCBRbuApGGaDPQfjSflGxdy4oyzqghxu6klEkkVIvBje+FF0BX9coEv8KqW6X/7njw==", - "requires": { - "bytes": "3.0.0", - "http-errors": "1.6.3", - "iconv-lite": "0.4.23", - "unpipe": "1.0.0" - } - }, - "readable-stream": { - "version": "1.0.34", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", - "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", - "optional": true, - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "0.0.1", - "string_decoder": "0.10.31" - } - }, - "regex-not": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", - "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", - "requires": { - "extend-shallow": "3.0.2", - "safe-regex": "1.1.0" - } - }, - "repeat-element": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", - "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==" - }, - "repeat-string": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", - "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=" - }, - "request": { - "version": "2.88.0", - "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", - "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", - "requires": { - "aws-sign2": "0.7.0", - "aws4": "1.8.0", - "caseless": "0.12.0", - "combined-stream": "1.0.7", - "extend": "3.0.2", - "forever-agent": "0.6.1", - "form-data": "2.3.3", - "har-validator": "5.1.3", - "http-signature": "1.2.0", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.21", - "oauth-sign": "0.9.0", - "performance-now": "2.1.0", - "qs": "6.5.2", - "safe-buffer": "5.1.2", - "tough-cookie": "2.4.3", - "tunnel-agent": "0.6.0", - "uuid": "3.3.2" - } - }, - "resolve-url": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", - "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=" - }, - "ret": { - "version": "0.1.15", - "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", - "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==" - }, - "retry-axios": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/retry-axios/-/retry-axios-0.3.2.tgz", - "integrity": "sha512-jp4YlI0qyDFfXiXGhkCOliBN1G7fRH03Nqy8YdShzGqbY5/9S2x/IR6C88ls2DFkbWuL3ASkP7QD3pVrNpPgwQ==" - }, - "retry-request": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-4.0.0.tgz", - "integrity": "sha512-S4HNLaWcMP6r8E4TMH52Y7/pM8uNayOcTDDQNBwsCccL1uI+Ol2TljxRDPzaNfbhOB30+XWP5NnZkB3LiJxi1w==", - "optional": true, - "requires": { - "through2": "2.0.5" - } - }, - "safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - }, - "safe-regex": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", - "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", - "requires": { - "ret": "0.1.15" - } - }, - "safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "send": { - "version": "0.16.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz", - "integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==", - "requires": { - "debug": "2.6.9", - "depd": "1.1.2", - "destroy": "1.0.4", - "encodeurl": "1.0.2", - "escape-html": "1.0.3", - "etag": "1.8.1", - "fresh": "0.5.2", - "http-errors": "1.6.3", - "mime": "1.4.1", - "ms": "2.0.0", - "on-finished": "2.3.0", - "range-parser": "1.2.0", - "statuses": "1.4.0" - }, - "dependencies": { - "mime": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", - "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==" - } - } - }, - "serve-static": { - "version": "1.13.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz", - "integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==", - "requires": { - "encodeurl": "1.0.2", - "escape-html": "1.0.3", - "parseurl": "1.3.2", - "send": "0.16.2" - } - }, - "set-value": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", - "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", - "requires": { - "extend-shallow": "2.0.1", - "is-extendable": "0.1.1", - "is-plain-object": "2.0.4", - "split-string": "3.1.0" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "setprototypeof": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", - "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==" - }, - "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", - "optional": true - }, - "slash": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", - "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=" - }, - "snakeize": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/snakeize/-/snakeize-0.1.0.tgz", - "integrity": "sha1-EMCI2LWOsHazIpu1oE4jLOEmQi0=", - "optional": true - }, - "snapdragon": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", - "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", - "requires": { - "base": "0.11.2", - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "map-cache": "0.2.2", - "source-map": "0.5.7", - "source-map-resolve": "0.5.2", - "use": "3.1.1" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "requires": { - "is-descriptor": "0.1.6" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - } - } - }, - "snapdragon-node": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", - "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", - "requires": { - "define-property": "1.0.0", - "isobject": "3.0.1", - "snapdragon-util": "3.0.1" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "requires": { - "is-descriptor": "1.0.2" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "requires": { - "kind-of": "6.0.2" - } - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" - } - } - } - }, - "snapdragon-util": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", - "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "source-map": { - "version": "0.5.7", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", - "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" - }, - "source-map-resolve": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", - "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", - "requires": { - "atob": "2.1.2", - "decode-uri-component": "0.2.0", - "resolve-url": "0.2.1", - "source-map-url": "0.4.0", - "urix": "0.1.0" - } - }, - "source-map-url": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", - "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=" - }, - "split-array-stream": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/split-array-stream/-/split-array-stream-1.0.3.tgz", - "integrity": "sha1-0rdajl4Ngk1S/eyLgiWDncLjXfo=", - "optional": true, - "requires": { - "async": "2.6.1", - "is-stream-ended": "0.1.4" - } - }, - "split-string": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", - "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", - "requires": { - "extend-shallow": "3.0.2" - } - }, - "sshpk": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.0.tgz", - "integrity": "sha512-Zhev35/y7hRMcID/upReIvRse+I9SVhyVre/KTJSJQWMz3C3+G+HpO7m1wK/yckEtujKZ7dS4hkVxAnmHaIGVQ==", - "requires": { - "asn1": "0.2.4", - "assert-plus": "1.0.0", - "bcrypt-pbkdf": "1.0.2", - "dashdash": "1.14.1", - "ecc-jsbn": "0.1.2", - "getpass": "0.1.7", - "jsbn": "0.1.1", - "safer-buffer": "2.1.2", - "tweetnacl": "0.14.5" - } - }, - "static-extend": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", - "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", - "requires": { - "define-property": "0.2.5", - "object-copy": "0.1.0" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "requires": { - "is-descriptor": "0.1.6" - } - } - } - }, - "statuses": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", - "integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==" - }, - "stream-events": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz", - "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==", - "requires": { - "stubs": "3.0.0" - } - }, - "stream-shift": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", - "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=" - }, - "string-format-obj": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string-format-obj/-/string-format-obj-1.1.1.tgz", - "integrity": "sha512-Mm+sROy+pHJmx0P/0Bs1uxIX6UhGJGj6xDGQZ5zh9v/SZRmLGevp+p0VJxV7lirrkAmQ2mvva/gHKpnF/pTb+Q==", - "optional": true - }, - "string-width": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", - "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" - } - }, - "string_decoder": { - "version": "0.10.31", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "optional": true - }, - "stringifier": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/stringifier/-/stringifier-1.4.0.tgz", - "integrity": "sha512-cNsMOqqrcbLcHTXEVmkw9y0fwDwkdgtZwlfyolzpQDoAE1xdNGhQhxBUfiDvvZIKl1hnUEgMv66nHwtMz3OjPw==", - "requires": { - "core-js": "2.6.1", - "traverse": "0.6.6", - "type-name": "2.0.2" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "requires": { - "ansi-regex": "2.1.1" - } - }, - "stubs": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz", - "integrity": "sha1-6NK6H6nJBXAwPAMLaQD31fiavls=" - }, - "through2": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", - "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", - "requires": { - "readable-stream": "2.3.6", - "xtend": "4.0.1" - }, - "dependencies": { - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "readable-stream": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", - "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", - "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "2.0.0", - "safe-buffer": "5.1.2", - "string_decoder": "1.1.1", - "util-deprecate": "1.0.2" - } - }, - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "requires": { - "safe-buffer": "5.1.2" - } - } - } - }, - "to-object-path": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", - "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", - "requires": { - "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "requires": { - "is-buffer": "1.1.6" - } - } - } - }, - "to-regex": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", - "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", - "requires": { - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "regex-not": "1.0.2", - "safe-regex": "1.1.0" - } - }, - "to-regex-range": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", - "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", - "requires": { - "is-number": "3.0.0", - "repeat-string": "1.6.1" - } - }, - "tough-cookie": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", - "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", - "requires": { - "psl": "1.1.31", - "punycode": "1.4.1" - }, - "dependencies": { - "punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=" - } - } - }, - "traverse": { - "version": "0.6.6", - "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.6.6.tgz", - "integrity": "sha1-y99WD9e5r2MlAv7UD5GMFX6pcTc=" - }, - "tslib": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.0.tgz", - "integrity": "sha512-f/qGG2tUkrISBlQZEjEqoZ3B2+npJjIf04H1wuAv9iA8i04Icp+61KRXxFdha22670NJopsZCIjhC3SnjPRKrQ==" - }, - "tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", - "requires": { - "safe-buffer": "5.1.2" - } - }, - "tweetnacl": { - "version": "0.14.5", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", - "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" - }, - "type-is": { - "version": "1.6.16", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", - "integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==", - "requires": { - "media-typer": "0.3.0", - "mime-types": "2.1.21" - } - }, - "type-name": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/type-name/-/type-name-2.0.2.tgz", - "integrity": "sha1-7+fUEj2KxSr/9/QMfk3sUmYAj7Q=" - }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" - }, - "union-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", - "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", - "requires": { - "arr-union": "3.1.0", - "get-value": "2.0.6", - "is-extendable": "0.1.1", - "set-value": "0.4.3" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "requires": { - "is-extendable": "0.1.1" - } - }, - "set-value": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", - "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", - "requires": { - "extend-shallow": "2.0.1", - "is-extendable": "0.1.1", - "is-plain-object": "2.0.4", - "to-object-path": "0.3.0" - } - } - } - }, - "unique-string": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-1.0.0.tgz", - "integrity": "sha1-nhBXzKhRq7kzmPizOuGHuZyuwRo=", - "optional": true, - "requires": { - "crypto-random-string": "1.0.0" - } - }, - "universal-deep-strict-equal": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/universal-deep-strict-equal/-/universal-deep-strict-equal-1.2.2.tgz", - "integrity": "sha1-DaSsL3PP95JMgfpN4BjKViyisKc=", - "requires": { - "array-filter": "1.0.0", - "indexof": "0.0.1", - "object-keys": "1.0.12" - } - }, - "unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" - }, - "unset-value": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", - "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", - "requires": { - "has-value": "0.3.1", - "isobject": "3.0.1" - }, - "dependencies": { - "has-value": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", - "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", - "requires": { - "get-value": "2.0.6", - "has-values": "0.1.4", - "isobject": "2.1.0" - }, - "dependencies": { - "isobject": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", - "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", - "requires": { - "isarray": "1.0.0" - } - } - } - }, - "has-values": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", - "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=" - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - } - } - }, - "uri-js": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", - "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", - "requires": { - "punycode": "2.1.1" - } - }, - "urix": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", - "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=" - }, - "use": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", - "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==" - }, - "util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - }, - "utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" - }, - "uuid": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", - "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" - }, - "vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" - }, - "verror": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", - "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", - "requires": { - "assert-plus": "1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "1.3.0" - } - }, - "websocket-driver": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.0.tgz", - "integrity": "sha1-DK+dLXVdk67gSdS90NP+LMoqJOs=", - "requires": { - "http-parser-js": "0.5.0", - "websocket-extensions": "0.1.3" - } - }, - "websocket-extensions": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.3.tgz", - "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==" - }, - "window-size": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.4.tgz", - "integrity": "sha1-+OGqHuWlPsW/FR/6CXQqatdpeHY=", - "optional": true - }, - "wrap-ansi": { - "version": "2.1.0", - "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", - "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", - "optional": true, - "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1" - } - }, - "wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" - }, - "write-file-atomic": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.3.0.tgz", - "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", - "optional": true, - "requires": { - "graceful-fs": "4.1.15", - "imurmurhash": "0.1.4", - "signal-exit": "3.0.2" - } - }, - "xdg-basedir": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-3.0.0.tgz", - "integrity": "sha1-SWsswQnsqNus/i3HK2A8F8WHCtQ=" - }, - "xmlhttprequest": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/xmlhttprequest/-/xmlhttprequest-1.8.0.tgz", - "integrity": "sha1-Z/4HXFwk/vOfnWX197f+dRcZaPw=" - }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" - }, - "y18n": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", - "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", - "optional": true - }, - "yallist": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=" - }, - "yargs": { - "version": "3.32.0", - "resolved": "http://registry.npmjs.org/yargs/-/yargs-3.32.0.tgz", - "integrity": "sha1-AwiOnr+edWtpdRYR0qXvWRSCyZU=", - "optional": true, - "requires": { - "camelcase": "2.1.1", - "cliui": "3.2.0", - "decamelize": "1.2.0", - "os-locale": "1.4.0", - "string-width": "1.0.2", - "window-size": "0.1.4", - "y18n": "3.2.1" - } - } - } -} diff --git a/functions/package.json b/functions/package.json deleted file mode 100644 index d4abf300..00000000 --- a/functions/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "functions", - "description": "Cloud Functions for Firebase", - "scripts": { - "serve": "firebase serve --only functions", - "shell": "firebase functions:shell", - "start": "npm run shell", - "deploy": "firebase deploy --only functions", - "logs": "firebase functions:log" - }, - "dependencies": { - "firebase-admin": "~6.0.0", - "firebase-functions": "^2.1.0" - }, - "private": true -}