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