cbl-ionic 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/CblIonic.podspec +18 -0
  2. package/LICENSE +201 -0
  3. package/README.md +19 -0
  4. package/android/build.gradle +69 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/cbl/js/kotiln/CollectionConfigDto.kt +5 -0
  7. package/android/src/main/java/cbl/js/kotiln/CollectionDocumentResult.kt +7 -0
  8. package/android/src/main/java/cbl/js/kotiln/CollectionDto.kt +9 -0
  9. package/android/src/main/java/cbl/js/kotiln/CollectionManager.kt +232 -0
  10. package/android/src/main/java/cbl/js/kotiln/ConfigDto.kt +5 -0
  11. package/android/src/main/java/cbl/js/kotiln/DatabaseManager.kt +183 -0
  12. package/android/src/main/java/cbl/js/kotiln/DocumentDto.kt +6 -0
  13. package/android/src/main/java/cbl/js/kotiln/FileSystemHelper.kt +18 -0
  14. package/android/src/main/java/cbl/js/kotiln/LoggingManager.kt +30 -0
  15. package/android/src/main/java/cbl/js/kotiln/ReplicatorManager.kt +123 -0
  16. package/android/src/main/java/cbl/js/kotiln/ScopeDto.kt +6 -0
  17. package/android/src/main/java/com/couchbase/ionic/CblIonicPluginPlugin.kt +1832 -0
  18. package/android/src/main/java/com/couchbase/ionic/IndexDto.kt +12 -0
  19. package/android/src/main/java/com/couchbase/ionic/IndexHelper.kt +30 -0
  20. package/android/src/main/java/com/couchbase/ionic/PluginHelper.kt +283 -0
  21. package/android/src/main/java/com/couchbase/ionic/QueryHelper.kt +62 -0
  22. package/android/src/main/java/com/couchbase/ionic/ReplicatorHelper.kt +174 -0
  23. package/android/src/main/res/.gitkeep +0 -0
  24. package/dist/esm/cblite-js/cblite/core-types.d.ts +634 -0
  25. package/dist/esm/cblite-js/cblite/core-types.js +2 -0
  26. package/dist/esm/cblite-js/cblite/core-types.js.map +1 -0
  27. package/dist/esm/cblite-js/cblite/index.d.ts +2 -0
  28. package/dist/esm/cblite-js/cblite/index.js +4 -0
  29. package/dist/esm/cblite-js/cblite/index.js.map +1 -0
  30. package/dist/esm/cblite-js/cblite/src/abstract-index.d.ts +14 -0
  31. package/dist/esm/cblite-js/cblite/src/abstract-index.js +12 -0
  32. package/dist/esm/cblite-js/cblite/src/abstract-index.js.map +1 -0
  33. package/dist/esm/cblite-js/cblite/src/authenticator.d.ts +6 -0
  34. package/dist/esm/cblite-js/cblite/src/authenticator.js +3 -0
  35. package/dist/esm/cblite-js/cblite/src/authenticator.js.map +1 -0
  36. package/dist/esm/cblite-js/cblite/src/basic-authenticator.d.ts +42 -0
  37. package/dist/esm/cblite-js/cblite/src/basic-authenticator.js +59 -0
  38. package/dist/esm/cblite-js/cblite/src/basic-authenticator.js.map +1 -0
  39. package/dist/esm/cblite-js/cblite/src/blob.d.ts +58 -0
  40. package/dist/esm/cblite-js/cblite/src/blob.js +86 -0
  41. package/dist/esm/cblite-js/cblite/src/blob.js.map +1 -0
  42. package/dist/esm/cblite-js/cblite/src/collation.d.ts +20 -0
  43. package/dist/esm/cblite-js/cblite/src/collation.js +64 -0
  44. package/dist/esm/cblite-js/cblite/src/collation.js.map +1 -0
  45. package/dist/esm/cblite-js/cblite/src/collection-config.d.ts +24 -0
  46. package/dist/esm/cblite-js/cblite/src/collection-config.js +30 -0
  47. package/dist/esm/cblite-js/cblite/src/collection-config.js.map +1 -0
  48. package/dist/esm/cblite-js/cblite/src/collection.d.ts +189 -0
  49. package/dist/esm/cblite-js/cblite/src/collection.js +354 -0
  50. package/dist/esm/cblite-js/cblite/src/collection.js.map +1 -0
  51. package/dist/esm/cblite-js/cblite/src/concurrency-control.d.ts +4 -0
  52. package/dist/esm/cblite-js/cblite/src/concurrency-control.js +8 -0
  53. package/dist/esm/cblite-js/cblite/src/concurrency-control.js.map +1 -0
  54. package/dist/esm/cblite-js/cblite/src/couchbase-lite-exception.d.ts +6 -0
  55. package/dist/esm/cblite-js/cblite/src/couchbase-lite-exception.js +15 -0
  56. package/dist/esm/cblite-js/cblite/src/couchbase-lite-exception.js.map +1 -0
  57. package/dist/esm/cblite-js/cblite/src/database-configuration.d.ts +52 -0
  58. package/dist/esm/cblite-js/cblite/src/database-configuration.js +75 -0
  59. package/dist/esm/cblite-js/cblite/src/database-configuration.js.map +1 -0
  60. package/dist/esm/cblite-js/cblite/src/database-logging.d.ts +13 -0
  61. package/dist/esm/cblite-js/cblite/src/database-logging.js +13 -0
  62. package/dist/esm/cblite-js/cblite/src/database-logging.js.map +1 -0
  63. package/dist/esm/cblite-js/cblite/src/database.d.ts +254 -0
  64. package/dist/esm/cblite-js/cblite/src/database.js +514 -0
  65. package/dist/esm/cblite-js/cblite/src/database.js.map +1 -0
  66. package/dist/esm/cblite-js/cblite/src/definitions.d.ts +7 -0
  67. package/dist/esm/cblite-js/cblite/src/definitions.js +2 -0
  68. package/dist/esm/cblite-js/cblite/src/definitions.js.map +1 -0
  69. package/dist/esm/cblite-js/cblite/src/document-replication.d.ts +13 -0
  70. package/dist/esm/cblite-js/cblite/src/document-replication.js +34 -0
  71. package/dist/esm/cblite-js/cblite/src/document-replication.js.map +1 -0
  72. package/dist/esm/cblite-js/cblite/src/document.d.ts +199 -0
  73. package/dist/esm/cblite-js/cblite/src/document.js +333 -0
  74. package/dist/esm/cblite-js/cblite/src/document.js.map +1 -0
  75. package/dist/esm/cblite-js/cblite/src/endpoint.d.ts +3 -0
  76. package/dist/esm/cblite-js/cblite/src/endpoint.js +2 -0
  77. package/dist/esm/cblite-js/cblite/src/endpoint.js.map +1 -0
  78. package/dist/esm/cblite-js/cblite/src/engine-locator.d.ts +42 -0
  79. package/dist/esm/cblite-js/cblite/src/engine-locator.js +50 -0
  80. package/dist/esm/cblite-js/cblite/src/engine-locator.js.map +1 -0
  81. package/dist/esm/cblite-js/cblite/src/expression.d.ts +134 -0
  82. package/dist/esm/cblite-js/cblite/src/expression.js +374 -0
  83. package/dist/esm/cblite-js/cblite/src/expression.js.map +1 -0
  84. package/dist/esm/cblite-js/cblite/src/file-system.d.ts +7 -0
  85. package/dist/esm/cblite-js/cblite/src/file-system.js +14 -0
  86. package/dist/esm/cblite-js/cblite/src/file-system.js.map +1 -0
  87. package/dist/esm/cblite-js/cblite/src/full-text-expression.d.ts +28 -0
  88. package/dist/esm/cblite-js/cblite/src/full-text-expression.js +38 -0
  89. package/dist/esm/cblite-js/cblite/src/full-text-expression.js.map +1 -0
  90. package/dist/esm/cblite-js/cblite/src/full-text-index.d.ts +47 -0
  91. package/dist/esm/cblite-js/cblite/src/full-text-index.js +77 -0
  92. package/dist/esm/cblite-js/cblite/src/full-text-index.js.map +1 -0
  93. package/dist/esm/cblite-js/cblite/src/index-builder.d.ts +20 -0
  94. package/dist/esm/cblite-js/cblite/src/index-builder.js +25 -0
  95. package/dist/esm/cblite-js/cblite/src/index-builder.js.map +1 -0
  96. package/dist/esm/cblite-js/cblite/src/index.d.ts +42 -0
  97. package/dist/esm/cblite-js/cblite/src/index.js +43 -0
  98. package/dist/esm/cblite-js/cblite/src/index.js.map +1 -0
  99. package/dist/esm/cblite-js/cblite/src/meta-expression.d.ts +10 -0
  100. package/dist/esm/cblite-js/cblite/src/meta-expression.js +30 -0
  101. package/dist/esm/cblite-js/cblite/src/meta-expression.js.map +1 -0
  102. package/dist/esm/cblite-js/cblite/src/meta.d.ts +7 -0
  103. package/dist/esm/cblite-js/cblite/src/meta.js +8 -0
  104. package/dist/esm/cblite-js/cblite/src/meta.js.map +1 -0
  105. package/dist/esm/cblite-js/cblite/src/mutable-document.d.ts +373 -0
  106. package/dist/esm/cblite-js/cblite/src/mutable-document.js +481 -0
  107. package/dist/esm/cblite-js/cblite/src/mutable-document.js.map +1 -0
  108. package/dist/esm/cblite-js/cblite/src/ordering.d.ts +14 -0
  109. package/dist/esm/cblite-js/cblite/src/ordering.js +31 -0
  110. package/dist/esm/cblite-js/cblite/src/ordering.js.map +1 -0
  111. package/dist/esm/cblite-js/cblite/src/parameter.d.ts +18 -0
  112. package/dist/esm/cblite-js/cblite/src/parameter.js +38 -0
  113. package/dist/esm/cblite-js/cblite/src/parameter.js.map +1 -0
  114. package/dist/esm/cblite-js/cblite/src/parameters.d.ts +17 -0
  115. package/dist/esm/cblite-js/cblite/src/parameters.js +61 -0
  116. package/dist/esm/cblite-js/cblite/src/parameters.js.map +1 -0
  117. package/dist/esm/cblite-js/cblite/src/query.d.ts +83 -0
  118. package/dist/esm/cblite-js/cblite/src/query.js +146 -0
  119. package/dist/esm/cblite-js/cblite/src/query.js.map +1 -0
  120. package/dist/esm/cblite-js/cblite/src/replicated-document.d.ts +25 -0
  121. package/dist/esm/cblite-js/cblite/src/replicated-document.js +51 -0
  122. package/dist/esm/cblite-js/cblite/src/replicated-document.js.map +1 -0
  123. package/dist/esm/cblite-js/cblite/src/replicator-activity-level.d.ts +7 -0
  124. package/dist/esm/cblite-js/cblite/src/replicator-activity-level.js +14 -0
  125. package/dist/esm/cblite-js/cblite/src/replicator-activity-level.js.map +1 -0
  126. package/dist/esm/cblite-js/cblite/src/replicator-change.d.ts +14 -0
  127. package/dist/esm/cblite-js/cblite/src/replicator-change.js +14 -0
  128. package/dist/esm/cblite-js/cblite/src/replicator-change.js.map +1 -0
  129. package/dist/esm/cblite-js/cblite/src/replicator-configuration.d.ts +341 -0
  130. package/dist/esm/cblite-js/cblite/src/replicator-configuration.js +516 -0
  131. package/dist/esm/cblite-js/cblite/src/replicator-configuration.js.map +1 -0
  132. package/dist/esm/cblite-js/cblite/src/replicator-progress.d.ts +9 -0
  133. package/dist/esm/cblite-js/cblite/src/replicator-progress.js +20 -0
  134. package/dist/esm/cblite-js/cblite/src/replicator-progress.js.map +1 -0
  135. package/dist/esm/cblite-js/cblite/src/replicator-status.d.ts +13 -0
  136. package/dist/esm/cblite-js/cblite/src/replicator-status.js +29 -0
  137. package/dist/esm/cblite-js/cblite/src/replicator-status.js.map +1 -0
  138. package/dist/esm/cblite-js/cblite/src/replicator.d.ts +108 -0
  139. package/dist/esm/cblite-js/cblite/src/replicator.js +224 -0
  140. package/dist/esm/cblite-js/cblite/src/replicator.js.map +1 -0
  141. package/dist/esm/cblite-js/cblite/src/result.d.ts +4 -0
  142. package/dist/esm/cblite-js/cblite/src/result.js +2 -0
  143. package/dist/esm/cblite-js/cblite/src/result.js.map +1 -0
  144. package/dist/esm/cblite-js/cblite/src/scope.d.ts +31 -0
  145. package/dist/esm/cblite-js/cblite/src/scope.js +34 -0
  146. package/dist/esm/cblite-js/cblite/src/scope.js.map +1 -0
  147. package/dist/esm/cblite-js/cblite/src/session-authenticator.d.ts +32 -0
  148. package/dist/esm/cblite-js/cblite/src/session-authenticator.js +52 -0
  149. package/dist/esm/cblite-js/cblite/src/session-authenticator.js.map +1 -0
  150. package/dist/esm/cblite-js/cblite/src/url-endpoint.d.ts +8 -0
  151. package/dist/esm/cblite-js/cblite/src/url-endpoint.js +12 -0
  152. package/dist/esm/cblite-js/cblite/src/url-endpoint.js.map +1 -0
  153. package/dist/esm/cblite-js/cblite/src/value-index.d.ts +32 -0
  154. package/dist/esm/cblite-js/cblite/src/value-index.js +54 -0
  155. package/dist/esm/cblite-js/cblite/src/value-index.js.map +1 -0
  156. package/dist/esm/cblite-js/cblite/src/variable-expression.d.ts +7 -0
  157. package/dist/esm/cblite-js/cblite/src/variable-expression.js +15 -0
  158. package/dist/esm/cblite-js/cblite/src/variable-expression.js.map +1 -0
  159. package/dist/esm/couchbase-lite/capacitor-engine.d.ts +124 -0
  160. package/dist/esm/couchbase-lite/capacitor-engine.js +303 -0
  161. package/dist/esm/couchbase-lite/capacitor-engine.js.map +1 -0
  162. package/dist/esm/definitions.d.ts +12 -0
  163. package/dist/esm/definitions.js +4 -0
  164. package/dist/esm/definitions.js.map +1 -0
  165. package/dist/esm/index.d.ts +4 -0
  166. package/dist/esm/index.js +5 -0
  167. package/dist/esm/index.js.map +1 -0
  168. package/dist/esm/ionic-couchbase-lite.d.ts +3 -0
  169. package/dist/esm/ionic-couchbase-lite.js +4 -0
  170. package/dist/esm/ionic-couchbase-lite.js.map +1 -0
  171. package/dist/plugin.cjs.js +4400 -0
  172. package/dist/plugin.cjs.js.map +1 -0
  173. package/dist/plugin.js +4403 -0
  174. package/dist/plugin.js.map +1 -0
  175. package/ios/Plugin/CblIonicPlugin.swift +1583 -0
  176. package/ios/Plugin/CblIonicPluginPlugin.h +10 -0
  177. package/ios/Plugin/CblIonicPluginPlugin.m +86 -0
  178. package/ios/Plugin/Info.plist +24 -0
  179. package/ios/Plugin/cbl-js-swift/CollectionManager.swift +489 -0
  180. package/ios/Plugin/cbl-js-swift/DatabaseManager.swift +319 -0
  181. package/ios/Plugin/cbl-js-swift/FileSystemHelper.swift +22 -0
  182. package/ios/Plugin/cbl-js-swift/IndexHelper.swift +36 -0
  183. package/ios/Plugin/cbl-js-swift/LICENSE +201 -0
  184. package/ios/Plugin/cbl-js-swift/LoggingManager.swift +79 -0
  185. package/ios/Plugin/cbl-js-swift/MapHelper.swift +92 -0
  186. package/ios/Plugin/cbl-js-swift/QueryHelper.swift +74 -0
  187. package/ios/Plugin/cbl-js-swift/README.md +9 -0
  188. package/ios/Plugin/cbl-js-swift/ReplicatorHelper.swift +184 -0
  189. package/ios/Plugin/cbl-js-swift/ReplicatorManager.swift +157 -0
  190. package/package.json +86 -0
package/dist/plugin.js ADDED
@@ -0,0 +1,4403 @@
1
+ var capacitorIonicCouchbaseLite = (function (exports, core) {
2
+ 'use strict';
3
+
4
+ exports.IndexType = void 0;
5
+ (function (IndexType) {
6
+ // eslint-disable-next-line
7
+ IndexType[IndexType["Value"] = 0] = "Value";
8
+ // eslint-disable-next-line
9
+ IndexType[IndexType["FullText"] = 1] = "FullText";
10
+ // eslint-disable-next-line
11
+ IndexType[IndexType["Geo"] = 2] = "Geo";
12
+ })(exports.IndexType || (exports.IndexType = {}));
13
+ class AbstractIndex {
14
+ }
15
+
16
+ class Authenticator {
17
+ }
18
+
19
+ class CollectionConfig {
20
+ /**
21
+ * The collection configuration that can be configured specifically for the replication.
22
+ */
23
+ constructor(channels, documentIds) {
24
+ this.channels = channels ?? [];
25
+ this.documentIds = documentIds ?? [];
26
+ }
27
+ /**
28
+ * An array of Sync Gateway/App Services channel names to pull from. Ignored for push replication. If unset, all accessible channels will be pulled. Note: channels that are not accessible to the user will be ignored by Sync Gateway.
29
+ * @param {string[]} channels - Array of channel names to configure for the collection
30
+ * @example
31
+ * const config = new CollectionConfig();
32
+ * config.setChannels(['channel1', 'channel2']);
33
+ */
34
+ setChannels(channels) {
35
+ this.channels = channels;
36
+ }
37
+ /**
38
+ * A set of document IDs to filter by: if given, only documents with these IDs will be pushed and/or pulled.
39
+ * @param {string[]} documentIds - Array of document IDs to include in replication
40
+ * @example
41
+ * const config = new CollectionConfig();
42
+ * config.setDocumentIDs(['doc1', 'doc2', 'doc3']);
43
+ */
44
+ setDocumentIDs(documentIds) {
45
+ this.documentIds = documentIds;
46
+ }
47
+ }
48
+
49
+ exports.ReplicatorType = void 0;
50
+ (function (ReplicatorType) {
51
+ ReplicatorType["PUSH_AND_PULL"] = "PUSH_AND_PULL";
52
+ ReplicatorType["PUSH"] = "PUSH";
53
+ ReplicatorType["PULL"] = "PULL";
54
+ })(exports.ReplicatorType || (exports.ReplicatorType = {}));
55
+ class ReplicatorConfiguration {
56
+ constructor(target) {
57
+ this.target = target;
58
+ this.replicatorType = exports.ReplicatorType.PUSH_AND_PULL;
59
+ this.target = target;
60
+ this.collections = new Map();
61
+ this.continuous = ReplicatorConfiguration.defaultContinuous;
62
+ this.autoPurgeEnabled = ReplicatorConfiguration.defaultEnableAutoPurge;
63
+ this.heartbeat = ReplicatorConfiguration.defaultHeartbeat;
64
+ this.acceptOnlySelfSignedCerts =
65
+ ReplicatorConfiguration.defaultSelfSignedCertificateOnly;
66
+ this.acceptParentDomainCookies =
67
+ ReplicatorConfiguration.defaultAcceptParentDomainCookies;
68
+ this.allowReplicatingInBackground =
69
+ ReplicatorConfiguration.defaultAllowReplicatingInBackground;
70
+ this.maxAttempts = ReplicatorConfiguration.defaultMaxAttemptsSingleShot;
71
+ this.maxAttemptWaitTime =
72
+ ReplicatorConfiguration.defaultMaxAttemptsWaitTime;
73
+ this.authenticator = undefined;
74
+ this.headers = undefined;
75
+ this.pinnedServerCertificate = undefined;
76
+ }
77
+ // eslint-disable-next-line no-dupe-class-members
78
+ addCollection(collection, config) {
79
+ const cols = [];
80
+ cols.push(collection);
81
+ this.removeCollection(collection);
82
+ if (config === undefined || config === null) {
83
+ config = new CollectionConfig(undefined, undefined);
84
+ }
85
+ this.collections.set(cols, config);
86
+ }
87
+ /**
88
+ * Add multiple collections used for the replication with an optional shared collection configuration.
89
+ * If any of the collections have been added before, the previously added collections and their
90
+ * configuration if specified will be replaced. Adding an empty collection array will be no-ops. if
91
+ * specified will be replaced. If a null or undefined configuration is specified, a default empty configuration will be
92
+ * applied.
93
+ *
94
+ * @function
95
+ */
96
+ addCollections(collections, config) {
97
+ this.removeCollections(collections);
98
+ if (config === undefined || config === null) {
99
+ config = new CollectionConfig(undefined, undefined);
100
+ }
101
+ this.collections.set(collections, config);
102
+ }
103
+ /**
104
+ * returns the setting used to specify the replicator to accept any and only self-signed certs. Any non-self-signed
105
+ * certs will be rejected to avoid accidentally using this mode with the non-self-signed certs in production.
106
+ *
107
+ * @function
108
+ */
109
+ getAcceptOnlySelfSignedCerts() {
110
+ return this.acceptOnlySelfSignedCerts;
111
+ }
112
+ /**
113
+ * returns the setting used as the option to remove the restriction that does not allow the replicator to save the
114
+ * parent-domain cookies, the cookies whose domains are the parent domain of the remote host, from the HTTP
115
+ * response. For example, when the option is set to true, the cookies whose domain are “.foo.com”
116
+ * returned by “bar.foo.com” host will be permitted to save.
117
+ *
118
+ * This option is disabled by default which means that the parent-domain cookies are not permitted to save by default.
119
+ *
120
+ * @function
121
+ */
122
+ getAcceptParentDomainCookies() {
123
+ return this.acceptParentDomainCookies;
124
+ }
125
+ /**
126
+ * returns the setting which is used to allow the replicator to continue replicating in the background.
127
+ * The default value is false, which means that the replicator will suspend itself when the
128
+ * replicator detects that the application is running in the background.
129
+ *
130
+ * If setting the value to true, the developer MUST ensure that the application requests
131
+ * for extending the background task properly in the configuration. See your platforms documentation
132
+ * more information.
133
+ *
134
+ * @function
135
+ */
136
+ getAllowReplicatingInBackground() {
137
+ return this.allowReplicatingInBackground;
138
+ }
139
+ /**
140
+ * return the auto purge feature setting
141
+ *
142
+ * The default value is true which means that the document will be automatically purged by the
143
+ * pull replicator when the user loses access to the document from both removed and revoked scenarios.
144
+ *
145
+ * When the property is set to false, this behavior is disabled and access removed event
146
+ * will be sent to any document listeners that are active on the replicator. For performance
147
+ * reasons, the document listeners must be added **before** the replicator is started, or
148
+ * they will not receive the events.
149
+ *
150
+ * Note: Auto purge will not be performed when documentIDs filter is specified.
151
+ *
152
+ * @function
153
+ */
154
+ getAutoPurgeEnabled() {
155
+ return this.autoPurgeEnabled;
156
+ }
157
+ /**
158
+ * returns the Authenticator to authenticate with a remote target.
159
+ *
160
+ * @function
161
+ */
162
+ getAuthenticator() {
163
+ return this.authenticator;
164
+ }
165
+ /**
166
+ * returns collections used for the replication.
167
+ *
168
+ * @function
169
+ */
170
+ getCollections() {
171
+ const keys = this.collections.keys();
172
+ return Array.from(keys).flat();
173
+ }
174
+ /**
175
+ * returns a copy of the collection’s config. If the config needs to be changed for the collection, the
176
+ * collection will need to be re-added with the updated config.
177
+ *
178
+ * @function
179
+ */
180
+ getCollectionConfig(collection) {
181
+ for (const key of this.collections.keys()) {
182
+ if (key.includes(collection)) {
183
+ return this.collections.get(key);
184
+ }
185
+ }
186
+ return null;
187
+ }
188
+ /**
189
+ * returns the continuous flag indicating whether the replicator should stay
190
+ * active indefinitely to replicate changed documents.
191
+ *
192
+ * @function
193
+ */
194
+ getContinuous() {
195
+ return this.continuous;
196
+ }
197
+ /**
198
+ * returns extra HTTP headers to send in all requests to the remote target.
199
+ *
200
+ * @function
201
+ */
202
+ getHeaders() {
203
+ return this.headers;
204
+ }
205
+ /**
206
+ * returns the heartbeat interval in second.
207
+ *
208
+ * The interval when the replicator sends the ping message to check whether the other peer is
209
+ * still alive. Default heartbeat is ``ReplicatorConfiguration.defaultHeartbeat`` secs.
210
+ *
211
+ * Note: Setting the heartbeat to negative value will result in an Exception
212
+ * being thrown. For backward compatibility, setting it to zero will result in
213
+ * default 300 secs internally.
214
+ *
215
+ * @function
216
+ */
217
+ getHeartbeat() {
218
+ return this.heartbeat;
219
+ }
220
+ /**
221
+ * returns the maximum attempts to perform retry. The retry attempt will be reset when the replicator is
222
+ * able to connect and replicate with the remote server again.
223
+ *
224
+ * Default _maxAttempts_ is ``ReplicatorConfiguration.defaultMaxAttemptsSingleShot`` times
225
+ * for single shot replicators and ``ReplicatorConfiguration.defaultMaxAttemptsContinuous`` times
226
+ * for continuous replicators.
227
+ *
228
+ * Settings the value to 1, will perform an initial request and if there is a transient error
229
+ * occurs, will stop without retry.
230
+ *
231
+ * Note: For backward compatibility, setting it to zero will result in default 10 internally.
232
+ *
233
+ * @function
234
+ */
235
+ getMaxAttempts() {
236
+ return this.maxAttempts;
237
+ }
238
+ /**
239
+ * returns the max wait time for the next attempt(retry) in seconds.
240
+ *
241
+ * The exponential backoff for calculating the wait time will be used by default and cannot be
242
+ * customized. Default max attempts is `ReplicatorConfiguration.defaultMaxAttemptsWaitTime` secs.
243
+ *
244
+ * Set the maxAttemptWaitTime to negative value will result in an Exception
245
+ * being thrown.
246
+ *
247
+ * Note: For backward compatibility, setting it to zero will result in default secs internally.
248
+ *
249
+ * @function
250
+ */
251
+ getMaxAttemptWaitTime() {
252
+ return this.maxAttemptWaitTime;
253
+ }
254
+ /**
255
+ * returns the string value of the remote target's SSL certificate that was previously set in the configuration.
256
+ *
257
+ * Note: The pinned cert will be evaluated against any certs in a cert chain,
258
+ * and the cert chain will be valid only if the cert chain contains the pinned cert.
259
+ *
260
+ * @function
261
+ */
262
+ getPinnedServerCertificate() {
263
+ return this.pinnedServerCertificate;
264
+ }
265
+ /**
266
+ * returns the replicator type indicating the direction of the replicator.
267
+ *
268
+ * @function
269
+ */
270
+ getReplicatorType() {
271
+ return this.replicatorType;
272
+ }
273
+ /**
274
+ * Remove a group of collections from the configuration. If the collection doesn’t exist, this operation will be no ops.
275
+ *
276
+ * @function
277
+ */
278
+ removeCollections(collections) {
279
+ for (const col of collections) {
280
+ for (const key of this.collections.keys()) {
281
+ if (key.includes(col)) {
282
+ this.collections.delete(key);
283
+ }
284
+ }
285
+ }
286
+ }
287
+ /**
288
+ * Remove the collection. If the collection doesn’t exist, this operation will be no ops.
289
+ *
290
+ * @function
291
+ */
292
+ removeCollection(collection) {
293
+ for (const key of this.collections.keys()) {
294
+ if (key.includes(collection)) {
295
+ const newCols = key.filter((col) => col !== collection);
296
+ const config = this.collections.get(key);
297
+ this.collections.delete(key);
298
+ this.collections.set(newCols, config);
299
+ }
300
+ }
301
+ }
302
+ /**
303
+ * Specify the replicator to accept any and only self-signed certs. Any non-self-signed certs will be rejected
304
+ * to avoid accidentally using this mode with the non-self-signed certs in production.
305
+ * Default value is ``ReplicatorConfiguration.defaultSelfSignedCertificateOnly``
306
+ *
307
+ * @function
308
+ */
309
+ setAcceptOnlySelfSignedCerts(selfSignedCerts) {
310
+ this.acceptOnlySelfSignedCerts = selfSignedCerts;
311
+ }
312
+ /**
313
+ * The option to remove the restriction that does not allow the replicator to save the parent-domain
314
+ * cookies, the cookies whose domains are the parent domain of the remote host, from the HTTP
315
+ * response. For example, when the option is set to true, the cookies whose domain are “.foo.com”
316
+ * returned by “bar.foo.com” host will be permitted to save.
317
+ *
318
+ * This option is disabled by default (See ``ReplicatorConfiguration.defaultAcceptParentCookies``)
319
+ * which means that the parent-domain cookies are not permitted to save by default.
320
+ *
321
+ * @function
322
+ */
323
+ setAcceptParentDomainCookies(acceptParentDomainCookies) {
324
+ this.acceptParentDomainCookies = acceptParentDomainCookies;
325
+ }
326
+ /**
327
+ * Allows the replicator to continue replicating in the background. The default
328
+ * value is false, which means that the replicator will suspend itself when the
329
+ * replicator detects that the application is running in the background.
330
+ *
331
+ * If setting the value to true, the developer MUST ensure that the application requests
332
+ * for extending the background task properly in the configuration. See your platforms documentation
333
+ * more information.
334
+ *
335
+ * @function
336
+ */
337
+ setAllowReplicatingInBackground(allowReplicatingInBackground) {
338
+ this.allowReplicatingInBackground = allowReplicatingInBackground;
339
+ }
340
+ /**
341
+ * To enable/disable the auto purge feature
342
+ *
343
+ * The default value is true which means that the document will be automatically purged by the
344
+ * pull replicator when the user loses access to the document from both removed and revoked scenarios.
345
+ *
346
+ * When the property is set to false, this behavior is disabled and access removed event
347
+ * will be sent to any document listeners that are active on the replicator. For performance
348
+ * reasons, the document listeners must be added **before** the replicator is started, or
349
+ * they will not receive the events.
350
+ *
351
+ * Note: Auto purge will not be performed when documentIDs filter is specified.
352
+ *
353
+ * @function
354
+ */
355
+ setAutoPurgeEnabled(autoPurgeEnabled) {
356
+ this.autoPurgeEnabled = autoPurgeEnabled;
357
+ }
358
+ /**
359
+ * The Authenticator to authenticate with a remote target.
360
+ *
361
+ * @function
362
+ */
363
+ setAuthenticator(authenticator) {
364
+ this.authenticator = authenticator;
365
+ }
366
+ /**
367
+ * The continuous flag indicating whether the replicator should stay
368
+ * active indefinitely to replicate changed documents.
369
+ *
370
+ * @function
371
+ */
372
+ setContinuous(continuous) {
373
+ this.continuous = continuous;
374
+ }
375
+ /**
376
+ * Extra HTTP headers to send in all requests to the remote target.
377
+ *
378
+ * @function
379
+ */
380
+ setHeaders(headers) {
381
+ this.headers = headers;
382
+ }
383
+ /**
384
+ * The heartbeat interval in second.
385
+ *
386
+ * The interval when the replicator sends the ping message to check whether the other peer is
387
+ * still alive. Default heartbeat is ``ReplicatorConfiguration.defaultHeartbeat`` secs.
388
+ *
389
+ * Note: Setting the heartbeat to negative value will result in an Exception
390
+ * being thrown. For backward compatibility, setting it to zero will result in
391
+ * default 300 secs internally.
392
+ *
393
+ * @function
394
+ */
395
+ setHeartbeat(heartbeat) {
396
+ this.heartbeat = heartbeat;
397
+ }
398
+ /**
399
+ * The maximum attempts to perform retry. The retry attempt will be reset when the replicator is
400
+ * able to connect and replicate with the remote server again.
401
+ *
402
+ * Default _maxAttempts_ is ``ReplicatorConfiguration.defaultMaxAttemptsSingleShot`` times
403
+ * for single shot replicators and ``ReplicatorConfiguration.defaultMaxAttemptsContinuous`` times
404
+ * for continuous replicators.
405
+ *
406
+ * Settings the value to 1, will perform an initial request and if there is a transient error
407
+ * occurs, will stop without retry.
408
+ *
409
+ * Note: For backward compatibility, setting it to zero will result in default 10 internally.
410
+ *
411
+ * @function
412
+ */
413
+ setMaxAttempts(maxAttempts) {
414
+ this.maxAttempts = maxAttempts;
415
+ }
416
+ /**
417
+ * Max wait time for the next attempt(retry) in seconds.
418
+ *
419
+ * The exponential backoff for calculating the wait time will be used by default and cannot be
420
+ * customized. Default max attempts is `ReplicatorConfiguration.defaultMaxAttemptsWaitTime` secs.
421
+ *
422
+ * Set the maxAttemptWaitTime to negative value will result in an Exception
423
+ * being thrown.
424
+ *
425
+ * Note: For backward compatibility, setting it to zero will result in default secs internally.
426
+ *
427
+ * @function
428
+ */
429
+ setMaxAttemptWaitTime(maxAttemptWaitTime) {
430
+ if (maxAttemptWaitTime >= 0) {
431
+ this.maxAttemptWaitTime = maxAttemptWaitTime;
432
+ }
433
+ else {
434
+ throw new Error('Error: maxAttemptWaitTime cannot be negative.');
435
+ }
436
+ }
437
+ /**
438
+ * The remote target's SSL certificate.
439
+ *
440
+ * Note: The pinned cert will be evaluated against any certs in a cert chain,
441
+ * and the cert chain will be valid only if the cert chain contains the pinned cert.
442
+ *
443
+ * @function
444
+ */
445
+ setPinnedServerCertificate(pinnedServerCertificate) {
446
+ this.pinnedServerCertificate = pinnedServerCertificate;
447
+ }
448
+ /**
449
+ * Replicator type indicating the direction of the replicator.
450
+ *
451
+ * @function
452
+ */
453
+ setReplicatorType(replicatorType) {
454
+ this.replicatorType = replicatorType;
455
+ }
456
+ toJson() {
457
+ const config = {
458
+ acceptParentDomainCookies: this.acceptParentDomainCookies,
459
+ acceptSelfSignedCerts: this.acceptOnlySelfSignedCerts,
460
+ allowReplicationInBackground: this.allowReplicatingInBackground,
461
+ autoPurgeEnabled: this.autoPurgeEnabled,
462
+ authenticator: null,
463
+ collectionConfig: null,
464
+ continuous: this.continuous,
465
+ headers: null,
466
+ heartbeat: this.heartbeat,
467
+ maxAttempts: this.maxAttempts,
468
+ maxAttemptWaitTime: this.maxAttemptWaitTime,
469
+ pinnedServerCertificate: null,
470
+ replicatorType: this.replicatorType,
471
+ target: this.target.toJson(),
472
+ };
473
+ if (this.headers !== undefined) {
474
+ config.headers = this.headers;
475
+ }
476
+ else {
477
+ config.headers = '';
478
+ }
479
+ if (this.pinnedServerCertificate !== undefined) {
480
+ config.pinnedServerCertificate = this.pinnedServerCertificate;
481
+ }
482
+ else {
483
+ config.pinnedServerCertificate = '';
484
+ }
485
+ if (this.authenticator !== undefined) {
486
+ config.authenticator = {
487
+ type: this.authenticator.getType(),
488
+ data: this.authenticator.toJson(),
489
+ };
490
+ }
491
+ else {
492
+ config.authenticator = '';
493
+ }
494
+ if (this.collections.size > 0) {
495
+ if (this.checkCollectionsScopeAndDatabase()) {
496
+ const colArray = [];
497
+ for (const [collections, collectionConfig] of this.collections) {
498
+ const collectionsArray = [];
499
+ for (const collection of collections) {
500
+ collectionsArray.push({ collection: collection.toJson() });
501
+ }
502
+ if (collectionConfig !== undefined || collectionConfig !== null) {
503
+ colArray.push({
504
+ collections: collectionsArray,
505
+ config: collectionConfig,
506
+ });
507
+ }
508
+ else {
509
+ colArray.push({ collections: collectionsArray, config: '' });
510
+ }
511
+ }
512
+ config.collectionConfig = JSON.stringify(colArray);
513
+ }
514
+ else {
515
+ throw new Error('All collections must be from the same database and scope');
516
+ }
517
+ }
518
+ else {
519
+ config.collectionConfig = '';
520
+ }
521
+ return config;
522
+ }
523
+ checkCollectionsScopeAndDatabase() {
524
+ let databaseName = null;
525
+ let scopeName = null;
526
+ // eslint-disable-next-line
527
+ for (const [collections, _] of this.collections) {
528
+ for (const collection of collections) {
529
+ if (databaseName === null && scopeName === null) {
530
+ databaseName = collection.database.getName();
531
+ scopeName = collection.scope.name;
532
+ }
533
+ else if (collection.database.getName() !== databaseName ||
534
+ collection.scope.name !== scopeName) {
535
+ return false;
536
+ }
537
+ }
538
+ }
539
+ return true;
540
+ }
541
+ }
542
+ ReplicatorConfiguration.ReplicatorType = exports.ReplicatorType;
543
+ // Authentication dictionary keys:
544
+ ReplicatorConfiguration.CBLReplicatorOptionCookies = 'cookies'; // HTTP Cookie header value; string
545
+ ReplicatorConfiguration.CBLReplicatorAuthOption = 'auth'; // Auth settings; Dict
546
+ ReplicatorConfiguration.CBLReplicatorAuthType = 'type'; // Auth property; string
547
+ ReplicatorConfiguration.CBLReplicatorAuthUserName = 'username'; // Auth property; string
548
+ ReplicatorConfiguration.CBLReplicatorAuthPassword = 'password'; // Auth property; string
549
+ ReplicatorConfiguration.CBLReplicatorAuthClientCert = 'clientCert'; // Auth property; value platform-dependent
550
+ // auth.type values:
551
+ ReplicatorConfiguration.CBLAuthTypeBasic = 'Basic'; // HTTP Basic (the default)
552
+ ReplicatorConfiguration.CBLAuthTypeSession = 'Session'; // SG session cookie
553
+ ReplicatorConfiguration.CBLAuthTypeOpenIDConnect = 'OpenID Connect';
554
+ ReplicatorConfiguration.CBLAuthTypeClientCert = 'Client Cert';
555
+ ReplicatorConfiguration.defaultContinuous = false;
556
+ ReplicatorConfiguration.defaultEnableAutoPurge = true;
557
+ ReplicatorConfiguration.defaultSelfSignedCertificateOnly = true;
558
+ ReplicatorConfiguration.defaultAcceptParentDomainCookies = false;
559
+ ReplicatorConfiguration.defaultAllowReplicatingInBackground = false;
560
+ ReplicatorConfiguration.defaultHeartbeat = 300;
561
+ ReplicatorConfiguration.defaultMaxAttemptsSingleShot = 10;
562
+ ReplicatorConfiguration.defaultMaxAttemptsWaitTime = 300;
563
+
564
+ class BasicAuthenticator extends Authenticator {
565
+ constructor(
566
+ // eslint-disable-next-line
567
+ username,
568
+ // eslint-disable-next-line
569
+ password) {
570
+ super();
571
+ this.username = username;
572
+ this.password = password;
573
+ }
574
+ /**
575
+ * Configures basic authentication options for a replicator
576
+ * @param {Dictionary} options - The replicator configuration options to be modified
577
+ * @returns {Dictionary} The authentication configuration containing username and password
578
+ * @example
579
+ * const authenticator = new BasicAuthenticator('user', 'password');
580
+ * const config = {};
581
+ * const auth = authenticator.authenticate(config);
582
+ * // config now contains the auth settings
583
+ * // auth contains: { type: 'basic', username: 'user', password: 'password' }
584
+ */
585
+ authenticate(options) {
586
+ const auth = {
587
+ [ReplicatorConfiguration.CBLReplicatorAuthType]: ReplicatorConfiguration.CBLAuthTypeBasic,
588
+ [ReplicatorConfiguration.CBLReplicatorAuthUserName]: this.username,
589
+ [ReplicatorConfiguration.CBLReplicatorAuthPassword]: this.password,
590
+ };
591
+ options[ReplicatorConfiguration.CBLReplicatorAuthOption] = auth;
592
+ return auth;
593
+ }
594
+ /**
595
+ * Returns the authentication type identifier
596
+ * @returns {string} The string 'basic' indicating basic authentication
597
+ * @example
598
+ * const authenticator = new BasicAuthenticator('user', 'password');
599
+ * const type = authenticator.getType();
600
+ * // Returns: 'basic'
601
+ */
602
+ getType() {
603
+ return 'basic';
604
+ }
605
+ /**
606
+ * Converts the authenticator to a JSON-compatible object
607
+ * @returns {{ username: string, password: string }} An object containing the authenticator's credentials
608
+ * @example
609
+ * const authenticator = new BasicAuthenticator('user', 'password');
610
+ * const json = authenticator.toJson();
611
+ * // Returns: { username: 'user', password: 'password' }
612
+ */
613
+ toJson() {
614
+ return {
615
+ username: this.username,
616
+ password: this.password,
617
+ };
618
+ }
619
+ }
620
+
621
+ class Blob {
622
+ /**
623
+ * Creates a new Blob instance to store binary data with a specified content type
624
+ * @param contentType - The MIME type of the blob content (e.g., 'image/jpeg', 'text/plain')
625
+ * @param data - The binary data as either a Uint8Array or ArrayBuffer
626
+ * @example
627
+ * // Create from Uint8Array
628
+ * const uint8Array = new Uint8Array([1, 2, 3]);
629
+ * const blob1 = new Blob('text/plain', uint8Array);
630
+ *
631
+ * // Create from ArrayBuffer
632
+ * const arrayBuffer = new ArrayBuffer(3);
633
+ * const blob2 = new Blob('text/plain', arrayBuffer);
634
+ */
635
+ constructor(contentType, data) {
636
+ this.contentType = contentType;
637
+ this.contentType = contentType;
638
+ this.bytes = data instanceof Uint8Array ? data.buffer : data;
639
+ }
640
+ /**
641
+ * Creates a new Blob instance from a JSON string representation
642
+ * @param jsonString - A JSON string containing blob data with format: { contentType: string, bytes: number[] }
643
+ * @returns A new Blob instance
644
+ * @throws {Error} If the JSON is invalid, missing required properties, or has incorrect types
645
+ * @example
646
+ * const jsonStr = '{"contentType": "image/jpeg", "bytes": [255, 216, 255, 224]}';
647
+ * const blob = Blob.fromJSON(jsonStr);
648
+ */
649
+ static fromJSON(jsonString) {
650
+ try {
651
+ const data = JSON.parse(jsonString);
652
+ // Validate required properties and types
653
+ if (!data.contentType || typeof data.contentType !== 'string') {
654
+ throw new Error('Invalid or missing contentType property');
655
+ }
656
+ if (!Array.isArray(data.bytes)) {
657
+ throw new Error('Invalid or missing bytes property');
658
+ }
659
+ // Convert number array back to ArrayBuffer
660
+ const bytes = new Uint8Array(data.bytes);
661
+ return new Blob(data.contentType, bytes);
662
+ }
663
+ catch (e) {
664
+ throw new Error(`Failed to parse Blob JSON: ${e.message}`);
665
+ }
666
+ }
667
+ /**
668
+ * Returns the raw binary data of the blob
669
+ * @returns {Uint8Array} The blob's content as an Uint8Array
670
+ */
671
+ getBytes() {
672
+ return new Uint8Array(this.bytes);
673
+ }
674
+ /**
675
+ * Returns the MIME type of the blob's content
676
+ * @returns {string} The content type (MIME type) of the blob
677
+ */
678
+ getContentType() {
679
+ return this.contentType;
680
+ }
681
+ /**
682
+ * Returns the cryptographic digest (hash) of the blob's content
683
+ * @returns {string} The blob's content digest
684
+ */
685
+ getDigest() {
686
+ return this.digest;
687
+ }
688
+ /**
689
+ * Returns the size of the blob's content in bytes
690
+ * @returns {number} The length of the blob in bytes
691
+ */
692
+ getLength() {
693
+ return this.length;
694
+ }
695
+ /**
696
+ * Converts the blob into a plain JavaScript object representation
697
+ * @returns {{ contentType: string, data: number[] }} An object containing the blob's content type and data as a byte array
698
+ */
699
+ toDictionary() {
700
+ return {
701
+ contentType: this.contentType,
702
+ data: Array.from(new Uint8Array(this.bytes)),
703
+ };
704
+ }
705
+ }
706
+
707
+ class Collation {
708
+ constructor() {
709
+ this._unicode = false;
710
+ this._ignoreCase = false;
711
+ this._ignoreAccents = false;
712
+ this._locale = null;
713
+ }
714
+ static ascii() {
715
+ return new CollationASCII();
716
+ }
717
+ static unicode() {
718
+ return new CollationUnicode();
719
+ }
720
+ toString() {
721
+ return ('Collation{' +
722
+ 'unicode=' +
723
+ this._unicode +
724
+ ', ignoreCase=' +
725
+ this._ignoreCase +
726
+ ', ignoreAccents=' +
727
+ this._ignoreAccents +
728
+ ", locale='" +
729
+ this._locale +
730
+ "'" +
731
+ '}');
732
+ }
733
+ asJSON() {
734
+ const json = {};
735
+ json.UNICODE = this._unicode;
736
+ json.LOCALE = this._locale == null ? null : this._locale;
737
+ json.CASE = !this._ignoreCase;
738
+ json.DIAC = !this._ignoreAccents;
739
+ return json;
740
+ }
741
+ }
742
+ class CollationASCII extends Collation {
743
+ constructor() {
744
+ super();
745
+ this._unicode = false;
746
+ }
747
+ ignoreCase(ignoreCase) {
748
+ this._ignoreCase = ignoreCase;
749
+ return this;
750
+ }
751
+ }
752
+ class CollationUnicode extends Collation {
753
+ constructor() {
754
+ super();
755
+ this._unicode = true;
756
+ }
757
+ ignoreCase(ignoreCase) {
758
+ this._ignoreCase = ignoreCase;
759
+ return this;
760
+ }
761
+ ignoreAccents(ignoreAccents) {
762
+ this._ignoreAccents = ignoreAccents;
763
+ return this;
764
+ }
765
+ locale(locale) {
766
+ this._locale = locale;
767
+ return this;
768
+ }
769
+ }
770
+
771
+ class EngineLocator {
772
+ constructor() { }
773
+ /**
774
+ * Returns the singleton instance of EngineLocator
775
+ * @returns {EngineLocator} The singleton instance of the EngineLocator
776
+ * @example
777
+ * const locator = EngineLocator.getInstance();
778
+ * // Use the same instance throughout the application
779
+ * const sameLocator = EngineLocator.getInstance(); // Returns the same instance
780
+ */
781
+ static getInstance() {
782
+ if (!EngineLocator.instance) {
783
+ EngineLocator.instance = new EngineLocator();
784
+ }
785
+ return EngineLocator.instance;
786
+ }
787
+ /**
788
+ * Registers a core engine implementation with the EngineLocator
789
+ * @param {string} key - The unique identifier for the engine
790
+ * @param {ICoreEngine} service - The core engine implementation to register
791
+ * @example
792
+ * const engine = new MyCoreEngine();
793
+ * EngineLocator.registerEngine('myEngine', engine);
794
+ *
795
+ * // Later, retrieve the engine
796
+ * const sameEngine = EngineLocator.getEngine('myEngine');
797
+ */
798
+ static registerEngine(key, service) {
799
+ EngineLocator.engines.set(key, service);
800
+ }
801
+ /**
802
+ * Retrieves a registered core engine implementation by its key
803
+ * @param {string} key - The unique identifier of the engine to retrieve
804
+ * @returns {ICoreEngine} The registered core engine implementation
805
+ * @example
806
+ * // First register an engine
807
+ * const engine = new MyCoreEngine();
808
+ * EngineLocator.registerEngine('myEngine', engine);
809
+ *
810
+ * // Then retrieve it
811
+ * const retrievedEngine = EngineLocator.getEngine('myEngine');
812
+ * // retrievedEngine === engine
813
+ */
814
+ static getEngine(key) {
815
+ return EngineLocator.engines.get(key);
816
+ }
817
+ }
818
+ EngineLocator.key = 'default';
819
+ EngineLocator.engines = new Map();
820
+
821
+ class Scope {
822
+ constructor(name, database) {
823
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
824
+ this.name = name ?? '';
825
+ this.database = database;
826
+ }
827
+ /**
828
+ * Retrieves all collections within this scope
829
+ * @returns {Promise<Collection[]>} A Promise that resolves to an array of Collection instances
830
+ * @throws {Error} If the database is closed or there's an error accessing collections
831
+ */
832
+ async collections() {
833
+ const results = await this._engine.collection_GetCollections({
834
+ name: this.database.getName(),
835
+ scopeName: this.name,
836
+ });
837
+ return results.collections;
838
+ }
839
+ /**
840
+ * Retrieves a specific collection within this scope by name
841
+ * @param {string} collectionName - The name of the collection to retrieve
842
+ * @returns {Promise<Collection | null>} A Promise that resolves to the Collection instance, or null if not found
843
+ * @throws {Error} If the database is closed or there's an error accessing the collection
844
+ */
845
+ async collection(collectionName) {
846
+ return this._engine.collection_GetCollection({
847
+ name: this.database.getName(),
848
+ collectionName: collectionName,
849
+ scopeName: this.name,
850
+ });
851
+ }
852
+ }
853
+
854
+ class Document {
855
+ constructor(id = null,
856
+ // eslint-disable-next-line
857
+ sequenceNo = null,
858
+ // eslint-disable-next-line
859
+ revisionID = null,
860
+ // eslint-disable-next-line
861
+ collection = null, data = {}) {
862
+ this.id = id;
863
+ this.sequenceNo = sequenceNo;
864
+ this.revisionID = revisionID;
865
+ this.collection = collection;
866
+ this.doc = {};
867
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
868
+ if (id === null) {
869
+ this.id = this._engine.getUUID();
870
+ }
871
+ this.doc = data;
872
+ }
873
+ /**
874
+ * The number of properties in the document.
875
+ *
876
+ * Throws an error if the collection is deleted or the database is closed.
877
+ *
878
+ * @function
879
+ */
880
+ count() {
881
+ return Object.keys(this.doc).length;
882
+ }
883
+ /**
884
+ * Returns the document data as a dictionary.
885
+ *
886
+ * Throws an error if the collection is deleted or the database is closed.
887
+ *
888
+ * @function
889
+ */
890
+ getData() {
891
+ return this.doc;
892
+ }
893
+ _get(key) {
894
+ return this.doc[key];
895
+ }
896
+ /**
897
+ * Get a property’s value as a ArrayObject, which is a mapping object of an array value.
898
+ * Returns null if the property doesn’t exists, or its value is not an array.
899
+ *
900
+ * Throws an error if the collection is deleted or the database is closed.
901
+ *
902
+ * @function
903
+ */
904
+ getArray(key) {
905
+ if (key in this.doc && Array.isArray(this.doc[key])) {
906
+ return this.doc[key];
907
+ }
908
+ return null;
909
+ }
910
+ /**
911
+ * Returns metadata associated with the Blob. Use getBlobContent() to get the Blob’s data.
912
+ * Throws an error if the collection is deleted or the database is closed.
913
+ *
914
+ * @function
915
+ */
916
+ getBlob(key) {
917
+ if (key in this.doc) {
918
+ const data = this._get(key);
919
+ if (data && typeof data === 'object' && 'content_type' in data) {
920
+ const b = new Blob(data.content_type, data.raw);
921
+ b.digest = data.digest;
922
+ b.length = data.length;
923
+ return b;
924
+ }
925
+ }
926
+ return null;
927
+ }
928
+ /**
929
+ * @deprecated - use the Blob API getBytes() function instead
930
+ *
931
+ * Get a property’s value as a ArrayBuffer. Returns null if the property doesn’t exist,
932
+ * or its value is not a blob.
933
+ *
934
+ * Throws an error if the collection is deleted or the database is closed.
935
+ *
936
+ * @function
937
+ */
938
+ async getBlobContent(key) {
939
+ const data = await this._engine.collection_GetBlobContent({
940
+ documentId: this.getId(),
941
+ key: key,
942
+ collectionName: this.collection.name,
943
+ scopeName: this.collection.scope.name,
944
+ name: this.collection.scope.database.getName(),
945
+ });
946
+ return data.data;
947
+ }
948
+ /**
949
+ * Gets a property’s value as a boolean value. Returns true if the value exists,
950
+ * and is either true or a nonzero number.
951
+ *
952
+ * Throws an error if the collection is deleted or the database is closed.
953
+ *
954
+ * @function
955
+ */
956
+ getBoolean(key) {
957
+ if (key in this.doc) {
958
+ const value = this.doc[key];
959
+ if (typeof value === 'boolean') {
960
+ return value;
961
+ }
962
+ if (value === 0 || value === '0.0') {
963
+ return false;
964
+ }
965
+ if (value === null) {
966
+ return false;
967
+ }
968
+ return true;
969
+ }
970
+ return false;
971
+ }
972
+ /**
973
+ * The collection that the document belongs to.
974
+ *
975
+ * Throws an error if the database is closed.
976
+ *
977
+ * @function
978
+ */
979
+ getCollection() {
980
+ return this.collection;
981
+ }
982
+ /**
983
+ * Gets a property’s value as a Date value. JSON does not directly support dates, so
984
+ * the actual property value must be a string, which is then parsed according to the
985
+ * ISO-8601 date format (the default used in JSON.) Returns null if the value doesn’t
986
+ * exist, is not a string, or is not parseable as a date. NOTE: This is not a generic
987
+ * date parser! It only recognizes the ISO-8601 format, with milliseconds.
988
+ *
989
+ * Throws an error if the collection is deleted or the database is closed.
990
+ *
991
+ * @function
992
+ */
993
+ getDate(key) {
994
+ if (key in this.doc) {
995
+ const value = this.doc[key];
996
+ if (typeof value === 'string') {
997
+ const date = new Date(value);
998
+ // Check if the date is valid (not "Invalid Date")
999
+ return !isNaN(date.getTime()) ? date : null;
1000
+ }
1001
+ }
1002
+ return null;
1003
+ }
1004
+ /**
1005
+ * Get a property’s value as a Dictionary, which is a mapping object of a dictionary
1006
+ * value. Returns null if the property doesn’t exists, or its value is not a dictionary.
1007
+ *
1008
+ * Throws an error if the collection is deleted or the database is closed.
1009
+ *
1010
+ * @function
1011
+ */
1012
+ getDictionary(key) {
1013
+ if (key in this.doc) {
1014
+ const value = this.doc[key];
1015
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
1016
+ return value;
1017
+ }
1018
+ }
1019
+ return null;
1020
+ }
1021
+ /**
1022
+ * Gets a property’s value as a double value. Integers will be converted to double.
1023
+ * The value true is returned as 1.0, false as 0.0. Returns 0.0 if the property doesn’t
1024
+ * exist or does not have a numeric value.
1025
+ *
1026
+ * Throws an error if the collection is deleted or the database is closed.
1027
+ *
1028
+ * @function
1029
+ */
1030
+ getDouble(key) {
1031
+ if (key in this.doc) {
1032
+ const value = this.doc[key];
1033
+ if (typeof value === 'number') {
1034
+ return value;
1035
+ }
1036
+ if (typeof value === 'boolean') {
1037
+ return value ? 1.0 : 0.0;
1038
+ }
1039
+ }
1040
+ return 0.0;
1041
+ }
1042
+ /**
1043
+ * Gets a property’s value as a float value. Integers will be converted to float.
1044
+ * The value true is returned as 1.0, false as 0.0. Returns 0.0 if the property doesn’t
1045
+ * exist or does not have a numeric value.
1046
+ *
1047
+ * Throws an error if the collection is deleted or the database is closed.
1048
+ *
1049
+ * @function
1050
+ */
1051
+ getFloat(key) {
1052
+ if (key in this.doc) {
1053
+ const value = this.doc[key];
1054
+ if (typeof value === 'number') {
1055
+ return value;
1056
+ }
1057
+ if (typeof value === 'boolean') {
1058
+ return value ? 1.0 : 0.0;
1059
+ }
1060
+ }
1061
+ return 0.0;
1062
+ }
1063
+ /**
1064
+ * Returns the document’s ID.
1065
+ *
1066
+ * Throws an error if the collection is deleted or the database is closed.
1067
+ *
1068
+ * @function
1069
+ */
1070
+ getId() {
1071
+ return this.id;
1072
+ }
1073
+ /**
1074
+ * Gets a property’s value as an int value. Floating point values will be rounded.
1075
+ * The value true is returned as 1, false as 0. Returns 0 if the property doesn’t
1076
+ * exist or does not have a numeric value.
1077
+ *
1078
+ * Throws an error if the collection is deleted or the database is closed.
1079
+ *
1080
+ * @function
1081
+ */
1082
+ getInt(key) {
1083
+ if (key in this.doc) {
1084
+ const value = this.doc[key];
1085
+ if (typeof value === 'number') {
1086
+ return Math.floor(value);
1087
+ }
1088
+ if (typeof value === 'boolean') {
1089
+ return value ? 1 : 0;
1090
+ }
1091
+ }
1092
+ return 0;
1093
+ }
1094
+ /**
1095
+ * returns an array containing all keys, or an empty array if the document
1096
+ * has no properties.
1097
+ *
1098
+ * Throws an error if the collection is deleted or the database is closed.
1099
+ *
1100
+ * @function
1101
+ */
1102
+ getKeys() {
1103
+ return Object.keys(this.doc);
1104
+ }
1105
+ /**
1106
+ * Gets a property’s value as an number value. Floating point values will be rounded.
1107
+ * The value true is returned as 1, false as 0. Returns 0 if the property doesn’t
1108
+ * exist or does not have a numeric value.
1109
+ *
1110
+ * Throws an error if the collection is deleted or the database is closed.
1111
+ *
1112
+ * @function
1113
+ */
1114
+ getLong(key) {
1115
+ return key in this.doc ? this.doc[key] : 0;
1116
+ }
1117
+ /**
1118
+ * The ID representing a document’s revision.
1119
+ *
1120
+ * Throws an error if the collection is deleted or the database is closed.
1121
+ *
1122
+ * @function
1123
+ */
1124
+ getRevisionID() {
1125
+ return this.revisionID;
1126
+ }
1127
+ /**
1128
+ * Sequence number of the document in the database. This indicates how recently the
1129
+ * document has been changed: every time any document is updated, the database assigns it
1130
+ * the next sequential sequence number. Thus, if a document’s sequence property changes
1131
+ * that means it’s been changed (on-disk); and if one document’s sequence is greater than
1132
+ * another’s, that means it was changed more recently.
1133
+ *
1134
+ * Throws an error if the collection is deleted or the database is closed.
1135
+ *
1136
+ * @function
1137
+ */
1138
+ getSequence() {
1139
+ return this.sequenceNo;
1140
+ }
1141
+ /**
1142
+ * Gets a property’s value as a string. Returns nil if the property doesn’t exist, i
1143
+ * or its value is not a string.
1144
+ *
1145
+ * Throws an error if the collection is deleted or the database is closed.
1146
+ *
1147
+ * @function
1148
+ */
1149
+ getString(key) {
1150
+ if (key in this.doc) {
1151
+ const value = this.doc[key];
1152
+ if (typeof value === 'string') {
1153
+ return value;
1154
+ }
1155
+ }
1156
+ return null;
1157
+ }
1158
+ /**
1159
+ * @deprecated getValue is deprecated. Returns values as any.
1160
+ */
1161
+ getValue(key) {
1162
+ return key in this.doc ? this.doc[key] : null;
1163
+ }
1164
+ /**
1165
+ * Returns the document data as a dictionary.
1166
+ *
1167
+ * Throws an error if the collection is deleted or the database is closed.
1168
+ *
1169
+ * @function
1170
+ */
1171
+ toDictionary() {
1172
+ return this.doc;
1173
+ }
1174
+ /**
1175
+ * Converts the document content to a JSON string representation
1176
+ * @returns {string} A JSON string
1177
+ *
1178
+ * @function
1179
+ */
1180
+ toJsonString() {
1181
+ return JSON.stringify(this.doc);
1182
+ }
1183
+ }
1184
+
1185
+ class Collection {
1186
+ constructor(name, scope, database) {
1187
+ //used for engine calls
1188
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
1189
+ this._didStartListener = false;
1190
+ /**
1191
+ * returns Collection's fully qualified name in the '<scope-name>.<collection-name>' format.
1192
+ *
1193
+ * @property
1194
+ */
1195
+ this.fullName = () => `${this.scope.name}.${this.name}`;
1196
+ this.name = name ?? '';
1197
+ this.scope = scope ?? new Scope('', database);
1198
+ this.database = database;
1199
+ this._documentChangeListener = new Map();
1200
+ this._didStartDocumentListener = new Map();
1201
+ }
1202
+ /**
1203
+ * Set a given CollectionChangeListener to the collection.
1204
+ *
1205
+ * @function
1206
+ */
1207
+ async addChangeListener(listener) {
1208
+ this._changeListener = listener;
1209
+ const token = this.uuid();
1210
+ if (!this._didStartListener) {
1211
+ await this._engine.collection_AddChangeListener({
1212
+ name: this.scope.database.getName(),
1213
+ scopeName: this.scope.name,
1214
+ collectionName: this.name,
1215
+ changeListenerToken: token,
1216
+ }, (data, err) => {
1217
+ if (err) {
1218
+ throw err;
1219
+ }
1220
+ this.notifyChangeListeners(data);
1221
+ });
1222
+ this._didStartListener = true;
1223
+ return token;
1224
+ }
1225
+ else {
1226
+ throw new Error('Listener already started');
1227
+ }
1228
+ }
1229
+ /**
1230
+ * Set a given Collection Document Change Listener to a given document in a collection.
1231
+ *
1232
+ * @function
1233
+ */
1234
+ async addDocumentChangeListener(documentId, listener) {
1235
+ const token = this.uuid();
1236
+ if (!this._didStartDocumentListener.has(documentId) &&
1237
+ !this._documentChangeListener[documentId]) {
1238
+ await this._engine.collection_AddDocumentChangeListener({
1239
+ name: this.scope.database.getName(),
1240
+ scopeName: this.scope.name,
1241
+ collectionName: this.name,
1242
+ changeListenerToken: token,
1243
+ documentId: documentId,
1244
+ }, (data, err) => {
1245
+ if (err) {
1246
+ throw err;
1247
+ }
1248
+ this.notifyDocumentChangeListeners(data);
1249
+ });
1250
+ this._documentChangeListener.set(documentId, listener);
1251
+ this._didStartDocumentListener[documentId] = true;
1252
+ return token;
1253
+ }
1254
+ else {
1255
+ throw new Error(`Listener for document ${documentId} already started`);
1256
+ }
1257
+ }
1258
+ /**
1259
+ * Total number of documents in the collection.
1260
+ *
1261
+ * @function
1262
+ */
1263
+ count() {
1264
+ return this._engine.collection_GetCount({
1265
+ name: this.scope.database.getName(),
1266
+ scopeName: this.scope.name,
1267
+ collectionName: this.name,
1268
+ });
1269
+ }
1270
+ /**
1271
+ * Create an index with the index name and AbstractIndex.
1272
+ *
1273
+ * @function
1274
+ */
1275
+ createIndex(indexName, index) {
1276
+ return this._engine.collection_CreateIndex({
1277
+ name: this.scope.database.getName(),
1278
+ scopeName: this.scope.name,
1279
+ collectionName: this.name,
1280
+ indexName: indexName,
1281
+ index: index.toJson(),
1282
+ });
1283
+ }
1284
+ /**
1285
+ * Delete a document from the collection. The default concurrency control, lastWriteWins,
1286
+ * will be used when there is conflict during delete. If the document doesn’t exist in the
1287
+ * collection, an error will be thrown.
1288
+ *
1289
+ * When deleting a document that already belongs to a collection, the collection instance of
1290
+ * the document and this collection instance must be the same, otherwise, an
1291
+ * error will be thrown.
1292
+ *
1293
+ * Throws an Error if the collection is deleted or the database is closed.
1294
+ *
1295
+ * @function
1296
+ */
1297
+ deleteDocument(document, concurrencyControl = null) {
1298
+ const id = document.getId();
1299
+ return this._engine.collection_DeleteDocument({
1300
+ name: this.scope.database.getName(),
1301
+ scopeName: this.scope.name,
1302
+ collectionName: this.name,
1303
+ docId: id,
1304
+ concurrencyControl: concurrencyControl,
1305
+ });
1306
+ }
1307
+ /**
1308
+ * Delete an index by name.
1309
+ *
1310
+ * @function
1311
+ */
1312
+ deleteIndex(indexName) {
1313
+ return this._engine.collection_DeleteIndex({
1314
+ name: this.scope.database.getName(),
1315
+ scopeName: this.scope.name,
1316
+ collectionName: this.name,
1317
+ indexName: indexName,
1318
+ });
1319
+ }
1320
+ /**
1321
+ * Get an existing document by document ID.
1322
+ *
1323
+ * Throws an error if the collection is deleted or the database is closed.
1324
+ *
1325
+ * @function
1326
+ */
1327
+ async document(id) {
1328
+ const docJson = await this._engine.collection_GetDocument({
1329
+ docId: id,
1330
+ name: this.scope.database.getName(),
1331
+ scopeName: this.scope.name,
1332
+ collectionName: this.name,
1333
+ });
1334
+ // @ts-expect-error - _id is used in getId()
1335
+ if (docJson && docJson._id) {
1336
+ // @ts-expect-error - _data is used in getData()
1337
+ const data = docJson._data;
1338
+ // @ts-expect-error - _sequence is used in getSequence()
1339
+ const sequence = docJson._sequence;
1340
+ // @ts-expect-error - _id is used in getId()
1341
+ const retId = docJson._id;
1342
+ // @ts-expect-error - _revId is used in getRevisionID()
1343
+ const revisionID = docJson._revId;
1344
+ return Promise.resolve(new Document(retId, sequence, revisionID, this, data));
1345
+ }
1346
+ else {
1347
+ return Promise.resolve(undefined);
1348
+ }
1349
+ }
1350
+ /**
1351
+ * Get an existing document by document ID.
1352
+ *
1353
+ * Throws an error if the collection is deleted or the database is closed.
1354
+ *
1355
+ * @function
1356
+ */
1357
+ async getDocument(id) {
1358
+ return this.document(id);
1359
+ }
1360
+ /**
1361
+ * Get the expiration date set to the document of the given id.
1362
+
1363
+ * Throws an error, if the collection is deleted or the database is closed.
1364
+ *
1365
+ * @function
1366
+ */
1367
+ async getDocumentExpiration(id) {
1368
+ const date = await this._engine.collection_GetDocumentExpiration({
1369
+ docId: id,
1370
+ name: this.scope.database.getName(),
1371
+ scopeName: this.scope.name,
1372
+ collectionName: this.name,
1373
+ });
1374
+ if (date !== null && date.date !== null) {
1375
+ return date.date;
1376
+ }
1377
+ else {
1378
+ return null;
1379
+ }
1380
+ }
1381
+ /**
1382
+ * Return ICoreEngine instance.
1383
+ *
1384
+ * @function
1385
+ */
1386
+ getEngine() {
1387
+ return this._engine;
1388
+ }
1389
+ /**
1390
+ * Return all index names
1391
+ *
1392
+ * @function
1393
+ */
1394
+ async indexes() {
1395
+ const indexes = await this._engine.collection_GetIndexes({
1396
+ name: this.scope.database.getName(),
1397
+ scopeName: this.scope.name,
1398
+ collectionName: this.name,
1399
+ });
1400
+ return indexes.indexes;
1401
+ }
1402
+ /**
1403
+ * send data to the listener
1404
+ *
1405
+ * @function
1406
+ */
1407
+ notifyChangeListeners(data) {
1408
+ this._changeListener(data);
1409
+ }
1410
+ /**
1411
+ * send data to the document change listener
1412
+ *
1413
+ * @function
1414
+ */
1415
+ notifyDocumentChangeListeners(data) {
1416
+ const documentId = data.documentId;
1417
+ const changeListener = this._documentChangeListener.get(documentId);
1418
+ changeListener({
1419
+ documentId: documentId,
1420
+ collection: this,
1421
+ database: this.database,
1422
+ });
1423
+ }
1424
+ /**
1425
+ * Purge a document by id from the collection. If the document doesn’t exist in the
1426
+ * collection, an error will be thrown.
1427
+ *
1428
+ * Throws an error if the collection is deleted or the database is closed.
1429
+ *
1430
+ * @function
1431
+ */
1432
+ purge(document) {
1433
+ return this._engine.collection_PurgeDocument({
1434
+ name: this.database.getName(),
1435
+ scopeName: this.scope.name,
1436
+ collectionName: this.name,
1437
+ docId: document.getId(),
1438
+ });
1439
+ }
1440
+ /**
1441
+ * Purge a document by id from the collection. If the document doesn’t exist in the
1442
+ * collection, an error will be thrown.
1443
+ *
1444
+ * Throws an error if the collection is deleted or the database is closed.
1445
+ *
1446
+ * @function
1447
+ */
1448
+ purgeById(documentId) {
1449
+ return this._engine.collection_PurgeDocument({
1450
+ name: this.database.getName(),
1451
+ scopeName: this.scope.name,
1452
+ collectionName: this.name,
1453
+ docId: documentId,
1454
+ });
1455
+ }
1456
+ /**
1457
+ * Remove the collection change listener.
1458
+ *
1459
+ * Throws an error if the collection is deleted or the database is closed.
1460
+ *
1461
+ * @function
1462
+ */
1463
+ async removeChangeListener(token) {
1464
+ await this._engine.collection_RemoveChangeListener({
1465
+ name: this.database.getName(),
1466
+ scopeName: this.scope.name,
1467
+ collectionName: this.name,
1468
+ changeListenerToken: token,
1469
+ });
1470
+ }
1471
+ /**
1472
+ * Remove the collection document change listener.
1473
+ *
1474
+ * Throws an error if the collection is deleted or the database is closed.
1475
+ *
1476
+ * @function
1477
+ */
1478
+ async removeDocumentChangeListener(token) {
1479
+ await this._engine.collection_RemoveDocumentChangeListener({
1480
+ name: this.database.getName(),
1481
+ scopeName: this.scope.name,
1482
+ collectionName: this.name,
1483
+ changeListenerToken: token,
1484
+ });
1485
+ }
1486
+ /**
1487
+ * Save a document into the collection. The default concurrency control, lastWriteWins, will
1488
+ * be used when there is conflict during save.
1489
+ *
1490
+ * When saving a document that already belongs to a collection, the collection instance of
1491
+ * the document and this collection instance must be the same, otherwise, an
1492
+ * error will be thrown.
1493
+ *
1494
+ * Throws an error if the collection is deleted or the database is closed.
1495
+ *
1496
+ * @function
1497
+ */
1498
+ async save(document, concurrencyControl = null) {
1499
+ const blobString = document.blobsToJsonString();
1500
+ const documentString = document.toJsonString();
1501
+ const ret = await this._engine.collection_Save({
1502
+ id: document.getId(),
1503
+ document: documentString,
1504
+ blobs: blobString,
1505
+ concurrencyControl: concurrencyControl,
1506
+ name: this.scope.database.getName(),
1507
+ scopeName: this.scope.name,
1508
+ collectionName: this.name,
1509
+ });
1510
+ document.setId(ret._id);
1511
+ document.setRevisionID(ret._revId);
1512
+ document.setSequence(ret._sequence);
1513
+ document.setCollection(this);
1514
+ }
1515
+ async setDocumentExpiration(id, expiration) {
1516
+ await this._engine.collection_SetDocumentExpiration({
1517
+ docId: id,
1518
+ name: this.database.getName(),
1519
+ scopeName: this.scope.name,
1520
+ collectionName: this.name,
1521
+ expiration: expiration,
1522
+ });
1523
+ }
1524
+ toJson() {
1525
+ return {
1526
+ name: this.name,
1527
+ scopeName: this.scope.name,
1528
+ databaseName: this.database.getName(),
1529
+ };
1530
+ }
1531
+ uuid() {
1532
+ return this._engine.getUUID();
1533
+ }
1534
+ }
1535
+
1536
+ exports.ConcurrencyControl = void 0;
1537
+ (function (ConcurrencyControl) {
1538
+ // eslint-disable-next-line
1539
+ ConcurrencyControl[ConcurrencyControl["LAST_WRITE_WINS"] = 0] = "LAST_WRITE_WINS";
1540
+ // eslint-disable-next-line
1541
+ ConcurrencyControl[ConcurrencyControl["FAIL_ON_CONFLICT"] = 1] = "FAIL_ON_CONFLICT";
1542
+ })(exports.ConcurrencyControl || (exports.ConcurrencyControl = {}));
1543
+
1544
+ class CouchbaseLiteException extends Error {
1545
+ constructor(
1546
+ // eslint-disable-next-line
1547
+ message,
1548
+ // eslint-disable-next-line
1549
+ domain,
1550
+ // eslint-disable-next-line
1551
+ code) {
1552
+ super();
1553
+ this.message = message;
1554
+ this.domain = domain;
1555
+ this.code = code;
1556
+ }
1557
+ }
1558
+
1559
+ /**
1560
+ * Configuration for opening a database
1561
+ */
1562
+ class DatabaseConfiguration {
1563
+ // eslint-disable-next-line
1564
+ constructor(arg1, arg2) {
1565
+ if (typeof arg1 === 'string') {
1566
+ this.directory = arg1;
1567
+ }
1568
+ else if (arg1 instanceof DatabaseConfiguration) {
1569
+ this.directory = arg1.directory;
1570
+ this.encryptionKey = arg1.encryptionKey;
1571
+ }
1572
+ else {
1573
+ //do nothing
1574
+ this.directory = undefined;
1575
+ }
1576
+ if (typeof arg2 === 'string') {
1577
+ this.encryptionKey = arg2;
1578
+ }
1579
+ }
1580
+ /**
1581
+ * Returns the directory path where the database files are stored
1582
+ * @returns {string} The configured database directory path
1583
+ * @example
1584
+ * const config = new DatabaseConfiguration();
1585
+ * config.setDirectory('/path/to/database');
1586
+ * const dir = config.getDirectory();
1587
+ * // Returns: '/path/to/database'
1588
+ */
1589
+ getDirectory() {
1590
+ return this.directory;
1591
+ }
1592
+ /**
1593
+ * Sets the directory path where the database files will be stored
1594
+ * @param {string} directory - The path to the directory where database files should be stored
1595
+ * @returns {DatabaseConfiguration} The current DatabaseConfiguration instance for method chaining
1596
+ * @example
1597
+ * const config = new DatabaseConfiguration();
1598
+ * config.setDirectory('/path/to/database');
1599
+ * // Or chain with other methods
1600
+ * config.setDirectory('/path/to/database').setEncryptionKey('myKey');
1601
+ */
1602
+ setDirectory(directory) {
1603
+ this.directory = directory;
1604
+ return this;
1605
+ }
1606
+ /**
1607
+ * Returns the encryption key used for database encryption
1608
+ * @returns {string} The configured encryption key, or undefined if no encryption is set
1609
+ * @example
1610
+ * const config = new DatabaseConfiguration();
1611
+ * config.setEncryptionKey('mySecretKey');
1612
+ * const key = config.getEncryptionKey();
1613
+ * // Returns: 'mySecretKey'
1614
+ */
1615
+ getEncryptionKey() {
1616
+ return this.encryptionKey;
1617
+ }
1618
+ /**
1619
+ * Sets the encryption key for the database
1620
+ * @param {string} key - The encryption key to use for database encryption
1621
+ * @returns {DatabaseConfiguration} The current DatabaseConfiguration instance for method chaining
1622
+ * @example
1623
+ * const config = new DatabaseConfiguration();
1624
+ * config.setEncryptionKey('mySecretKey');
1625
+ * // Or chain with other methods
1626
+ * config.setDirectory('/path/to/db').setEncryptionKey('mySecretKey');
1627
+ */
1628
+ setEncryptionKey(key) {
1629
+ this.encryptionKey = key;
1630
+ return this;
1631
+ }
1632
+ }
1633
+
1634
+ class DatabaseLogging {
1635
+ // eslint-disable-next-line
1636
+ constructor(database) {
1637
+ this.database = database;
1638
+ }
1639
+ setFileConfig(config) {
1640
+ return this.database.getEngine().database_SetFileLoggingConfig({
1641
+ name: this.database.getName(),
1642
+ config: config,
1643
+ });
1644
+ }
1645
+ }
1646
+
1647
+ /**
1648
+ * A Parameters object used for setting values to the query parameters defined in the query.
1649
+ */
1650
+ class Parameter {
1651
+ _set(name, value, type) {
1652
+ this.name = name;
1653
+ this.value = value;
1654
+ this.type = type;
1655
+ }
1656
+ setValue(name, value) {
1657
+ this._set(name, value, 'value');
1658
+ }
1659
+ setString(name, value) {
1660
+ this._set(name, value, 'string');
1661
+ }
1662
+ setBoolean(name, value) {
1663
+ this._set(name, value, 'boolean');
1664
+ }
1665
+ setFloat(name, value) {
1666
+ this._set(name, value, 'float');
1667
+ }
1668
+ setDouble(name, value) {
1669
+ this._set(name, value, 'double');
1670
+ }
1671
+ setLong(name, value) {
1672
+ this._set(name, value, 'long');
1673
+ }
1674
+ setInt(name, value) {
1675
+ this._set(name, value, 'int');
1676
+ }
1677
+ setDate(name, value) {
1678
+ this._set(name, value, 'date');
1679
+ }
1680
+ get() {
1681
+ return this;
1682
+ }
1683
+ }
1684
+
1685
+ /**
1686
+ * A Parameters object used for setting values to the query parameters defined in the query.
1687
+ */
1688
+ class Parameters {
1689
+ constructor() {
1690
+ this._parameters = {};
1691
+ }
1692
+ setValue(name, value) {
1693
+ const parameter = new Parameter();
1694
+ parameter.setValue(name, value);
1695
+ this._parameters[name] = parameter;
1696
+ }
1697
+ setString(name, value) {
1698
+ const parameter = new Parameter();
1699
+ parameter.setString(name, value);
1700
+ this._parameters[name] = parameter;
1701
+ }
1702
+ setBoolean(name, value) {
1703
+ const parameter = new Parameter();
1704
+ parameter.setBoolean(name, value);
1705
+ this._parameters[name] = parameter;
1706
+ }
1707
+ setFloat(name, value) {
1708
+ const parameter = new Parameter();
1709
+ parameter.setFloat(name, value);
1710
+ this._parameters[name] = parameter;
1711
+ }
1712
+ setDouble(name, value) {
1713
+ const parameter = new Parameter();
1714
+ parameter.setDouble(name, value);
1715
+ this._parameters[name] = parameter;
1716
+ }
1717
+ setLong(name, value) {
1718
+ const parameter = new Parameter();
1719
+ parameter.setLong(name, value);
1720
+ this._parameters[name] = parameter;
1721
+ }
1722
+ setInt(name, value) {
1723
+ const parameter = new Parameter();
1724
+ parameter.setInt(name, value);
1725
+ this._parameters[name] = parameter;
1726
+ }
1727
+ setDate(name, value) {
1728
+ const parameter = new Parameter();
1729
+ parameter.setDate(name, value.toISOString());
1730
+ this._parameters[name] = parameter;
1731
+ }
1732
+ remove(name) {
1733
+ this._parameters[name] = null;
1734
+ }
1735
+ get() {
1736
+ if (Object.keys(this._parameters).length > 0) {
1737
+ return this._parameters;
1738
+ }
1739
+ else {
1740
+ return {};
1741
+ }
1742
+ }
1743
+ }
1744
+
1745
+ /**
1746
+ * A database query. A Query instance can be constructed by calling
1747
+ * execute or explain.
1748
+ */
1749
+ class Query {
1750
+ constructor(queryString, database) {
1751
+ //used for engine calls
1752
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
1753
+ this._queryString = queryString;
1754
+ this._database = database;
1755
+ this._didStartQueryListener = false;
1756
+ }
1757
+ /**
1758
+ * Adds a query change listener.
1759
+ *
1760
+ * @function
1761
+ */
1762
+ async addChangeListener(listener) {
1763
+ this._changeListener = listener;
1764
+ const token = this._engine.getUUID();
1765
+ if (!this._didStartQueryListener) {
1766
+ await this._engine.query_AddChangeListener({
1767
+ name: this._database.getName(),
1768
+ query: this._queryString,
1769
+ parameters: this.parameters,
1770
+ changeListenerToken: token,
1771
+ }, (data, err) => {
1772
+ if (err) {
1773
+ throw err;
1774
+ }
1775
+ this.notifyChangeListeners(data);
1776
+ });
1777
+ this._didStartQueryListener = true;
1778
+ return token;
1779
+ }
1780
+ else {
1781
+ throw new Error(`Listener for query ${this._queryString} already started`);
1782
+ }
1783
+ }
1784
+ /**
1785
+ * Adds a Parameter object used for setting values to the query parameters defined in the query. All parameters defined in the query must be given values before running the query, or the query will fail.
1786
+ *
1787
+ * @function
1788
+ */
1789
+ addParameter(parameters) {
1790
+ this.parameters = parameters;
1791
+ }
1792
+ /**
1793
+ * Executes the query. The returning an enumerator that returns result rows one at a time.
1794
+ *
1795
+ * The results come from a snapshot of the database taken at the moment -run: is called, so they will not reflect any changes made to the database afterward.
1796
+ *
1797
+ * @function
1798
+ */
1799
+ async execute() {
1800
+ if (this.parameters === undefined) {
1801
+ this.parameters = new Parameters();
1802
+ }
1803
+ const queryResults = await this._database.getEngine().query_Execute({
1804
+ name: this._database.getName(),
1805
+ query: this._queryString,
1806
+ parameters: this.parameters.get(),
1807
+ });
1808
+ const data = queryResults.data;
1809
+ return JSON.parse(data);
1810
+ }
1811
+ /**
1812
+ *
1813
+ * Returns a string describing the implementation of the compiled query. This is intended to be read by a developer for purposes of optimizing the query, especially to add database indexes. It’s not machine-readable and its format may change.
1814
+ *
1815
+ * As currently implemented, the result is two or more lines separated by newline characters:
1816
+ *
1817
+ * The first line is the SQLite SELECT statement.
1818
+ * The subsequent lines are the output of SQLite’s “EXPLAIN QUERY PLAN” command applied to that statement; for help interpreting this, see https://www.sqlite.org/eqp.html . The most important thing to know is that if you see “SCAN TABLE”, it means that SQLite is doing a slow linear scan of the documents instead of using an index.
1819
+ *
1820
+ * @function
1821
+ */
1822
+ async explain() {
1823
+ if (this.parameters === undefined) {
1824
+ this.parameters = new Parameters();
1825
+ }
1826
+ const queryResults = await this._database.getEngine().query_Explain({
1827
+ name: this._database.getName(),
1828
+ query: this._queryString,
1829
+ parameters: this.parameters.get(),
1830
+ });
1831
+ return queryResults.data;
1832
+ }
1833
+ getDatabase() {
1834
+ return this._database;
1835
+ }
1836
+ /**
1837
+ * A Parameters object used for setting values to the query parameters defined in the query. All parameters defined in the query must be given values before running the query, or the query will fail.
1838
+ *
1839
+ * The returned Parameters object will be readonly.
1840
+ *
1841
+ * @function
1842
+ */
1843
+ getParameters() {
1844
+ return this.parameters;
1845
+ }
1846
+ /**
1847
+ * send data to the listener
1848
+ *
1849
+ * @function
1850
+ */
1851
+ notifyChangeListeners(data) {
1852
+ const stringData = data.data;
1853
+ this._changeListener({
1854
+ query: this,
1855
+ error: data.error,
1856
+ results: JSON.parse(stringData),
1857
+ });
1858
+ }
1859
+ /**
1860
+ * Removes a change listener wih the given listener token.
1861
+ *
1862
+ * @function
1863
+ */
1864
+ async removeChangeListener(token) {
1865
+ await this._database.getEngine().query_RemoveChangeListener({
1866
+ changeListenerToken: token,
1867
+ name: this._database.getName(),
1868
+ });
1869
+ }
1870
+ setDatabase(database) {
1871
+ this._database = database;
1872
+ }
1873
+ /**
1874
+ * Returns the query string used to create this Query instance
1875
+ * @returns {string} The original query string
1876
+ * @example
1877
+ * const query = new Query("SELECT * FROM users WHERE age >= $minAge", database);
1878
+ * console.log(query.toString());
1879
+ * // Returns: "SELECT * FROM users WHERE age >= $minAge"
1880
+ *
1881
+ * // Useful for debugging or logging query definitions
1882
+ * console.log(`Current query: ${query}`); // Automatically calls toString()
1883
+ */
1884
+ toString() {
1885
+ return this._queryString;
1886
+ }
1887
+ }
1888
+
1889
+ exports.LogDomain = void 0;
1890
+ (function (LogDomain) {
1891
+ // eslint-disable-next-line
1892
+ LogDomain["ALL"] = "ALL";
1893
+ // eslint-disable-next-line
1894
+ LogDomain["DATABASE"] = "DATABASE";
1895
+ // eslint-disable-next-line
1896
+ LogDomain["NETWORK"] = "NETWORK";
1897
+ // eslint-disable-next-line
1898
+ LogDomain["QUERY"] = "QUERY";
1899
+ // eslint-disable-next-line
1900
+ LogDomain["REPLICATOR"] = "REPLICATOR";
1901
+ })(exports.LogDomain || (exports.LogDomain = {}));
1902
+ exports.LogLevel = void 0;
1903
+ (function (LogLevel) {
1904
+ // eslint-disable-next-line
1905
+ LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
1906
+ // eslint-disable-next-line
1907
+ LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE";
1908
+ // eslint-disable-next-line
1909
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
1910
+ // eslint-disable-next-line
1911
+ LogLevel[LogLevel["WARNING"] = 3] = "WARNING";
1912
+ // eslint-disable-next-line
1913
+ LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
1914
+ // eslint-disable-next-line
1915
+ LogLevel[LogLevel["NONE"] = 5] = "NONE";
1916
+ })(exports.LogLevel || (exports.LogLevel = {}));
1917
+ exports.MaintenanceType = void 0;
1918
+ (function (MaintenanceType) {
1919
+ // eslint-disable-next-line
1920
+ MaintenanceType[MaintenanceType["COMPACT"] = 0] = "COMPACT";
1921
+ // eslint-disable-next-line
1922
+ MaintenanceType[MaintenanceType["REINDEX"] = 1] = "REINDEX";
1923
+ // eslint-disable-next-line
1924
+ MaintenanceType[MaintenanceType["INTEGRITY_CHECK"] = 2] = "INTEGRITY_CHECK";
1925
+ // eslint-disable-next-line
1926
+ MaintenanceType[MaintenanceType["OPTIMIZE"] = 3] = "OPTIMIZE";
1927
+ // eslint-disable-next-line
1928
+ MaintenanceType[MaintenanceType["FULL_OPTIMIZE"] = 4] = "FULL_OPTIMIZE";
1929
+ })(exports.MaintenanceType || (exports.MaintenanceType = {}));
1930
+ /**
1931
+ * A Couchbase Lite database.
1932
+ */
1933
+ class Database {
1934
+ constructor(
1935
+ // eslint-disable-next-line
1936
+ _databaseName,
1937
+ // eslint-disable-next-line
1938
+ _databaseConfig = null) {
1939
+ this._databaseName = _databaseName;
1940
+ this._databaseConfig = _databaseConfig;
1941
+ this._isClosed = false;
1942
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
1943
+ this.log = new DatabaseLogging(this);
1944
+ }
1945
+ getEngine() {
1946
+ return this._engine;
1947
+ }
1948
+ /**
1949
+ * Open a database with the given name and configuration.
1950
+ *
1951
+ * @function
1952
+ */
1953
+ open() {
1954
+ const result = this._engine.database_Open({
1955
+ name: this._databaseName,
1956
+ config: this._databaseConfig,
1957
+ });
1958
+ this._isClosed = false;
1959
+ return result;
1960
+ }
1961
+ /**
1962
+ * Changes the database’s encryption key, or removes
1963
+ * encryption if the new key is nil.
1964
+ *
1965
+ * @function
1966
+ */
1967
+ async changeEncryptionKey(newKey) {
1968
+ await this._engine.database_ChangeEncryptionKey({
1969
+ name: this._databaseName,
1970
+ newKey: newKey,
1971
+ });
1972
+ this._databaseConfig.setEncryptionKey(newKey);
1973
+ }
1974
+ /**
1975
+ * Close the database. This will release all resources associated with the database.
1976
+ *
1977
+ * @function
1978
+ */
1979
+ close() {
1980
+ const result = this._engine.database_Close({ name: this._databaseName });
1981
+ this._isClosed = true;
1982
+ return result;
1983
+ }
1984
+ /**
1985
+ * @deprecated compact is deprecated. Use performMaintenance instead.
1986
+ *
1987
+ * @function
1988
+ */
1989
+ compact() {
1990
+ const args = {
1991
+ name: this._databaseName,
1992
+ maintenanceType: exports.MaintenanceType.COMPACT,
1993
+ };
1994
+ return this._engine.database_PerformMaintenance(args);
1995
+ }
1996
+ /**
1997
+ * Performs database maintenance.
1998
+ *
1999
+ * @function
2000
+ */
2001
+ performMaintenance(maintenanceType) {
2002
+ const args = { name: this._databaseName, maintenanceType: maintenanceType };
2003
+ return this._engine.database_PerformMaintenance(args);
2004
+ }
2005
+ /**
2006
+ * Copy database
2007
+ *
2008
+ * @function
2009
+ */
2010
+ copy(path, name, config) {
2011
+ return this._engine.database_Copy({
2012
+ name: this._databaseName,
2013
+ path: path,
2014
+ newName: name,
2015
+ config: config,
2016
+ });
2017
+ }
2018
+ /**
2019
+ * Deletes a database.
2020
+ *
2021
+ * @function
2022
+ */
2023
+ deleteDatabase() {
2024
+ if (this._isClosed) {
2025
+ throw new Error('Cannot delete a closed database using this API. Open the database first.');
2026
+ }
2027
+ return this._engine.database_Delete({ name: this._databaseName });
2028
+ }
2029
+ /**
2030
+ * Deletes a database.
2031
+ *
2032
+ * @function
2033
+ */
2034
+ static async deleteDatabase(databaseName, directory) {
2035
+ const engine = EngineLocator.getEngine(EngineLocator.key);
2036
+ const args = {
2037
+ databaseName: databaseName,
2038
+ directory: directory,
2039
+ };
2040
+ await engine.database_DeleteWithPath(args);
2041
+ }
2042
+ /**
2043
+ * Return the database's path.
2044
+ *
2045
+ * @function
2046
+ */
2047
+ async getPath() {
2048
+ return (await this._engine.database_GetPath({ name: this._databaseName }))
2049
+ .path;
2050
+ }
2051
+ /**
2052
+ * Checks whether a database of the given name exists in the given directory or not.
2053
+ *
2054
+ * @function
2055
+ */
2056
+ static async exists(name, directory) {
2057
+ const engine = EngineLocator.getEngine(EngineLocator.key);
2058
+ const args = {
2059
+ databaseName: name,
2060
+ directory: directory,
2061
+ };
2062
+ const ret = await engine.database_Exists(args);
2063
+ return ret.exists;
2064
+ }
2065
+ /**
2066
+ * Return the database name
2067
+ *
2068
+ * @function
2069
+ */
2070
+ getName() {
2071
+ return this._databaseName;
2072
+ }
2073
+ /**
2074
+ * Returns a READONLY config object which will throw a runtime exception when any setter methods are called.
2075
+ *
2076
+ * @function
2077
+ */
2078
+ getConfig() {
2079
+ return this._databaseConfig;
2080
+ }
2081
+ /**
2082
+ * TODO - Fix with QUEUE
2083
+ */
2084
+ inBatch(fn) {
2085
+ fn();
2086
+ return Promise.reject(null);
2087
+ }
2088
+ /**
2089
+ * Set log level for the given log domain.
2090
+ *
2091
+ * @function
2092
+ */
2093
+ static setLogLevel(domain, level) {
2094
+ const engine = EngineLocator.getEngine(EngineLocator.key);
2095
+ return engine.database_SetLogLevel({
2096
+ domain: domain,
2097
+ logLevel: level,
2098
+ });
2099
+ }
2100
+ /**
2101
+ * Set log level for the given log domain.
2102
+ *
2103
+ * @function
2104
+ */
2105
+ setLogLevel(domain, level) {
2106
+ return this._engine.database_SetLogLevel({
2107
+ domain: domain,
2108
+ logLevel: level,
2109
+ });
2110
+ }
2111
+ /**
2112
+ * Get the default Scope.
2113
+ *
2114
+ * @function
2115
+ */
2116
+ async defaultScope() {
2117
+ const scope = await this._engine.scope_GetDefault({
2118
+ name: this._databaseName,
2119
+ });
2120
+ return new Scope(scope.name, this);
2121
+ }
2122
+ /**
2123
+ * Get a scope object by name. As the scope cannot exist by itself without having a collection, null value will be returned if there are no collections under the given scope’s name. Note: The default scope is exceptional, and it will always be returned.
2124
+ *
2125
+ * @function
2126
+ */
2127
+ async scope(scopeName) {
2128
+ try {
2129
+ const scope = await this._engine.scope_GetScope({
2130
+ name: this._databaseName,
2131
+ scopeName: scopeName,
2132
+ });
2133
+ return new Scope(scope.name, this);
2134
+ }
2135
+ catch {
2136
+ return undefined;
2137
+ }
2138
+ }
2139
+ /**
2140
+ * Get scope names that have at least one collection. Note: the default scope is exceptional as it will always be listed even though there are no collections under it.
2141
+ *
2142
+ * @function
2143
+ */
2144
+ async scopes() {
2145
+ const results = await this._engine.scope_GetScopes({
2146
+ name: this._databaseName,
2147
+ });
2148
+ const scopes = [];
2149
+ for (const scope of results.scopes) {
2150
+ scopes.push(new Scope(scope.name, this));
2151
+ }
2152
+ return scopes;
2153
+ }
2154
+ /**
2155
+ * Get the default Collection.
2156
+ *
2157
+ * @function
2158
+ */
2159
+ async defaultCollection() {
2160
+ const col = await this._engine.collection_GetDefault({
2161
+ name: this._databaseName,
2162
+ });
2163
+ const scope = new Scope(col.scope.name, this);
2164
+ return new Collection(col.name, scope, this);
2165
+ }
2166
+ // eslint-disable-next-line no-dupe-class-members
2167
+ async collection(collectionName, scopeOrName) {
2168
+ let col;
2169
+ if (typeof scopeOrName === 'string') {
2170
+ col = await this._engine.collection_GetCollection({
2171
+ name: this._databaseName,
2172
+ collectionName: collectionName,
2173
+ scopeName: scopeOrName,
2174
+ });
2175
+ }
2176
+ else if (scopeOrName instanceof Scope) {
2177
+ col = await this._engine.collection_GetCollection({
2178
+ name: this._databaseName,
2179
+ collectionName: collectionName,
2180
+ scopeName: scopeOrName.name,
2181
+ });
2182
+ }
2183
+ else {
2184
+ col = await this._engine.collection_GetCollection({
2185
+ name: this._databaseName,
2186
+ collectionName: collectionName,
2187
+ scopeName: Database.defaultScopeName,
2188
+ });
2189
+ }
2190
+ const scope = new Scope(col.scope.name, this);
2191
+ return new Collection(col.name, scope, this);
2192
+ }
2193
+ // eslint-disable-next-line
2194
+ async collections(scopeOrName) {
2195
+ const collections = [];
2196
+ let colResults;
2197
+ if (typeof scopeOrName === 'string') {
2198
+ colResults = await this._engine.collection_GetCollections({
2199
+ name: this._databaseName,
2200
+ scopeName: scopeOrName,
2201
+ });
2202
+ }
2203
+ else if (scopeOrName instanceof Scope) {
2204
+ colResults = await this._engine.collection_GetCollections({
2205
+ name: this._databaseName,
2206
+ scopeName: scopeOrName.name,
2207
+ });
2208
+ }
2209
+ else {
2210
+ colResults = await this._engine.collection_GetCollections({
2211
+ name: this._databaseName,
2212
+ scopeName: Database.defaultScopeName,
2213
+ });
2214
+ }
2215
+ for (const col of colResults.collections) {
2216
+ const scope = new Scope(col.scope.name, this);
2217
+ collections.push(new Collection(col.name, scope, this));
2218
+ }
2219
+ return collections;
2220
+ }
2221
+ // eslint-disable-next-line
2222
+ async createCollection(collectionName, scopeOrName) {
2223
+ let col;
2224
+ if (typeof scopeOrName === 'string') {
2225
+ col = await this._engine.collection_CreateCollection({
2226
+ name: this._databaseName,
2227
+ collectionName: collectionName,
2228
+ scopeName: scopeOrName,
2229
+ });
2230
+ }
2231
+ else if (scopeOrName instanceof Scope) {
2232
+ col = await this._engine.collection_CreateCollection({
2233
+ name: this._databaseName,
2234
+ collectionName: collectionName,
2235
+ scopeName: scopeOrName.name,
2236
+ });
2237
+ }
2238
+ else {
2239
+ col = await this._engine.collection_CreateCollection({
2240
+ name: this._databaseName,
2241
+ collectionName: collectionName,
2242
+ scopeName: Database.defaultScopeName,
2243
+ });
2244
+ }
2245
+ const scope = new Scope(col.scope.name, this);
2246
+ return new Collection(col.name, scope, this);
2247
+ }
2248
+ // eslint-disable-next-line
2249
+ deleteCollection(collectionOrName, scopeName) {
2250
+ if (typeof collectionOrName === 'string' && scopeName !== undefined) {
2251
+ return this._engine.collection_DeleteCollection({
2252
+ name: this._databaseName,
2253
+ collectionName: collectionOrName,
2254
+ scopeName: scopeName,
2255
+ });
2256
+ }
2257
+ else if (collectionOrName instanceof Collection) {
2258
+ return this._engine.collection_DeleteCollection({
2259
+ name: this._databaseName,
2260
+ collectionName: collectionOrName.name,
2261
+ scopeName: collectionOrName.scope.name,
2262
+ });
2263
+ }
2264
+ else {
2265
+ throw new Error('Invalid arguments');
2266
+ }
2267
+ }
2268
+ /**
2269
+ * @deprecated deleteDocument is deprecated. Use Collection deleteDocument instead.
2270
+ *
2271
+ * @function
2272
+ */
2273
+ deleteDocument(document, concurrencyControl = null) {
2274
+ const id = document.getId();
2275
+ return this._engine.database_DeleteDocument({
2276
+ name: this._databaseName,
2277
+ docId: id,
2278
+ concurrencyControl: concurrencyControl,
2279
+ });
2280
+ }
2281
+ /**
2282
+ * @deprecated purgeDocument is deprecated. Use Collection purgeDocument instead.
2283
+ *
2284
+ * @function
2285
+ */
2286
+ purgeDocument(document) {
2287
+ return this._engine.database_PurgeDocument({
2288
+ name: this._databaseName,
2289
+ docId: document.getId(),
2290
+ });
2291
+ }
2292
+ /**
2293
+ * @deprecated getCount is deprecated. Use Collection getCount instead.
2294
+ *
2295
+ * @function
2296
+ */
2297
+ async getCount() {
2298
+ const count = await this._engine.database_GetCount({
2299
+ name: this._databaseName,
2300
+ });
2301
+ return Promise.resolve(count.count);
2302
+ }
2303
+ /**
2304
+ * @deprecated getDocument is deprecated. Use Collection getDocument instead.
2305
+ *
2306
+ * @function
2307
+ */
2308
+ async getDocument(id) {
2309
+ const docJson = await this._engine.database_GetDocument({
2310
+ name: this._databaseName,
2311
+ docId: id,
2312
+ });
2313
+ if (docJson) {
2314
+ // @ts-expect-error - _data is used in getData()
2315
+ const data = docJson._data;
2316
+ // @ts-expect-error - _sequence is used in getSequence()
2317
+ const sequence = docJson._sequence;
2318
+ // @ts-expect-error _id exists in documents
2319
+ const retId = docJson._id;
2320
+ return Promise.resolve(new Document(retId, sequence, data));
2321
+ }
2322
+ else {
2323
+ return Promise.resolve(null);
2324
+ }
2325
+ }
2326
+ /**
2327
+ * @deprecated save is deprecated. Use Collection save instead.
2328
+ *
2329
+ * @function
2330
+ */
2331
+ async save(document, concurrencyControl = null) {
2332
+ const ret = await this._engine.database_Save({
2333
+ name: this._databaseName,
2334
+ id: document.getId(),
2335
+ document: document.toJsonString(),
2336
+ blobs: document.blobsToJsonString(),
2337
+ concurrencyControl: concurrencyControl,
2338
+ });
2339
+ const id = ret._id;
2340
+ document.setId(id);
2341
+ }
2342
+ /**
2343
+ * @deprecated createIndex is deprecated. Use Collection createIndex instead.
2344
+ *
2345
+ * @function
2346
+ */
2347
+ createIndex(indexName, index) {
2348
+ return this._engine.database_CreateIndex({
2349
+ name: this._databaseName,
2350
+ indexName: indexName,
2351
+ index: index.toJson(),
2352
+ });
2353
+ }
2354
+ /**
2355
+ * @deprecated getIndexes is deprecated. Use Collection getIndexes instead.
2356
+ *
2357
+ * @function
2358
+ */
2359
+ async getIndexes() {
2360
+ return (await this._engine.database_GetIndexes({
2361
+ name: this._databaseName,
2362
+ })).indexes;
2363
+ }
2364
+ /**
2365
+ * @deprecated deleteIndex is deprecated. Use Collection deleteIndex instead.
2366
+ *
2367
+ * @function
2368
+ */
2369
+ deleteIndex(indexName) {
2370
+ return this._engine.database_DeleteIndex({
2371
+ name: this._databaseName,
2372
+ indexName: indexName,
2373
+ });
2374
+ }
2375
+ /**
2376
+ * Creates a Query object from the given query string.
2377
+ *
2378
+ * @function
2379
+ */
2380
+ createQuery(queryString) {
2381
+ return new Query(queryString, this);
2382
+ }
2383
+ }
2384
+ /**
2385
+ * The default scope name constant
2386
+ *
2387
+ * @property
2388
+ */
2389
+ Database.defaultScopeName = '_default';
2390
+ /**
2391
+ * The default collection name constant
2392
+ *
2393
+ * @property
2394
+ */
2395
+ Database.defaultCollectionName = '_default';
2396
+
2397
+ exports.ReplicatedDocumentFlag = void 0;
2398
+ (function (ReplicatedDocumentFlag) {
2399
+ // eslint-disable-next-line
2400
+ ReplicatedDocumentFlag["DELETED"] = "DELETED";
2401
+ // eslint-disable-next-line
2402
+ ReplicatedDocumentFlag["ACCESS_REMOVED"] = "ACCESS_REMOVED";
2403
+ })(exports.ReplicatedDocumentFlag || (exports.ReplicatedDocumentFlag = {}));
2404
+ class ReplicatedDocument {
2405
+ // eslint-disable-next-line
2406
+ constructor(id, flags, error = undefined, scopeName, collectionName) {
2407
+ this.id = id;
2408
+ this.flags = flags;
2409
+ this.error = error;
2410
+ this.scopeName = scopeName;
2411
+ this.collectionName = collectionName;
2412
+ }
2413
+ getId() {
2414
+ return this.id;
2415
+ }
2416
+ getFlags() {
2417
+ return this.flags;
2418
+ }
2419
+ getError() {
2420
+ return this.error;
2421
+ }
2422
+ }
2423
+ function isReplicatedDocumentRepresentation(obj) {
2424
+ try {
2425
+ const object = obj;
2426
+ object.flags.forEach((flag) => {
2427
+ const flagTest = (exports.ReplicatedDocumentFlag)[flag];
2428
+ if (flagTest === undefined) {
2429
+ throw 'unrecognized replication flag ' + flag;
2430
+ }
2431
+ });
2432
+ if (object.id === null) {
2433
+ throw 'document id cannot be null';
2434
+ }
2435
+ if (object.error !== null) {
2436
+ if (object.error.message === null) {
2437
+ throw 'document error is incomplete';
2438
+ }
2439
+ }
2440
+ return true;
2441
+ }
2442
+ catch (e) {
2443
+ console.warn('Invalid ReplicatedDocumentRepresentation:', e);
2444
+ return false;
2445
+ }
2446
+ }
2447
+
2448
+ class DocumentReplication {
2449
+ // eslint-disable-next-line
2450
+ constructor(isPush, documents) {
2451
+ this.isPush = isPush;
2452
+ this.documents = documents;
2453
+ }
2454
+ getIsPush() {
2455
+ return this.isPush;
2456
+ }
2457
+ getDocuments() {
2458
+ return this.documents;
2459
+ }
2460
+ }
2461
+ function isDocumentReplicationRepresentation(obj) {
2462
+ try {
2463
+ const object = obj;
2464
+ object.documents.forEach((document) => {
2465
+ if (!isReplicatedDocumentRepresentation(document)) {
2466
+ throw 'invalid replicated document';
2467
+ }
2468
+ });
2469
+ const isPush = object.isPush;
2470
+ if (isPush === undefined) {
2471
+ throw 'unrecognized replication isPush ';
2472
+ }
2473
+ return true;
2474
+ }
2475
+ catch (e) {
2476
+ console.warn('Invalid DocumentReplicationRepresentation:', e);
2477
+ return false;
2478
+ }
2479
+ }
2480
+
2481
+ class Expression {
2482
+ static value(value) {
2483
+ return new ValueExpression(value);
2484
+ }
2485
+ static string(value) {
2486
+ return new ValueExpression(value);
2487
+ }
2488
+ static number(value) {
2489
+ return new ValueExpression(value);
2490
+ }
2491
+ static intValue(value) {
2492
+ return new ValueExpression(value);
2493
+ }
2494
+ static longValue(value) {
2495
+ return new ValueExpression(value);
2496
+ }
2497
+ static floatValue(value) {
2498
+ return new ValueExpression(value);
2499
+ }
2500
+ static doubleValue(value) {
2501
+ return new ValueExpression(value);
2502
+ }
2503
+ static booleanValue(value) {
2504
+ return new ValueExpression(value);
2505
+ }
2506
+ static date(value) {
2507
+ return new ValueExpression(value);
2508
+ }
2509
+ static all() {
2510
+ return new PropertyExpression('*');
2511
+ }
2512
+ static property(property) {
2513
+ return new PropertyExpression(property);
2514
+ }
2515
+ static parameter(name) {
2516
+ return new ParameterExpression(name);
2517
+ }
2518
+ static negated(expression) {
2519
+ return new CompoundExpression([expression], CompoundExpression.OpType.Not);
2520
+ }
2521
+ static not(expression) {
2522
+ return Expression.negated(expression);
2523
+ }
2524
+ multiply(expression) {
2525
+ return new BinaryExpression(this, expression, exports.BinaryOpType.Multiply);
2526
+ }
2527
+ divide(expression) {
2528
+ return new BinaryExpression(this, expression, exports.BinaryOpType.Divide);
2529
+ }
2530
+ modulo(expression) {
2531
+ return new BinaryExpression(this, expression, exports.BinaryOpType.Modulus);
2532
+ }
2533
+ /**
2534
+ * Create an add expression to add the given expression to the current expression
2535
+ */
2536
+ add(expression) {
2537
+ return new BinaryExpression(this, expression, exports.BinaryOpType.Add);
2538
+ }
2539
+ subtract(expression) {
2540
+ return new BinaryExpression(this, expression, exports.BinaryOpType.Subtract);
2541
+ }
2542
+ lessThan(expression) {
2543
+ return new BinaryExpression(this, expression, exports.BinaryOpType.LessThan);
2544
+ }
2545
+ lessThanOrEqualTo(expression) {
2546
+ return new BinaryExpression(this, expression, exports.BinaryOpType.LessThanOrEqualTo);
2547
+ }
2548
+ greaterThan(expression) {
2549
+ return new BinaryExpression(this, expression, exports.BinaryOpType.GreaterThan);
2550
+ }
2551
+ greaterThanOrEqualTo(expression) {
2552
+ return new BinaryExpression(this, expression, exports.BinaryOpType.GreaterThanOrEqualTo);
2553
+ }
2554
+ equalTo(expression) {
2555
+ return new BinaryExpression(this, expression, BinaryExpression.OpType.EqualTo);
2556
+ }
2557
+ notEqualTo(expression) {
2558
+ return new BinaryExpression(this, expression, BinaryExpression.OpType.NotEqualTo);
2559
+ }
2560
+ and(expression) {
2561
+ return new CompoundExpression([this, expression], exports.CompoundExpressionOpType.And);
2562
+ }
2563
+ or(expression) {
2564
+ return new CompoundExpression([this, expression], exports.CompoundExpressionOpType.Or);
2565
+ }
2566
+ like(expression) {
2567
+ return new BinaryExpression(this, expression, BinaryExpression.OpType.Like);
2568
+ }
2569
+ regex(expression) {
2570
+ return new BinaryExpression(this, expression, BinaryExpression.OpType.RegexLike);
2571
+ }
2572
+ is(expression) {
2573
+ return new BinaryExpression(this, expression, BinaryExpression.OpType.Is);
2574
+ }
2575
+ isNot(expression) {
2576
+ return new BinaryExpression(this, expression, BinaryExpression.OpType.IsNot);
2577
+ }
2578
+ between(expression1, expression2) {
2579
+ const aggr = new AggregateExpression([expression1, expression2]);
2580
+ return new BinaryExpression(this, aggr, BinaryExpression.OpType.Between);
2581
+ }
2582
+ isNullOrMissing() {
2583
+ return new UnaryExpression(this, UnaryExpression.OpType.Null).or(new UnaryExpression(this, UnaryExpression.OpType.Missing));
2584
+ }
2585
+ notNullOrMissing() {
2586
+ return Expression.negated(this.isNullOrMissing());
2587
+ }
2588
+ collate(collation) {
2589
+ return new CollationExpression(this, collation);
2590
+ }
2591
+ in(...expressions) {
2592
+ const aggr = new AggregateExpression(expressions);
2593
+ return new BinaryExpression(this, aggr, BinaryExpression.OpType.In);
2594
+ }
2595
+ }
2596
+ class PropertyExpression extends Expression {
2597
+ constructor(keyPath, _from = '', columnName = '') {
2598
+ super();
2599
+ this.keyPath = keyPath;
2600
+ this._from = _from;
2601
+ this.columnName = columnName;
2602
+ }
2603
+ from(alias) {
2604
+ return new PropertyExpression(this.keyPath, alias);
2605
+ }
2606
+ static allFrom(from) {
2607
+ const colName = from || PropertyExpression.kCBLAllPropertiesName;
2608
+ return new PropertyExpression(PropertyExpression.kCBLAllPropertiesName, from, colName);
2609
+ }
2610
+ asJSON() {
2611
+ const json = [];
2612
+ if (this._from !== null && this._from !== '') {
2613
+ json.push('.' + this._from + '.' + this.keyPath);
2614
+ }
2615
+ else {
2616
+ json.push('.' + this.keyPath);
2617
+ }
2618
+ return json;
2619
+ }
2620
+ getColumnName() {
2621
+ if (!this.columnName) {
2622
+ const paths = this.keyPath.split('.');
2623
+ this.columnName = paths.pop();
2624
+ }
2625
+ return this.columnName;
2626
+ }
2627
+ }
2628
+ PropertyExpression.kCBLAllPropertiesName = '';
2629
+ class ValueExpression extends Expression {
2630
+ constructor(value) {
2631
+ super();
2632
+ this.value = value;
2633
+ }
2634
+ asJSON() {
2635
+ if (this.value instanceof Date) {
2636
+ return this.value.toISOString();
2637
+ }
2638
+ else {
2639
+ return this.value;
2640
+ }
2641
+ }
2642
+ }
2643
+ exports.BinaryOpType = void 0;
2644
+ (function (BinaryOpType) {
2645
+ BinaryOpType[BinaryOpType["Add"] = 0] = "Add";
2646
+ BinaryOpType[BinaryOpType["Between"] = 1] = "Between";
2647
+ BinaryOpType[BinaryOpType["Divide"] = 2] = "Divide";
2648
+ BinaryOpType[BinaryOpType["EqualTo"] = 3] = "EqualTo";
2649
+ BinaryOpType[BinaryOpType["GreaterThan"] = 4] = "GreaterThan";
2650
+ BinaryOpType[BinaryOpType["GreaterThanOrEqualTo"] = 5] = "GreaterThanOrEqualTo";
2651
+ BinaryOpType[BinaryOpType["In"] = 6] = "In";
2652
+ BinaryOpType[BinaryOpType["Is"] = 7] = "Is";
2653
+ BinaryOpType[BinaryOpType["IsNot"] = 8] = "IsNot";
2654
+ BinaryOpType[BinaryOpType["LessThan"] = 9] = "LessThan";
2655
+ BinaryOpType[BinaryOpType["LessThanOrEqualTo"] = 10] = "LessThanOrEqualTo";
2656
+ BinaryOpType[BinaryOpType["Like"] = 11] = "Like";
2657
+ BinaryOpType[BinaryOpType["Modulus"] = 12] = "Modulus";
2658
+ BinaryOpType[BinaryOpType["Multiply"] = 13] = "Multiply";
2659
+ BinaryOpType[BinaryOpType["NotEqualTo"] = 14] = "NotEqualTo";
2660
+ BinaryOpType[BinaryOpType["Subtract"] = 15] = "Subtract";
2661
+ BinaryOpType[BinaryOpType["RegexLike"] = 16] = "RegexLike";
2662
+ })(exports.BinaryOpType || (exports.BinaryOpType = {}));
2663
+ class BinaryExpression extends Expression {
2664
+ constructor(lhs, rhs, type) {
2665
+ super();
2666
+ this.lhs = lhs;
2667
+ this.rhs = rhs;
2668
+ this.type = type;
2669
+ }
2670
+ asJSON() {
2671
+ const json = [];
2672
+ switch (this.type) {
2673
+ case exports.BinaryOpType.Add:
2674
+ json.push('+');
2675
+ break;
2676
+ case exports.BinaryOpType.Between:
2677
+ json.push('BETWEEN');
2678
+ break;
2679
+ case exports.BinaryOpType.Divide:
2680
+ json.push('/');
2681
+ break;
2682
+ case exports.BinaryOpType.EqualTo:
2683
+ json.push('=');
2684
+ break;
2685
+ case exports.BinaryOpType.GreaterThan:
2686
+ json.push('>');
2687
+ break;
2688
+ case exports.BinaryOpType.GreaterThanOrEqualTo:
2689
+ json.push('>=');
2690
+ break;
2691
+ case exports.BinaryOpType.In:
2692
+ json.push('IN');
2693
+ break;
2694
+ case exports.BinaryOpType.Is:
2695
+ json.push('IS');
2696
+ break;
2697
+ case exports.BinaryOpType.IsNot:
2698
+ json.push('IS NOT');
2699
+ break;
2700
+ case exports.BinaryOpType.LessThan:
2701
+ json.push('<');
2702
+ break;
2703
+ case exports.BinaryOpType.LessThanOrEqualTo:
2704
+ json.push('<=');
2705
+ break;
2706
+ case exports.BinaryOpType.Like:
2707
+ json.push('LIKE');
2708
+ break;
2709
+ case exports.BinaryOpType.Modulus:
2710
+ json.push('%');
2711
+ break;
2712
+ case exports.BinaryOpType.Multiply:
2713
+ json.push('*');
2714
+ break;
2715
+ case exports.BinaryOpType.NotEqualTo:
2716
+ json.push('!=');
2717
+ break;
2718
+ case exports.BinaryOpType.RegexLike:
2719
+ json.push('regexp_like()');
2720
+ break;
2721
+ case exports.BinaryOpType.Subtract:
2722
+ json.push('-');
2723
+ break;
2724
+ }
2725
+ json.push(this.lhs.asJSON());
2726
+ if (this.type === exports.BinaryOpType.Between) {
2727
+ // "between"'s RHS is an aggregate of the min and max, but the min and max need to be
2728
+ // written out as parameters to the BETWEEN operation:
2729
+ const rangeExprs = this.rhs.getExpressions();
2730
+ json.push(rangeExprs[0].asJSON());
2731
+ json.push(rangeExprs[1].asJSON());
2732
+ }
2733
+ else {
2734
+ json.push(this.rhs.asJSON());
2735
+ }
2736
+ return json;
2737
+ }
2738
+ }
2739
+ BinaryExpression.OpType = exports.BinaryOpType;
2740
+ class AggregateExpression extends Expression {
2741
+ constructor(expressions) {
2742
+ super();
2743
+ this.expressions = expressions;
2744
+ }
2745
+ getExpressions() {
2746
+ return this.expressions;
2747
+ }
2748
+ asJSON() {
2749
+ const json = [];
2750
+ json.push('[]');
2751
+ for (let expr of this.expressions) {
2752
+ json.push(expr.asJSON());
2753
+ }
2754
+ return json;
2755
+ }
2756
+ }
2757
+ class ParameterExpression extends Expression {
2758
+ constructor(name) {
2759
+ super();
2760
+ this.name = name;
2761
+ }
2762
+ asJSON() {
2763
+ return ['$' + this.name];
2764
+ }
2765
+ }
2766
+ exports.CompoundExpressionOpType = void 0;
2767
+ (function (CompoundExpressionOpType) {
2768
+ CompoundExpressionOpType[CompoundExpressionOpType["And"] = 0] = "And";
2769
+ CompoundExpressionOpType[CompoundExpressionOpType["Or"] = 1] = "Or";
2770
+ CompoundExpressionOpType[CompoundExpressionOpType["Not"] = 2] = "Not";
2771
+ })(exports.CompoundExpressionOpType || (exports.CompoundExpressionOpType = {}));
2772
+ class CompoundExpression extends Expression {
2773
+ constructor(subexpressions, type) {
2774
+ super();
2775
+ this.subexpressions = subexpressions;
2776
+ this.type = type;
2777
+ }
2778
+ asJSON() {
2779
+ const json = [];
2780
+ switch (this.type) {
2781
+ case exports.CompoundExpressionOpType.And:
2782
+ json.push('AND');
2783
+ break;
2784
+ case exports.CompoundExpressionOpType.Or:
2785
+ json.push('OR');
2786
+ break;
2787
+ case exports.CompoundExpressionOpType.Not:
2788
+ json.push('NOT');
2789
+ break;
2790
+ }
2791
+ json.push(...this.subexpressions.map((s) => s.asJSON()));
2792
+ return json;
2793
+ }
2794
+ }
2795
+ CompoundExpression.OpType = exports.CompoundExpressionOpType;
2796
+ exports.UnaryExpressionOpType = void 0;
2797
+ (function (UnaryExpressionOpType) {
2798
+ UnaryExpressionOpType[UnaryExpressionOpType["Missing"] = 0] = "Missing";
2799
+ UnaryExpressionOpType[UnaryExpressionOpType["NotMissing"] = 1] = "NotMissing";
2800
+ UnaryExpressionOpType[UnaryExpressionOpType["NotNull"] = 2] = "NotNull";
2801
+ UnaryExpressionOpType[UnaryExpressionOpType["Null"] = 3] = "Null";
2802
+ })(exports.UnaryExpressionOpType || (exports.UnaryExpressionOpType = {}));
2803
+ class UnaryExpression extends Expression {
2804
+ constructor(operand, type) {
2805
+ super();
2806
+ this.operand = operand;
2807
+ this.type = type;
2808
+ if (operand == null)
2809
+ throw new Error('operand is null.');
2810
+ }
2811
+ asJSON() {
2812
+ const opd = this.operand.asJSON();
2813
+ switch (this.type) {
2814
+ case exports.UnaryExpressionOpType.Missing: {
2815
+ return ['IS', opd, ['MISSING']];
2816
+ }
2817
+ case exports.UnaryExpressionOpType.NotMissing: {
2818
+ return ['IS NOT', opd, ['MISSING']];
2819
+ }
2820
+ case exports.UnaryExpressionOpType.Null: {
2821
+ return ['IS', opd, null];
2822
+ }
2823
+ case exports.UnaryExpressionOpType.NotNull: {
2824
+ return ['IS NOT', opd, null];
2825
+ }
2826
+ default:
2827
+ return [];
2828
+ }
2829
+ }
2830
+ }
2831
+ UnaryExpression.OpType = exports.UnaryExpressionOpType;
2832
+ class CollationExpression extends Expression {
2833
+ constructor(operand, collation) {
2834
+ super();
2835
+ this.operand = operand;
2836
+ this.collation = collation;
2837
+ }
2838
+ asJSON() {
2839
+ return ['COLLATE', this.collation.asJSON(), this.operand.asJSON()];
2840
+ }
2841
+ }
2842
+ class FunctionExpression extends Expression {
2843
+ constructor(func, params) {
2844
+ super();
2845
+ this.func = func;
2846
+ this.params = params;
2847
+ }
2848
+ asJSON() {
2849
+ const json = [this.func];
2850
+ json.push(...this.params.map((p) => p.asJSON()));
2851
+ return json;
2852
+ }
2853
+ }
2854
+
2855
+ class FileSystem {
2856
+ constructor() {
2857
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
2858
+ }
2859
+ async getDefaultPath() {
2860
+ const results = await this._engine.file_GetDefaultPath();
2861
+ return results.path;
2862
+ }
2863
+ async getFilesInDirectory(path) {
2864
+ return this._engine.file_GetFileNamesInDirectory({ path });
2865
+ }
2866
+ }
2867
+
2868
+ /**
2869
+ * Full-text expression
2870
+ */
2871
+ class FullTextExpression {
2872
+ constructor(name) {
2873
+ this.name = name;
2874
+ }
2875
+ /**
2876
+ * Creates a full-text expression with the given full-text index name.
2877
+ *
2878
+ * @param name The full-text index name.
2879
+ * @return The full-text expression.
2880
+ */
2881
+ static index(name) {
2882
+ return new FullTextExpression(name);
2883
+ }
2884
+ /**
2885
+ * Creates a full-text match expression with the given search text.
2886
+ *
2887
+ * @param query The search text
2888
+ * @return The full-text match expression
2889
+ */
2890
+ match(query) {
2891
+ return new FullTextMatchExpression(this.name, query);
2892
+ }
2893
+ }
2894
+ class FullTextMatchExpression extends Expression {
2895
+ constructor(indexName, text) {
2896
+ super();
2897
+ this.indexName = indexName;
2898
+ this.text = text;
2899
+ }
2900
+ asJSON() {
2901
+ return ['MATCH()', this.indexName, this.text];
2902
+ }
2903
+ }
2904
+
2905
+ /**
2906
+ * Index for Full-Text search
2907
+ */
2908
+ class FullTextIndex extends AbstractIndex {
2909
+ constructor(...indexItems) {
2910
+ super();
2911
+ this._language = FullTextIndex.getDefaultLanguage();
2912
+ this._ignoreAccents = false;
2913
+ this.indexItems = indexItems;
2914
+ }
2915
+ /**
2916
+ * The language code which is an ISO-639 language such as "en", "fr", etc.
2917
+ * Setting the language code affects how word breaks and word stems are parsed.
2918
+ * Without setting the value, the current locale's language will be used. Setting
2919
+ * a nil or "" value to disable the language features.
2920
+ */
2921
+ setLanguage(language) {
2922
+ this._language = language;
2923
+ return this;
2924
+ }
2925
+ /**
2926
+ * Set the true value to ignore accents/diacritical marks. The default value is false.
2927
+ */
2928
+ setIgnoreAccents(ignoreAccents) {
2929
+ this._ignoreAccents = ignoreAccents;
2930
+ return this;
2931
+ }
2932
+ type() {
2933
+ return exports.IndexType.FullText;
2934
+ }
2935
+ language() {
2936
+ return this._language;
2937
+ }
2938
+ ignoreAccents() {
2939
+ return this._ignoreAccents;
2940
+ }
2941
+ items() {
2942
+ const items = [];
2943
+ for (let item of this.indexItems) {
2944
+ items.push(item.expression.asJSON());
2945
+ }
2946
+ return items;
2947
+ }
2948
+ toJson() {
2949
+ return {
2950
+ type: 'full-text',
2951
+ language: this._language,
2952
+ ignoreAccents: this._ignoreAccents,
2953
+ items: this.items(),
2954
+ };
2955
+ }
2956
+ static getDefaultLanguage() {
2957
+ return 'en';
2958
+ //return Locale.getDefault().getLanguage();
2959
+ }
2960
+ }
2961
+ /**
2962
+ * Full-text Index Item.
2963
+ */
2964
+ class FullTextIndexItem {
2965
+ constructor(expression) {
2966
+ this.expression = expression;
2967
+ this.expression = expression;
2968
+ }
2969
+ /**
2970
+ * Creates a full-text search index item with the given property.
2971
+ *
2972
+ * @param property A property used to perform the match operation against with.
2973
+ * @return The full-text search index item.
2974
+ */
2975
+ static property(property) {
2976
+ return new FullTextIndexItem(Expression.property(property));
2977
+ }
2978
+ }
2979
+
2980
+ class ValueIndex extends AbstractIndex {
2981
+ constructor(...indexItems) {
2982
+ super();
2983
+ this.indexItems = indexItems;
2984
+ }
2985
+ type() {
2986
+ return exports.IndexType.Value;
2987
+ }
2988
+ language() {
2989
+ return null;
2990
+ }
2991
+ ignoreAccents() {
2992
+ return false;
2993
+ }
2994
+ items() {
2995
+ const items = [];
2996
+ for (let item of this.indexItems) {
2997
+ items.push(item.expr.asJSON());
2998
+ }
2999
+ return items;
3000
+ }
3001
+ toJson() {
3002
+ return {
3003
+ type: 'value',
3004
+ items: this.items(),
3005
+ };
3006
+ }
3007
+ }
3008
+ class ValueIndexItem {
3009
+ constructor(expr) {
3010
+ this.expr = expr;
3011
+ }
3012
+ /**
3013
+ * Creates a value index item with the given property.
3014
+ *
3015
+ * @param property the property name
3016
+ * @return The value index item
3017
+ */
3018
+ static property(property) {
3019
+ return new ValueIndexItem(Expression.property(property));
3020
+ }
3021
+ /**
3022
+ * Creates a value index item with the given property.
3023
+ *
3024
+ * @param expression The expression to index. Typically a property expression.
3025
+ * @return The value index item
3026
+ */
3027
+ static expression(expression) {
3028
+ return new ValueIndexItem(expression);
3029
+ }
3030
+ }
3031
+
3032
+ class IndexBuilder {
3033
+ /**
3034
+ * Create a value index with the given index items. The index items are a list of
3035
+ * the properties or expressions to be indexed.
3036
+ *
3037
+ * @param items The index items
3038
+ * @return The value index
3039
+ */
3040
+ static valueIndex(...items) {
3041
+ return new ValueIndex(...items);
3042
+ }
3043
+ /**
3044
+ * Create a full-text search index with the given index item and options. Typically the index item is
3045
+ * the property that is used to perform the match operation against with.
3046
+ *
3047
+ * @param items The index items.
3048
+ * @return The full-text search index.
3049
+ */
3050
+ static fullTextIndex(...items) {
3051
+ return new FullTextIndex(...items);
3052
+ }
3053
+ }
3054
+
3055
+ class MetaExpression extends Expression {
3056
+ constructor(_keyPath, _columnName, _from) {
3057
+ super();
3058
+ this._keyPath = _keyPath;
3059
+ this._columnName = _columnName;
3060
+ this._from = _from;
3061
+ }
3062
+ from(alias) {
3063
+ return new MetaExpression(this._keyPath, null, alias);
3064
+ }
3065
+ asJSON() {
3066
+ const json = [];
3067
+ if (this._from) {
3068
+ json.push('.' + this._from + '.' + this._keyPath);
3069
+ }
3070
+ else {
3071
+ json.push('.' + this._keyPath);
3072
+ }
3073
+ return json;
3074
+ }
3075
+ getColumnName() {
3076
+ if (!this._columnName) {
3077
+ const paths = this._keyPath.split('.');
3078
+ this._columnName = paths[paths.length - 1];
3079
+ }
3080
+ return this._columnName;
3081
+ }
3082
+ }
3083
+
3084
+ class Meta {
3085
+ }
3086
+ Meta.id = new MetaExpression('_id', 'id', null);
3087
+ Meta.sequence = new MetaExpression('_sequence', 'sequence', null);
3088
+ Meta.deleted = new MetaExpression('_deleted', 'deleted', null);
3089
+ Meta.expiration = new MetaExpression('_expiration', 'expiration', null);
3090
+
3091
+ class MutableDocument extends Document {
3092
+ // Actual constructor implementation
3093
+ constructor(id = null, sequenceNoOrData = null, revisionIDOrData = null, data = {}, collection = null) {
3094
+ if (arguments.length === 0) {
3095
+ super(null, null, null, null, {});
3096
+ }
3097
+ else if (arguments.length === 1) {
3098
+ // Just ID
3099
+ super(id, null, null, null, {});
3100
+ }
3101
+ else if (arguments.length === 2 && typeof sequenceNoOrData === 'object') {
3102
+ // ID and data
3103
+ super(id, null, null, null, sequenceNoOrData || {});
3104
+ }
3105
+ else if (arguments.length === 3 && typeof revisionIDOrData === 'object') {
3106
+ // ID, sequenceNo, and data
3107
+ super(id, sequenceNoOrData, null, null, revisionIDOrData || {});
3108
+ }
3109
+ else {
3110
+ // Full constructor
3111
+ super(id, sequenceNoOrData, revisionIDOrData, collection, data);
3112
+ }
3113
+ this._blobs = {};
3114
+ }
3115
+ /**
3116
+ * Creates a new MutableDocument instance from an existing Document
3117
+ * @param {Document} document - The source Document to create a mutable copy from
3118
+ * @returns {MutableDocument} A new MutableDocument containing the same data as the source document
3119
+ * @example
3120
+ * const doc = await collection.document('doc1');
3121
+ * const mutableDoc = MutableDocument.fromDocument(doc);
3122
+ *
3123
+ * // Now you can modify the document
3124
+ * mutableDoc.setString('name', 'John');
3125
+ * await collection.save(mutableDoc);
3126
+ */
3127
+ static fromDocument(document) {
3128
+ return new MutableDocument(document.getId(), document.getSequence(), document.getRevisionID(), document.getData(), document.getCollection());
3129
+ }
3130
+ static fromJSON(documentId, jsonString) {
3131
+ try {
3132
+ const data = JSON.parse(jsonString);
3133
+ return new MutableDocument(documentId, data);
3134
+ }
3135
+ catch (e) {
3136
+ throw new Error(`Failed to parse JSON string: ${e.message}`);
3137
+ }
3138
+ }
3139
+ /**
3140
+ * Removes a property from the document
3141
+ * @param {string} key - The property key to remove. Can be a dot-notation path for nested properties
3142
+ * @returns {MutableDocument} The current document instance for method chaining
3143
+ * @example
3144
+ * // Remove a top-level property
3145
+ * doc.remove('name');
3146
+ *
3147
+ * // Remove a nested property
3148
+ * doc.remove('address.city');
3149
+ *
3150
+ * // Chain with other methods
3151
+ * doc.remove('name')
3152
+ * .setString('title', 'Mr.')
3153
+ * .setNumber('age', 30);
3154
+ */
3155
+ remove(key) {
3156
+ const parts = key.split('.');
3157
+ let current = this.doc;
3158
+ // Navigate to the parent object for nested properties
3159
+ for (let i = 0; i < parts.length - 1; i++) {
3160
+ if (current[parts[i]] === undefined) {
3161
+ return this;
3162
+ }
3163
+ current = current[parts[i]];
3164
+ }
3165
+ // Delete the final property
3166
+ delete current[parts[parts.length - 1]];
3167
+ return this;
3168
+ }
3169
+ /**
3170
+ * Internal method to set a value in the document
3171
+ * @param {string} key - The property key where the value will be stored
3172
+ * @param {T | null} value - The value to store, can be null
3173
+ * @template T - The type of the value being stored
3174
+ * @private
3175
+ * @example
3176
+ * // This is an internal method, typically used by public setters:
3177
+ * // Instead of using _set directly, use public methods like:
3178
+ * doc.setString('name', 'John');
3179
+ * doc.setNumber('age', 30);
3180
+ */
3181
+ _set(key, value) {
3182
+ if (key in this._blobs) {
3183
+ delete this._blobs[key];
3184
+ }
3185
+ this.doc[key] = value;
3186
+ }
3187
+ /**
3188
+ * Sets the document's ID
3189
+ * @param {string} id - The new ID for the document
3190
+ * @example
3191
+ * const doc = new MutableDocument();
3192
+ * doc.setId('user123');
3193
+ *
3194
+ * // Note: Changing an existing document's ID is generally not recommended
3195
+ * // as it may affect document tracking and replication
3196
+ */
3197
+ setId(id) {
3198
+ this.id = id;
3199
+ }
3200
+ /**
3201
+ * Sets an array value for a given key in the document
3202
+ * @param {string} key - The property key where the array will be stored
3203
+ * @param {T[]} value - The array to store
3204
+ * @template T - The type of elements in the array
3205
+ * @returns {MutableDocument} The current document instance for method chaining
3206
+ * @example
3207
+ * // Set an array of strings
3208
+ * doc.setArray('tags', ['important', 'urgent']);
3209
+ *
3210
+ * // Set an array of numbers
3211
+ * doc.setArray('scores', [85, 92, 78]);
3212
+ *
3213
+ * // Chain with other methods
3214
+ * doc.setArray('items', ['a', 'b'])
3215
+ * .setString('status', 'active');
3216
+ */
3217
+ setArray(key, value) {
3218
+ this._set(key, value);
3219
+ return this;
3220
+ }
3221
+ /**
3222
+ * Sets a blob value for a given key in the document
3223
+ * @param {string} key - The property key where the blob will be stored
3224
+ * @param {Blob | null} value - The blob to store, or null to remove existing blob
3225
+ * @returns {MutableDocument} The current document instance for method chaining
3226
+ * @example
3227
+ * // Create and set a new blob
3228
+ * const bytes = new Uint8Array([72, 101, 108, 108, 111]);
3229
+ * const blob = new Blob('text/plain', bytes);
3230
+ * doc.setBlob('attachment', blob);
3231
+ *
3232
+ * // Remove a blob
3233
+ * doc.setBlob('attachment', null);
3234
+ *
3235
+ * // Chain with other methods
3236
+ * doc.setBlob('attachment', blob)
3237
+ * .setString('filename', 'hello.txt');
3238
+ */
3239
+ setBlob(key, value) {
3240
+ //remove it from the internal doc because it's a blob
3241
+ if (key in this.doc) {
3242
+ delete this.doc[key];
3243
+ }
3244
+ if (value === null) {
3245
+ this._blobs[key] = null;
3246
+ return this;
3247
+ }
3248
+ this._blobs[key] = {
3249
+ _type: 'blob',
3250
+ data: value.toDictionary(),
3251
+ };
3252
+ return this;
3253
+ }
3254
+ /**
3255
+ * Sets a boolean value for a given key in the document
3256
+ * @param {string} key - The property key where the boolean will be stored
3257
+ * @param {boolean} value - The boolean value to store
3258
+ * @returns {MutableDocument} The current document instance for method chaining
3259
+ * @example
3260
+ * // Set a boolean value
3261
+ * doc.setBoolean('isActive', true);
3262
+ *
3263
+ * // Set multiple boolean values using method chaining
3264
+ * doc.setBoolean('isEnabled', true)
3265
+ * .setBoolean('isVisible', false)
3266
+ * .setBoolean('isLocked', true);
3267
+ */
3268
+ setBoolean(key, value) {
3269
+ this._set(key, value);
3270
+ return this;
3271
+ }
3272
+ /**
3273
+ * Sets the collection that this document belongs to
3274
+ * @param {Collection} collection - The collection instance to associate with this document
3275
+ * @example
3276
+ * const collection = await database.collection('users');
3277
+ * const doc = new MutableDocument('user123');
3278
+ * doc.setCollection(collection);
3279
+ *
3280
+ * // Note: This method is typically used internally.
3281
+ * // Documents are usually associated with collections when created through the collection itself
3282
+ */
3283
+ setCollection(collection) {
3284
+ this.collection = collection;
3285
+ }
3286
+ /**
3287
+ * Sets the entire document's data content
3288
+ * @param {Dictionary} data - An object containing all the data to be stored in the document
3289
+ * @returns {MutableDocument} The current document instance for method chaining
3290
+ * @example
3291
+ * // Set complete document data
3292
+ * doc.setData({
3293
+ * name: 'John Doe',
3294
+ * age: 30,
3295
+ * email: 'john@example.com'
3296
+ * });
3297
+ *
3298
+ * // Chain with other methods
3299
+ * doc.setData({ name: 'John' })
3300
+ * .setString('title', 'Mr.');
3301
+ *
3302
+ * // Replace existing data
3303
+ * const newData = { status: 'active', type: 'user' };
3304
+ * doc.setData(newData); // Previous data is completely replaced
3305
+ */
3306
+ setData(data) {
3307
+ this.doc = data;
3308
+ return this;
3309
+ }
3310
+ /**
3311
+ * Sets a date value for a given key in the document
3312
+ * @param {string} key - The property key where the date will be stored
3313
+ * @param {Date | null} value - The date to store, or null to remove the date
3314
+ * @returns {MutableDocument} The current document instance for method chaining
3315
+ * @example
3316
+ * // Set current date
3317
+ * doc.setDate('createdAt', new Date());
3318
+ *
3319
+ * // Set specific date
3320
+ * doc.setDate('dueDate', new Date('2024-12-31'));
3321
+ *
3322
+ * // Remove date
3323
+ * doc.setDate('expiredAt', null);
3324
+ *
3325
+ * // Chain with other methods
3326
+ * doc.setDate('createdAt', new Date())
3327
+ * .setString('status', 'active');
3328
+ *
3329
+ * // Note: Dates are stored as ISO 8601 strings in the document
3330
+ */
3331
+ setDate(key, value) {
3332
+ if (value !== null) {
3333
+ this._set(key, value.toISOString());
3334
+ }
3335
+ else {
3336
+ this._set(key, value);
3337
+ }
3338
+ return this;
3339
+ }
3340
+ /**
3341
+ * Sets a dictionary (object) value for a given key in the document
3342
+ * @param {string} key - The property key where the dictionary will be stored
3343
+ * @param {Dictionary | null} value - The dictionary to store, or null to remove the dictionary
3344
+ * @returns {MutableDocument} The current document instance for method chaining
3345
+ * @example
3346
+ * // Set a dictionary
3347
+ * doc.setDictionary('address', {
3348
+ * street: '123 Main St',
3349
+ * city: 'Boston',
3350
+ * state: 'MA',
3351
+ * zip: '02108'
3352
+ * });
3353
+ *
3354
+ * // Remove a dictionary
3355
+ * doc.setDictionary('oldAddress', null);
3356
+ *
3357
+ * // Chain with other methods
3358
+ * doc.setDictionary('contact', { email: 'john@example.com' })
3359
+ * .setString('status', 'active');
3360
+ */
3361
+ setDictionary(key, value) {
3362
+ this._set(key, value);
3363
+ return this;
3364
+ }
3365
+ /**
3366
+ * Sets a double-precision floating point number for a given key in the document
3367
+ * @param {string} key - The property key where the number will be stored
3368
+ * @param {number} value - The double value to store
3369
+ * @returns {MutableDocument} The current document instance for method chaining
3370
+ * @example
3371
+ * // Set a double value
3372
+ * doc.setDouble('price', 99.99);
3373
+ *
3374
+ * // Set a scientific notation
3375
+ * doc.setDouble('distance', 1.23e-4);
3376
+ *
3377
+ * // Chain with other methods
3378
+ * doc.setDouble('weight', 75.5)
3379
+ * .setDouble('height', 182.3)
3380
+ * .setString('unit', 'metric');
3381
+ */
3382
+ setDouble(key, value) {
3383
+ this._set(key, value);
3384
+ return this;
3385
+ }
3386
+ /**
3387
+ * Sets a single-precision floating point number for a given key in the document
3388
+ * @param {string} key - The property key where the number will be stored
3389
+ * @param {number} value - The float value to store
3390
+ * @returns {MutableDocument} The current document instance for method chaining
3391
+ * @example
3392
+ * // Set a float value
3393
+ * doc.setFloat('temperature', 98.6);
3394
+ *
3395
+ * // Set a scientific notation
3396
+ * doc.setFloat('measurement', 3.14e2);
3397
+ *
3398
+ * // Chain with other methods
3399
+ * doc.setFloat('latitude', 42.3601)
3400
+ * .setFloat('longitude', -71.0589)
3401
+ * .setString('location', 'Boston');
3402
+ *
3403
+ * // Note: Use setDouble() instead if you need higher precision
3404
+ */
3405
+ setFloat(key, value) {
3406
+ this._set(key, value);
3407
+ return this;
3408
+ }
3409
+ /**
3410
+ * Sets a 32-bit integer value for a given key in the document
3411
+ * @param {string} key - The property key where the integer will be stored
3412
+ * @param {number} value - The integer value to store
3413
+ * @returns {MutableDocument} The current document instance for method chaining
3414
+ * @example
3415
+ * // Set an integer value
3416
+ * doc.setInt('age', 25);
3417
+ *
3418
+ * // Set a negative integer
3419
+ * doc.setInt('temperature', -5);
3420
+ *
3421
+ * // Chain with other methods
3422
+ * doc.setInt('quantity', 100)
3423
+ * .setInt('minStock', 10)
3424
+ * .setString('status', 'in-stock');
3425
+ *
3426
+ * // Note: For larger numbers, use setLong() instead
3427
+ */
3428
+ setInt(key, value) {
3429
+ this._set(key, value);
3430
+ return this;
3431
+ }
3432
+ /**
3433
+ * Sets a 64-bit integer value for a given key in the document
3434
+ * @param {string} key - The property key where the long integer will be stored
3435
+ * @param {number} value - The long integer value to store
3436
+ * @returns {MutableDocument} The current document instance for method chaining
3437
+ * @example
3438
+ * // Set a large integer value
3439
+ * doc.setLong('fileSize', 2147483648);
3440
+ *
3441
+ * // Set a timestamp
3442
+ * doc.setLong('timestamp', Date.now());
3443
+ *
3444
+ * // Chain with other methods
3445
+ * doc.setLong('userId', 9876543210)
3446
+ * .setString('status', 'active');
3447
+ *
3448
+ * // Note: Use this instead of setInt() for numbers larger than 2^31 - 1
3449
+ */
3450
+ setLong(key, value) {
3451
+ this._set(key, value);
3452
+ return this;
3453
+ }
3454
+ /**
3455
+ * Sets a numeric value for a given key in the document
3456
+ * @param {string} key - The property key where the number will be stored
3457
+ * @param {number} value - The numeric value to store
3458
+ * @returns {MutableDocument} The current document instance for method chaining
3459
+ * @example
3460
+ * // Set various types of numbers
3461
+ * doc.setNumber('integer', 42);
3462
+ * doc.setNumber('decimal', 3.14);
3463
+ * doc.setNumber('scientific', 1.23e-4);
3464
+ * doc.setNumber('negative', -10);
3465
+ *
3466
+ * // Chain with other methods
3467
+ * doc.setNumber('price', 99.99)
3468
+ * .setString('currency', 'USD');
3469
+ *
3470
+ * // Note: For specific number types, consider using:
3471
+ * // setInt() for 32-bit integers
3472
+ * // setLong() for 64-bit integers
3473
+ * // setFloat() for single-precision decimals
3474
+ * // setDouble() for double-precision decimals
3475
+ */
3476
+ setNumber(key, value) {
3477
+ this._set(key, value);
3478
+ return this;
3479
+ }
3480
+ /**
3481
+ * Sets the revision ID for the document
3482
+ * @param {string} revisionID - The new revision ID to set
3483
+ * @example
3484
+ * const doc = new MutableDocument('user123');
3485
+ * doc.setRevisionID('1-abc123');
3486
+ *
3487
+ * // Note: THIS METHOD IS USED INTERNALLY ONLY - DO NOT SET THIS MANUALLY.
3488
+ * // Revision IDs ARE MANAGED AUTOMATICALLY BY THE DATABASE
3489
+ */
3490
+ setRevisionID(revisionID) {
3491
+ this.revisionID = revisionID;
3492
+ }
3493
+ /**
3494
+ * Sets the sequence number for the document
3495
+ * @param {string} revisionID - The new sequence number to set
3496
+ * @example
3497
+ * const doc = new MutableDocument('user123');
3498
+ * doc.setSequence(123);
3499
+ *
3500
+ * // Note: THIS METHOD IS USED INTERNALLY ONLY - DO NOT SET THIS MANUALLY.
3501
+ * // SEQUENCE NUMBERS ARE MANAGED AUTOMATICALLY BY THE DATABASE
3502
+ */
3503
+ setSequence(sequence) {
3504
+ this.sequenceNo = sequence;
3505
+ }
3506
+ /**
3507
+ * Sets a string value for a given key in the document
3508
+ * @param {string} key - The property key where the string will be stored
3509
+ * @param {string | null} value - The string value to store, or null to remove the value
3510
+ * @returns {MutableDocument} The current document instance for method chaining
3511
+ * @example
3512
+ * // Set a string value
3513
+ * doc.setString('name', 'John Doe');
3514
+ *
3515
+ * // Remove a string value
3516
+ * doc.setString('middleName', null);
3517
+ *
3518
+ * // Chain with other methods
3519
+ * doc.setString('firstName', 'John')
3520
+ * .setString('lastName', 'Doe')
3521
+ * .setString('email', 'john@example.com');
3522
+ */
3523
+ setString(key, value) {
3524
+ this._set(key, value);
3525
+ return this;
3526
+ }
3527
+ /**
3528
+ * Sets a value of any type for a given key in the document
3529
+ * @param {string} key - The property key where the value will be stored
3530
+ * @param {T} value - The value to store
3531
+ * @template T - The type of the value being stored
3532
+ * @returns {MutableDocument} The current document instance for method chaining
3533
+ * @example
3534
+ * // Set values of different types
3535
+ * doc.setValue('name', 'John')
3536
+ * .setValue('age', 30)
3537
+ * .setValue('isActive', true)
3538
+ * .setValue('scores', [85, 92, 78])
3539
+ * .setValue('address', {
3540
+ * street: '123 Main St',
3541
+ * city: 'Boston'
3542
+ * });
3543
+ *
3544
+ * // Note: Consider using type-specific setters (setString, setNumber, etc.)
3545
+ * // when the type is known at development time
3546
+ */
3547
+ setValue(key, value) {
3548
+ this._set(key, value);
3549
+ return this;
3550
+ }
3551
+ /**
3552
+ * Converts the document's blob attachments to a JSON string representation
3553
+ * @returns {string} A JSON string containing all blob attachments in the document
3554
+ * @example
3555
+ * // First, add some blobs to the document
3556
+ * const imageBlob = new Blob('image/jpeg', imageBytes);
3557
+ * const pdfBlob = new Blob('application/pdf', pdfBytes);
3558
+ *
3559
+ * doc.setBlob('profile_image', imageBlob)
3560
+ * .setBlob('resume', pdfBlob);
3561
+ *
3562
+ * // Get JSON string of all blobs
3563
+ * const blobsJson = doc.blobsToJsonString();
3564
+ * // Returns: '{"profile_image":{"_type":"blob","data":{...}},"resume":{...}}'
3565
+ */
3566
+ blobsToJsonString() {
3567
+ return JSON.stringify(this._blobs);
3568
+ }
3569
+ }
3570
+
3571
+ class Ordering {
3572
+ static property(property) {
3573
+ return this.expression(Expression.property(property));
3574
+ }
3575
+ static expression(expression) {
3576
+ return new SortOrder(expression);
3577
+ }
3578
+ }
3579
+ class SortOrder extends Ordering {
3580
+ constructor(expression) {
3581
+ super();
3582
+ this.expression = expression;
3583
+ this.isAscending = true;
3584
+ }
3585
+ ascending() {
3586
+ this.isAscending = true;
3587
+ return this;
3588
+ }
3589
+ descending() {
3590
+ this.isAscending = false;
3591
+ return this;
3592
+ }
3593
+ asJSON() {
3594
+ if (this.isAscending) {
3595
+ return this.expression.asJSON();
3596
+ }
3597
+ return ['DESC', this.expression.asJSON()];
3598
+ }
3599
+ }
3600
+
3601
+ class ReplicatorStatus {
3602
+ // eslint-disable-next-line
3603
+ constructor(activityLevel, progress, error) {
3604
+ this.activityLevel = activityLevel;
3605
+ this.progress = progress;
3606
+ this.error = error;
3607
+ }
3608
+ getActivityLevel() {
3609
+ return this.activityLevel;
3610
+ }
3611
+ getProgress() {
3612
+ return this.progress;
3613
+ }
3614
+ getError() {
3615
+ return this.error;
3616
+ }
3617
+ toString() {
3618
+ if (this.error !== undefined) {
3619
+ return `Status{activityLevel=${this.activityLevel}, progress=${this.progress}}, error=${this.error}`;
3620
+ }
3621
+ else {
3622
+ return `Status{activityLevel=${this.activityLevel}, progress=${this.progress}}`;
3623
+ }
3624
+ }
3625
+ copy() {
3626
+ return new ReplicatorStatus(this.activityLevel, this.progress, this.error);
3627
+ }
3628
+ }
3629
+
3630
+ class ReplicatorProgress {
3631
+ // eslint-disable-next-line
3632
+ constructor(completed, total) {
3633
+ this.completed = completed;
3634
+ this.total = total;
3635
+ }
3636
+ getCompleted() {
3637
+ return this.completed;
3638
+ }
3639
+ getTotal() {
3640
+ return this.total;
3641
+ }
3642
+ toString() {
3643
+ return `Progress{completed=${this.completed}, total=${this.total}}`;
3644
+ }
3645
+ copy() {
3646
+ return new ReplicatorProgress(this.completed, this.total);
3647
+ }
3648
+ }
3649
+
3650
+ class Replicator {
3651
+ /**
3652
+ * Initializes a replicator with the given configuration
3653
+ *
3654
+ * @param config
3655
+ */
3656
+ constructor(replicatorId, config) {
3657
+ this._replicatorId = undefined;
3658
+ this._engine = EngineLocator.getEngine(EngineLocator.key);
3659
+ this._didStartStatusChangeListener = false;
3660
+ this._replicatorId = replicatorId;
3661
+ this._config = config;
3662
+ this._documentChangeListener = new Map();
3663
+ }
3664
+ /**
3665
+ * Adds a replicator change listener for listening to status updates
3666
+ *
3667
+ * @function
3668
+ *
3669
+ */
3670
+ async addChangeListener(listener) {
3671
+ this._statusChangeListener = listener;
3672
+ const token = this._engine.getUUID();
3673
+ if (!this._didStartStatusChangeListener) {
3674
+ await this._engine.replicator_AddChangeListener({
3675
+ replicatorId: this._replicatorId,
3676
+ changeListenerToken: token,
3677
+ }, (data, err) => {
3678
+ if (err) {
3679
+ throw err;
3680
+ }
3681
+ this.notifyStatusChange(data);
3682
+ });
3683
+ this._didStartStatusChangeListener = true;
3684
+ return token;
3685
+ }
3686
+ else {
3687
+ throw new Error('Listener already started');
3688
+ }
3689
+ }
3690
+ async addDocumentChangeListener(listener) {
3691
+ const token = this._engine.getUUID();
3692
+ this._documentChangeListener.set(token, listener);
3693
+ await this._engine.replicator_AddDocumentChangeListener({
3694
+ replicatorId: this._replicatorId,
3695
+ changeListenerToken: token,
3696
+ }, (data, err) => {
3697
+ if (err) {
3698
+ throw err;
3699
+ }
3700
+ if (isDocumentReplicationRepresentation(data)) {
3701
+ this.notifyDocumentChange(data, token);
3702
+ }
3703
+ else {
3704
+ throw new Error('Invalid document replication change notification');
3705
+ }
3706
+ });
3707
+ return token;
3708
+ }
3709
+ /**
3710
+ * Creates a new Replicator instance for database synchronization
3711
+ * @param {ReplicatorConfiguration} config - The configuration for the replicator
3712
+ * @returns {Promise<Replicator>} A Promise that resolves to a new Replicator instance
3713
+ * @throws {Error} If the configuration is invalid or required parameters are missing
3714
+ */
3715
+ static async create(config) {
3716
+ if (config.getCollections().length === 0) {
3717
+ throw new Error('No collections specified in the configuration');
3718
+ }
3719
+ const engine = EngineLocator.getEngine(EngineLocator.key);
3720
+ const configJson = config.toJson();
3721
+ const ret = await engine.replicator_Create({ config: configJson });
3722
+ const replicator = new Replicator(ret.replicatorId, config);
3723
+ return replicator;
3724
+ }
3725
+ /**
3726
+ * Removes the replicator from the native engine and stops the replicator from running.
3727
+ * This will remove all listeners from the replicator. As part of this, if you were to call
3728
+ * start after this method, a new replicator would be created Natively and a new replicator
3729
+ * id would be created.
3730
+ *
3731
+ * @function
3732
+ */
3733
+ async cleanup() {
3734
+ await this._engine.replicator_Cleanup({ replicatorId: this._replicatorId });
3735
+ this._replicatorId = null;
3736
+ }
3737
+ /**
3738
+ * returns the replicator id used to manage the replicator between the engine and the
3739
+ * replicator native implementation. This value should get set when the replicator is
3740
+ * created in the native engine via the start method.
3741
+ *
3742
+ * @function
3743
+ */
3744
+ getId() {
3745
+ return this._replicatorId;
3746
+ }
3747
+ /**
3748
+ * returns a copy of the replicators current configuration.
3749
+ * @function
3750
+ */
3751
+ getConfiguration() {
3752
+ return this._config;
3753
+ }
3754
+ /**
3755
+ * returns the replicators current status: its activity level and progress.
3756
+ *
3757
+ * @function
3758
+ */
3759
+ getStatus() {
3760
+ return this._engine.replicator_GetStatus({
3761
+ replicatorId: this._replicatorId,
3762
+ });
3763
+ }
3764
+ /**
3765
+ * Get pending document ids for the given collection. If the given collection is not part of the replication, an error will be thrown.
3766
+ *
3767
+ * @function
3768
+ */
3769
+ async getPendingDocumentIds(collection) {
3770
+ const collections = this._config.getCollections();
3771
+ if (!collections.includes(collection)) {
3772
+ throw new Error('Collection not part of the replication');
3773
+ }
3774
+ return await this._engine.replicator_GetPendingDocumentIds({
3775
+ replicatorId: this._replicatorId,
3776
+ collectionName: collection.name,
3777
+ scopeName: collection.scope.name,
3778
+ name: collection.database.getName(),
3779
+ });
3780
+ }
3781
+ /**
3782
+ * Check whether the document in the given collection is pending to push or not. If the given collection is not part of the replicator, an Exception will be thrown.
3783
+ *
3784
+ * @function
3785
+ */
3786
+ async isDocumentPending(documentId, collection) {
3787
+ const collections = this._config.getCollections();
3788
+ if (!collections.includes(collection)) {
3789
+ throw new Error('Collection not part of the replication');
3790
+ }
3791
+ return await this._engine.replicator_IsDocumentPending({
3792
+ replicatorId: this._replicatorId,
3793
+ documentId: documentId,
3794
+ collectionName: collection.name,
3795
+ scopeName: collection.scope.name,
3796
+ name: collection.database.getName(),
3797
+ });
3798
+ }
3799
+ notifyDocumentChange(data, token) {
3800
+ const documents = data.documents.map((doc) => {
3801
+ return {
3802
+ scopeName: doc.scopeName,
3803
+ collectionName: doc.collectionName,
3804
+ id: doc.id,
3805
+ flags: doc.flags,
3806
+ error: doc.error,
3807
+ };
3808
+ });
3809
+ const documentReplication = { isPush: data.isPush, documents: documents };
3810
+ this._documentChangeListener.get(token)(documentReplication);
3811
+ }
3812
+ notifyStatusChange(data) {
3813
+ let status;
3814
+ const activityLevel = Number(data.activityLevel);
3815
+ const replicatorProgress = new ReplicatorProgress(data.progress.completed, data.progress.total);
3816
+ if (data.error && typeof data.error.message === 'string') {
3817
+ status = new ReplicatorStatus(activityLevel, replicatorProgress, data.error.message);
3818
+ }
3819
+ else {
3820
+ status = new ReplicatorStatus(activityLevel, replicatorProgress, undefined);
3821
+ }
3822
+ const statusChange = { status: status };
3823
+ this._statusChangeListener(statusChange);
3824
+ }
3825
+ /**
3826
+ * Removes a change listener with the given listener token.
3827
+ *
3828
+ * @function
3829
+ */
3830
+ async removeChangeListener(token) {
3831
+ await this._engine.replicator_RemoveChangeListener({
3832
+ replicatorId: this._replicatorId,
3833
+ changeListenerToken: token,
3834
+ });
3835
+ }
3836
+ /**
3837
+ * Starts the replicator with an option to reset the local checkpoint of the replicator. When the
3838
+ * local checkpoint is reset, the replicator will sync all changes since the beginning of time from
3839
+ * the remote database.
3840
+ *
3841
+ * This method returns immediately; the replicator runs asynchronously and will report its progress
3842
+ * through the replicator change notification.
3843
+ *
3844
+ * @function
3845
+ *
3846
+ * @param {boolean} reset Resets the local checkpoint before starting the replicator.
3847
+ */
3848
+ async start(reset) {
3849
+ if (reset) {
3850
+ await this._engine.replicator_ResetCheckpoint({
3851
+ replicatorId: this._replicatorId,
3852
+ });
3853
+ return;
3854
+ }
3855
+ await this._engine.replicator_Start({ replicatorId: this._replicatorId });
3856
+ }
3857
+ /**
3858
+ * Stops a running replicator. This method returns immediately; when the replicator actually
3859
+ * stops, the replicator will change its status's activity level to
3860
+ * `ReplicatorActivityLevel.STOPPED` and the replicator change notification will be notified
3861
+ * accordingly.
3862
+ *
3863
+ * @function
3864
+ */
3865
+ stop() {
3866
+ return this._engine.replicator_Stop({ replicatorId: this._replicatorId });
3867
+ }
3868
+ }
3869
+
3870
+ exports.ReplicatorActivityLevel = void 0;
3871
+ (function (ReplicatorActivityLevel) {
3872
+ // eslint-disable-next-line
3873
+ ReplicatorActivityLevel[ReplicatorActivityLevel["STOPPED"] = 0] = "STOPPED";
3874
+ // eslint-disable-next-line
3875
+ ReplicatorActivityLevel[ReplicatorActivityLevel["OFFLINE"] = 1] = "OFFLINE";
3876
+ // eslint-disable-next-line
3877
+ ReplicatorActivityLevel[ReplicatorActivityLevel["CONNECTING"] = 2] = "CONNECTING";
3878
+ // eslint-disable-next-line
3879
+ ReplicatorActivityLevel[ReplicatorActivityLevel["IDLE"] = 3] = "IDLE";
3880
+ // eslint-disable-next-line
3881
+ ReplicatorActivityLevel[ReplicatorActivityLevel["BUSY"] = 4] = "BUSY";
3882
+ })(exports.ReplicatorActivityLevel || (exports.ReplicatorActivityLevel = {}));
3883
+
3884
+ function isReplicatorChange(obj) {
3885
+ try {
3886
+ const object = obj;
3887
+ return (object.activityLevel != null &&
3888
+ object.progress != null &&
3889
+ object.progress.completed != null &&
3890
+ object.progress.total != null);
3891
+ }
3892
+ catch (e) {
3893
+ console.warn('Invalid ReplicatorChange', e);
3894
+ return false;
3895
+ }
3896
+ }
3897
+
3898
+ class SessionAuthenticator extends Authenticator {
3899
+ // eslint-disable-next-line
3900
+ constructor(sessionID, cookieName = SessionAuthenticator.DEFAULT_SYNC_GATEWAY_SESSION_ID_NAME) {
3901
+ super();
3902
+ this.sessionID = sessionID;
3903
+ this.cookieName = cookieName;
3904
+ }
3905
+ /**
3906
+ * Configures session-based authentication options for a replicator using cookies
3907
+ * @param {Dictionary} options - The options to be modified
3908
+ */
3909
+ authenticate(options) {
3910
+ const current = options[ReplicatorConfiguration.CBLReplicatorOptionCookies] || '';
3911
+ let cookieStr = current;
3912
+ if (current.length) {
3913
+ cookieStr += '; ';
3914
+ }
3915
+ cookieStr += `${this.cookieName}=${this.sessionID}`;
3916
+ options[ReplicatorConfiguration.CBLReplicatorOptionCookies] = cookieStr;
3917
+ }
3918
+ /**
3919
+ * Returns the session ID used for authentication
3920
+ * @returns {string} The current session ID
3921
+ */
3922
+ getSessionID() {
3923
+ return this.sessionID;
3924
+ }
3925
+ /**
3926
+ * Returns the name of the cookie used for session authentication
3927
+ * @returns {string} The cookie name (defaults to 'SyncGatewaySession' if not specified)
3928
+ */
3929
+ getCookieName() {
3930
+ return this.cookieName;
3931
+ }
3932
+ getType() {
3933
+ return 'session';
3934
+ }
3935
+ /**
3936
+ * Converts the session authenticator configuration to a JSON-compatible object
3937
+ * @returns {{ cookieName: string, sessionID: string }} An object containing the cookie name and session ID
3938
+ */
3939
+ toJson() {
3940
+ return {
3941
+ cookieName: this.cookieName,
3942
+ sessionID: this.sessionID,
3943
+ };
3944
+ }
3945
+ }
3946
+ SessionAuthenticator.DEFAULT_SYNC_GATEWAY_SESSION_ID_NAME = 'SyncGatewaySession';
3947
+
3948
+ class URLEndpoint {
3949
+ // eslint-disable-next-line
3950
+ constructor(url) {
3951
+ this.url = url;
3952
+ }
3953
+ toJson() {
3954
+ return {
3955
+ url: this.url,
3956
+ };
3957
+ }
3958
+ }
3959
+
3960
+ class VariableExpression extends Expression {
3961
+ // eslint-disable-next-line
3962
+ constructor(name) {
3963
+ super();
3964
+ this.name = name;
3965
+ }
3966
+ getName() {
3967
+ return this.name;
3968
+ }
3969
+ asJSON() {
3970
+ return ['?' + this.name];
3971
+ }
3972
+ }
3973
+
3974
+ const IonicCouchbaseLite = core.registerPlugin('CblIonicPlugin');
3975
+
3976
+ // Unique ID creation requires a high quality random # generator. In the browser we therefore
3977
+ // require the crypto API and do not support built-in fallback to lower quality random number
3978
+ // generators (like Math.random()).
3979
+ let getRandomValues;
3980
+ const rnds8 = new Uint8Array(16);
3981
+ function rng() {
3982
+ // lazy load so that environments that need to polyfill have a chance to do so
3983
+ if (!getRandomValues) {
3984
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
3985
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
3986
+
3987
+ if (!getRandomValues) {
3988
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
3989
+ }
3990
+ }
3991
+
3992
+ return getRandomValues(rnds8);
3993
+ }
3994
+
3995
+ /**
3996
+ * Convert array of 16 byte values to UUID string format of the form:
3997
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
3998
+ */
3999
+
4000
+ const byteToHex = [];
4001
+
4002
+ for (let i = 0; i < 256; ++i) {
4003
+ byteToHex.push((i + 0x100).toString(16).slice(1));
4004
+ }
4005
+
4006
+ function unsafeStringify(arr, offset = 0) {
4007
+ // Note: Be careful editing this code! It's been tuned for performance
4008
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
4009
+ return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
4010
+ }
4011
+
4012
+ const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
4013
+ var native = {
4014
+ randomUUID
4015
+ };
4016
+
4017
+ function v4(options, buf, offset) {
4018
+ if (native.randomUUID && !buf && !options) {
4019
+ return native.randomUUID();
4020
+ }
4021
+
4022
+ options = options || {};
4023
+ const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
4024
+
4025
+ rnds[6] = rnds[6] & 0x0f | 0x40;
4026
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
4027
+
4028
+ if (buf) {
4029
+ offset = offset || 0;
4030
+
4031
+ for (let i = 0; i < 16; ++i) {
4032
+ buf[offset + i] = rnds[i];
4033
+ }
4034
+
4035
+ return buf;
4036
+ }
4037
+
4038
+ return unsafeStringify(rnds);
4039
+ }
4040
+
4041
+ /* eslint-disable @typescript-eslint/no-explicit-any */
4042
+ class CapacitorEngine {
4043
+ constructor() {
4044
+ this._defaultCollectionName = '_default';
4045
+ this._defaultScopeName = '_default';
4046
+ EngineLocator.registerEngine(EngineLocator.key, this);
4047
+ }
4048
+ collection_AddChangeListener(args, cb) {
4049
+ return IonicCouchbaseLite.collection_AddChangeListener({
4050
+ name: args.name,
4051
+ scopeName: args.scopeName,
4052
+ collectionName: args.collectionName,
4053
+ changeListenerToken: args.changeListenerToken,
4054
+ }, cb);
4055
+ }
4056
+ collection_AddDocumentChangeListener(args, cb) {
4057
+ return IonicCouchbaseLite.collection_AddDocumentChangeListener({
4058
+ name: args.name,
4059
+ scopeName: args.scopeName,
4060
+ collectionName: args.collectionName,
4061
+ changeListenerToken: args.changeListenerToken,
4062
+ documentId: args.documentId,
4063
+ }, cb);
4064
+ }
4065
+ async collection_CreateCollection(args) {
4066
+ return IonicCouchbaseLite.collection_CreateCollection(args);
4067
+ }
4068
+ async collection_CreateIndex(args) {
4069
+ return IonicCouchbaseLite.collection_CreateIndex(args);
4070
+ }
4071
+ async collection_DeleteCollection(args) {
4072
+ return IonicCouchbaseLite.collection_DeleteCollection(args);
4073
+ }
4074
+ async collection_DeleteDocument(args) {
4075
+ return IonicCouchbaseLite.collection_DeleteDocument(args);
4076
+ }
4077
+ async collection_DeleteIndex(args) {
4078
+ return IonicCouchbaseLite.collection_DeleteIndex(args);
4079
+ }
4080
+ async collection_GetCollections(args) {
4081
+ return IonicCouchbaseLite.collection_GetCollections(args);
4082
+ }
4083
+ async collection_GetCollection(args) {
4084
+ return IonicCouchbaseLite.collection_GetCollection(args);
4085
+ }
4086
+ async collection_GetCount(args) {
4087
+ return IonicCouchbaseLite.collection_GetCount(args);
4088
+ }
4089
+ async collection_GetDefault(args) {
4090
+ return IonicCouchbaseLite.collection_GetDefault(args);
4091
+ }
4092
+ async collection_GetDocument(args) {
4093
+ return IonicCouchbaseLite.collection_GetDocument(args);
4094
+ }
4095
+ async collection_GetDocumentExpiration(args) {
4096
+ return IonicCouchbaseLite.collection_GetDocumentExpiration(args);
4097
+ }
4098
+ async collection_GetBlobContent(args) {
4099
+ const data = await IonicCouchbaseLite.collection_GetBlobContent(args);
4100
+ return { data: new Uint8Array(data.data).buffer };
4101
+ }
4102
+ async collection_GetIndexes(args) {
4103
+ return IonicCouchbaseLite.collection_GetIndexes(args);
4104
+ }
4105
+ async collection_PurgeDocument(args) {
4106
+ return IonicCouchbaseLite.collection_PurgeDocument(args);
4107
+ }
4108
+ async collection_RemoveChangeListener(args) {
4109
+ return IonicCouchbaseLite.collection_RemoveChangeListener(args);
4110
+ }
4111
+ async collection_RemoveDocumentChangeListener(args) {
4112
+ return IonicCouchbaseLite.collection_RemoveChangeListener(args);
4113
+ }
4114
+ async collection_Save(args) {
4115
+ return IonicCouchbaseLite.collection_Save(args);
4116
+ }
4117
+ async collection_SetDocumentExpiration(args) {
4118
+ return IonicCouchbaseLite.collection_SetDocumentExpiration(args);
4119
+ }
4120
+ async database_Close(args) {
4121
+ return IonicCouchbaseLite.database_Close(args);
4122
+ }
4123
+ async database_Copy(args) {
4124
+ return IonicCouchbaseLite.database_Copy(args);
4125
+ }
4126
+ async database_ChangeEncryptionKey(args) {
4127
+ return IonicCouchbaseLite.database_ChangeEncryptionKey(args);
4128
+ }
4129
+ /**
4130
+ * @deprecated This function will be removed in future versions. Use colllection_CreateIndex instead.
4131
+ */
4132
+ async database_CreateIndex(args) {
4133
+ const colArgs = {
4134
+ name: args.name,
4135
+ collectionName: this._defaultCollectionName,
4136
+ scopeName: this._defaultScopeName,
4137
+ indexName: args.indexName,
4138
+ index: args.index,
4139
+ };
4140
+ return IonicCouchbaseLite.collection_CreateIndex(colArgs);
4141
+ }
4142
+ async database_Delete(args) {
4143
+ return IonicCouchbaseLite.database_Delete(args);
4144
+ }
4145
+ async database_DeleteWithPath(args) {
4146
+ return IonicCouchbaseLite.database_DeleteWithPath(args);
4147
+ }
4148
+ /**
4149
+ * @deprecated This will be removed in future versions. Use collection_GetCount instead.
4150
+ */
4151
+ async database_DeleteDocument(args) {
4152
+ const colArgs = {
4153
+ name: args.name,
4154
+ collectionName: this._defaultCollectionName,
4155
+ scopeName: this._defaultScopeName,
4156
+ docId: args.docId,
4157
+ concurrencyControl: args.concurrencyControl,
4158
+ };
4159
+ return IonicCouchbaseLite.collection_DeleteDocument(colArgs);
4160
+ }
4161
+ /**
4162
+ * @deprecated This function will be removed in future versions. Use colllection_CreateIndex instead.
4163
+ */
4164
+ async database_DeleteIndex(args) {
4165
+ const colArgs = {
4166
+ name: args.name,
4167
+ collectionName: this._defaultCollectionName,
4168
+ scopeName: this._defaultScopeName,
4169
+ indexName: args.indexName,
4170
+ };
4171
+ return IonicCouchbaseLite.collection_DeleteIndex(colArgs);
4172
+ }
4173
+ async database_Exists(args) {
4174
+ return IonicCouchbaseLite.database_Exists(args);
4175
+ }
4176
+ /**
4177
+ * @deprecated This will be removed in future versions. Use collection_GetCount instead.
4178
+ */
4179
+ async database_GetCount(args) {
4180
+ const colArgs = {
4181
+ name: args.name,
4182
+ collectionName: this._defaultCollectionName,
4183
+ scopeName: this._defaultScopeName,
4184
+ };
4185
+ return IonicCouchbaseLite.collection_GetCount(colArgs);
4186
+ }
4187
+ /**
4188
+ * @deprecated This will be removed in future versions. Use collection_GetCount instead.
4189
+ */
4190
+ async database_GetDocument(args) {
4191
+ const colArgs = {
4192
+ name: args.name,
4193
+ collectionName: this._defaultCollectionName,
4194
+ scopeName: this._defaultScopeName,
4195
+ docId: args.docId,
4196
+ };
4197
+ return IonicCouchbaseLite.collection_GetDocument(colArgs);
4198
+ }
4199
+ /**
4200
+ * @deprecated This function will be removed in future versions. Use colllection_CreateIndex instead.
4201
+ */
4202
+ async database_GetIndexes(args) {
4203
+ const colArgs = {
4204
+ name: args.name,
4205
+ collectionName: this._defaultCollectionName,
4206
+ scopeName: this._defaultScopeName,
4207
+ };
4208
+ return IonicCouchbaseLite.collection_GetIndexes(colArgs);
4209
+ }
4210
+ async database_GetPath(args) {
4211
+ return IonicCouchbaseLite.database_GetPath(args);
4212
+ }
4213
+ async database_Open(args) {
4214
+ return IonicCouchbaseLite.database_Open(args);
4215
+ }
4216
+ async database_PerformMaintenance(args) {
4217
+ return IonicCouchbaseLite.database_PerformMaintenance(args);
4218
+ }
4219
+ /**
4220
+ * @deprecated This will be removed in future versions. Use collection_GetCount instead.
4221
+ */
4222
+ async database_PurgeDocument(args) {
4223
+ const colArgs = {
4224
+ name: args.name,
4225
+ collectionName: this._defaultCollectionName,
4226
+ scopeName: this._defaultScopeName,
4227
+ docId: args.docId,
4228
+ };
4229
+ return IonicCouchbaseLite.collection_PurgeDocument(colArgs);
4230
+ }
4231
+ /**
4232
+ * @deprecated This function will be removed in future versions. Use colllection_Save instead.
4233
+ */
4234
+ async database_Save(args) {
4235
+ const colArgs = {
4236
+ name: args.name,
4237
+ collectionName: this._defaultCollectionName,
4238
+ scopeName: this._defaultScopeName,
4239
+ id: args.id,
4240
+ document: JSON.stringify(args.document),
4241
+ blobs: JSON.stringify(args.blobs),
4242
+ concurrencyControl: args.concurrencyControl,
4243
+ };
4244
+ return IonicCouchbaseLite.collection_Save(colArgs);
4245
+ }
4246
+ async database_SetFileLoggingConfig(args) {
4247
+ return IonicCouchbaseLite.database_SetFileLoggingConfig(args);
4248
+ }
4249
+ async database_SetLogLevel(args) {
4250
+ return IonicCouchbaseLite.database_SetLogLevel(args);
4251
+ }
4252
+ /**
4253
+ * @deprecated This will be removed in future versions. Use collection_GetCount instead.
4254
+ */
4255
+ async document_GetBlobContent(args) {
4256
+ const colArgs = {
4257
+ name: args.name,
4258
+ collectionName: this._defaultCollectionName,
4259
+ scopeName: this._defaultScopeName,
4260
+ documentId: args.documentId,
4261
+ key: args.key
4262
+ };
4263
+ const data = await IonicCouchbaseLite.collection_GetBlobContent(colArgs);
4264
+ return { data: new Uint8Array(data.data).buffer };
4265
+ }
4266
+ async file_GetDefaultPath() {
4267
+ return IonicCouchbaseLite.file_GetDefaultPath();
4268
+ }
4269
+ async file_GetFileNamesInDirectory(args) {
4270
+ return IonicCouchbaseLite.file_GetFileNamesInDirectory(args);
4271
+ }
4272
+ async plugin_Configure(config) {
4273
+ return IonicCouchbaseLite.plugin_Configure({
4274
+ config,
4275
+ });
4276
+ }
4277
+ query_AddChangeListener(args, cb) {
4278
+ return IonicCouchbaseLite.query_AddChangeListener({
4279
+ name: args.name,
4280
+ query: args.query,
4281
+ parameters: args.parameters,
4282
+ changeListenerToken: args.changeListenerToken,
4283
+ }, cb);
4284
+ }
4285
+ async query_Execute(args) {
4286
+ return await IonicCouchbaseLite.query_Execute(args);
4287
+ }
4288
+ async query_Explain(args) {
4289
+ return await IonicCouchbaseLite.query_Explain(args);
4290
+ }
4291
+ async query_RemoveChangeListener(args) {
4292
+ return IonicCouchbaseLite.query_RemoveChangeListener(args);
4293
+ }
4294
+ replicator_AddChangeListener(args, cb) {
4295
+ return IonicCouchbaseLite.replicator_AddChangeListener(args, cb);
4296
+ }
4297
+ replicator_AddDocumentChangeListener(args, cb) {
4298
+ return IonicCouchbaseLite.replicator_AddDocumentChangeListener(args, cb);
4299
+ }
4300
+ async replicator_Cleanup(args) {
4301
+ return IonicCouchbaseLite.replicator_Cleanup(args);
4302
+ }
4303
+ async replicator_Create(args) {
4304
+ return await IonicCouchbaseLite.replicator_Create(args);
4305
+ }
4306
+ async replicator_GetStatus(args) {
4307
+ return IonicCouchbaseLite.replicator_GetStatus(args);
4308
+ }
4309
+ async replicator_GetPendingDocumentIds(args) {
4310
+ return IonicCouchbaseLite.replicator_GetPendingDocumentIds(args);
4311
+ }
4312
+ async replicator_IsDocumentPending(args) {
4313
+ return IonicCouchbaseLite.replicator_IsDocumentPending(args);
4314
+ }
4315
+ async replicator_ResetCheckpoint(args) {
4316
+ return IonicCouchbaseLite.replicator_ResetCheckpoint(args);
4317
+ }
4318
+ async replicator_RemoveChangeListener(args) {
4319
+ return IonicCouchbaseLite.replicator_RemoveChangeListener(args);
4320
+ }
4321
+ async replicator_Start(args) {
4322
+ return IonicCouchbaseLite.replicator_Start(args);
4323
+ }
4324
+ async replicator_Stop(args) {
4325
+ return IonicCouchbaseLite.replicator_Stop(args);
4326
+ }
4327
+ async scope_GetDefault(args) {
4328
+ return IonicCouchbaseLite.scope_GetDefault(args);
4329
+ }
4330
+ async scope_GetScope(args) {
4331
+ return IonicCouchbaseLite.scope_GetScope(args);
4332
+ }
4333
+ async scope_GetScopes(args) {
4334
+ return IonicCouchbaseLite.scope_GetScopes(args);
4335
+ }
4336
+ getUUID() {
4337
+ return v4().toString();
4338
+ }
4339
+ }
4340
+
4341
+ exports.AbstractIndex = AbstractIndex;
4342
+ exports.AggregateExpression = AggregateExpression;
4343
+ exports.Authenticator = Authenticator;
4344
+ exports.BasicAuthenticator = BasicAuthenticator;
4345
+ exports.BinaryExpression = BinaryExpression;
4346
+ exports.Blob = Blob;
4347
+ exports.CapacitorEngine = CapacitorEngine;
4348
+ exports.Collation = Collation;
4349
+ exports.CollationASCII = CollationASCII;
4350
+ exports.CollationExpression = CollationExpression;
4351
+ exports.CollationUnicode = CollationUnicode;
4352
+ exports.Collection = Collection;
4353
+ exports.CollectionConfig = CollectionConfig;
4354
+ exports.CompoundExpression = CompoundExpression;
4355
+ exports.CouchbaseLiteException = CouchbaseLiteException;
4356
+ exports.Database = Database;
4357
+ exports.DatabaseConfiguration = DatabaseConfiguration;
4358
+ exports.DatabaseLogging = DatabaseLogging;
4359
+ exports.Document = Document;
4360
+ exports.DocumentReplication = DocumentReplication;
4361
+ exports.EngineLocator = EngineLocator;
4362
+ exports.Expression = Expression;
4363
+ exports.FileSystem = FileSystem;
4364
+ exports.FullTextExpression = FullTextExpression;
4365
+ exports.FullTextIndex = FullTextIndex;
4366
+ exports.FullTextIndexItem = FullTextIndexItem;
4367
+ exports.FullTextMatchExpression = FullTextMatchExpression;
4368
+ exports.FunctionExpression = FunctionExpression;
4369
+ exports.IndexBuilder = IndexBuilder;
4370
+ exports.IonicCouchbaseLite = IonicCouchbaseLite;
4371
+ exports.Meta = Meta;
4372
+ exports.MetaExpression = MetaExpression;
4373
+ exports.MutableDocument = MutableDocument;
4374
+ exports.Ordering = Ordering;
4375
+ exports.Parameter = Parameter;
4376
+ exports.ParameterExpression = ParameterExpression;
4377
+ exports.Parameters = Parameters;
4378
+ exports.PropertyExpression = PropertyExpression;
4379
+ exports.Query = Query;
4380
+ exports.ReplicatedDocument = ReplicatedDocument;
4381
+ exports.Replicator = Replicator;
4382
+ exports.ReplicatorConfiguration = ReplicatorConfiguration;
4383
+ exports.ReplicatorProgress = ReplicatorProgress;
4384
+ exports.ReplicatorStatus = ReplicatorStatus;
4385
+ exports.Scope = Scope;
4386
+ exports.SessionAuthenticator = SessionAuthenticator;
4387
+ exports.SortOrder = SortOrder;
4388
+ exports.URLEndpoint = URLEndpoint;
4389
+ exports.UnaryExpression = UnaryExpression;
4390
+ exports.ValueExpression = ValueExpression;
4391
+ exports.ValueIndex = ValueIndex;
4392
+ exports.ValueIndexItem = ValueIndexItem;
4393
+ exports.VariableExpression = VariableExpression;
4394
+ exports.isDocumentReplicationRepresentation = isDocumentReplicationRepresentation;
4395
+ exports.isReplicatedDocumentRepresentation = isReplicatedDocumentRepresentation;
4396
+ exports.isReplicatorChange = isReplicatorChange;
4397
+
4398
+ Object.defineProperty(exports, '__esModule', { value: true });
4399
+
4400
+ return exports;
4401
+
4402
+ })({}, capacitorExports);
4403
+ //# sourceMappingURL=plugin.js.map