monsqlize 1.3.0 → 2.0.0

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 (172) hide show
  1. package/CHANGELOG.md +56 -60
  2. package/LICENSE +201 -21
  3. package/README.md +537 -1828
  4. package/changelogs/README.md +160 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/dist/cjs/index.cjs +10600 -0
  7. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  8. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  9. package/dist/cjs/transaction/Transaction.cjs +158 -0
  10. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  11. package/dist/esm/index.mjs +10650 -0
  12. package/dist/types/base.d.ts +81 -0
  13. package/dist/types/collection.d.ts +1031 -0
  14. package/dist/types/expression.d.ts +115 -0
  15. package/dist/types/index.d.ts +23 -0
  16. package/dist/types/lock.d.ts +74 -0
  17. package/dist/types/model.d.ts +526 -0
  18. package/dist/types/mongodb.d.ts +49 -0
  19. package/dist/types/monsqlize.d.ts +491 -0
  20. package/dist/types/pool.d.ts +84 -0
  21. package/dist/types/runtime.d.ts +362 -0
  22. package/dist/types/saga.d.ts +143 -0
  23. package/dist/types/slow-query-log.d.ts +126 -0
  24. package/dist/types/sync.d.ts +103 -0
  25. package/dist/types/transaction.d.ts +132 -0
  26. package/package.json +67 -69
  27. package/index.d.ts +0 -206
  28. package/index.mjs +0 -52
  29. package/lib/cache-invalidation.js +0 -279
  30. package/lib/cache.js +0 -530
  31. package/lib/common/cursor.js +0 -59
  32. package/lib/common/docs-urls.js +0 -73
  33. package/lib/common/index-options.js +0 -223
  34. package/lib/common/log.js +0 -61
  35. package/lib/common/namespace.js +0 -22
  36. package/lib/common/normalize.js +0 -34
  37. package/lib/common/page-result.js +0 -43
  38. package/lib/common/runner.js +0 -57
  39. package/lib/common/server-features.js +0 -232
  40. package/lib/common/shape-builders.js +0 -27
  41. package/lib/common/validation.js +0 -113
  42. package/lib/connect.js +0 -99
  43. package/lib/constants.js +0 -55
  44. package/lib/count-queue.js +0 -188
  45. package/lib/distributed-cache-invalidator.js +0 -260
  46. package/lib/errors.js +0 -168
  47. package/lib/expression/cache/ExpressionCache.js +0 -114
  48. package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
  49. package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
  50. package/lib/expression/detector.js +0 -84
  51. package/lib/expression/factory.js +0 -29
  52. package/lib/expression/index.js +0 -19
  53. package/lib/function-cache.js +0 -533
  54. package/lib/index.js +0 -1251
  55. package/lib/infrastructure/ConnectionPoolManager.js +0 -464
  56. package/lib/infrastructure/HealthChecker.js +0 -281
  57. package/lib/infrastructure/PoolConfig.js +0 -199
  58. package/lib/infrastructure/PoolSelector.js +0 -225
  59. package/lib/infrastructure/PoolStats.js +0 -244
  60. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
  61. package/lib/infrastructure/ssh-tunnel.js +0 -41
  62. package/lib/infrastructure/uri-parser.js +0 -36
  63. package/lib/lock/Lock.js +0 -67
  64. package/lib/lock/errors.js +0 -28
  65. package/lib/lock/index.js +0 -13
  66. package/lib/logger.js +0 -225
  67. package/lib/model/examples/test.js +0 -311
  68. package/lib/model/features/defaults.js +0 -161
  69. package/lib/model/features/populate.js +0 -568
  70. package/lib/model/features/relations.js +0 -120
  71. package/lib/model/features/soft-delete.js +0 -349
  72. package/lib/model/features/version.js +0 -157
  73. package/lib/model/features/virtuals.js +0 -219
  74. package/lib/model/index.js +0 -1265
  75. package/lib/mongodb/common/accessor-helpers.js +0 -59
  76. package/lib/mongodb/common/agg-pipeline.js +0 -36
  77. package/lib/mongodb/common/aggregation-validator.js +0 -127
  78. package/lib/mongodb/common/iid.js +0 -28
  79. package/lib/mongodb/common/lexicographic-expr.js +0 -53
  80. package/lib/mongodb/common/shape.js +0 -32
  81. package/lib/mongodb/common/sort.js +0 -39
  82. package/lib/mongodb/common/transaction-aware.js +0 -25
  83. package/lib/mongodb/connect.js +0 -234
  84. package/lib/mongodb/index.js +0 -639
  85. package/lib/mongodb/management/admin-ops.js +0 -200
  86. package/lib/mongodb/management/bookmark-ops.js +0 -167
  87. package/lib/mongodb/management/cache-ops.js +0 -50
  88. package/lib/mongodb/management/collection-ops.js +0 -387
  89. package/lib/mongodb/management/database-ops.js +0 -202
  90. package/lib/mongodb/management/index-ops.js +0 -475
  91. package/lib/mongodb/management/index.js +0 -17
  92. package/lib/mongodb/management/namespace.js +0 -31
  93. package/lib/mongodb/management/validation-ops.js +0 -268
  94. package/lib/mongodb/queries/aggregate.js +0 -172
  95. package/lib/mongodb/queries/chain.js +0 -631
  96. package/lib/mongodb/queries/count.js +0 -99
  97. package/lib/mongodb/queries/distinct.js +0 -78
  98. package/lib/mongodb/queries/find-and-count.js +0 -193
  99. package/lib/mongodb/queries/find-by-ids.js +0 -236
  100. package/lib/mongodb/queries/find-one-by-id.js +0 -171
  101. package/lib/mongodb/queries/find-one.js +0 -71
  102. package/lib/mongodb/queries/find-page.js +0 -618
  103. package/lib/mongodb/queries/find.js +0 -171
  104. package/lib/mongodb/queries/index.js +0 -51
  105. package/lib/mongodb/queries/watch.js +0 -538
  106. package/lib/mongodb/writes/common/batch-retry.js +0 -65
  107. package/lib/mongodb/writes/delete-batch.js +0 -323
  108. package/lib/mongodb/writes/delete-many.js +0 -181
  109. package/lib/mongodb/writes/delete-one.js +0 -173
  110. package/lib/mongodb/writes/find-one-and-delete.js +0 -203
  111. package/lib/mongodb/writes/find-one-and-replace.js +0 -239
  112. package/lib/mongodb/writes/find-one-and-update.js +0 -240
  113. package/lib/mongodb/writes/increment-one.js +0 -259
  114. package/lib/mongodb/writes/index.js +0 -46
  115. package/lib/mongodb/writes/insert-batch.js +0 -508
  116. package/lib/mongodb/writes/insert-many.js +0 -223
  117. package/lib/mongodb/writes/insert-one.js +0 -169
  118. package/lib/mongodb/writes/replace-one.js +0 -226
  119. package/lib/mongodb/writes/result-handler.js +0 -237
  120. package/lib/mongodb/writes/update-batch.js +0 -416
  121. package/lib/mongodb/writes/update-many.js +0 -275
  122. package/lib/mongodb/writes/update-one.js +0 -273
  123. package/lib/mongodb/writes/upsert-one.js +0 -203
  124. package/lib/multi-level-cache.js +0 -244
  125. package/lib/operators.js +0 -330
  126. package/lib/redis-cache-adapter.js +0 -267
  127. package/lib/saga/SagaContext.js +0 -67
  128. package/lib/saga/SagaDefinition.js +0 -32
  129. package/lib/saga/SagaExecutor.js +0 -201
  130. package/lib/saga/SagaOrchestrator.js +0 -186
  131. package/lib/saga/index.js +0 -11
  132. package/lib/slow-query-log/base-storage.js +0 -70
  133. package/lib/slow-query-log/batch-queue.js +0 -97
  134. package/lib/slow-query-log/config-manager.js +0 -196
  135. package/lib/slow-query-log/index.js +0 -238
  136. package/lib/slow-query-log/mongodb-storage.js +0 -324
  137. package/lib/slow-query-log/query-hash.js +0 -39
  138. package/lib/sync/ChangeStreamSyncManager.js +0 -405
  139. package/lib/sync/ResumeTokenStore.js +0 -192
  140. package/lib/sync/SyncConfig.js +0 -127
  141. package/lib/sync/SyncTarget.js +0 -240
  142. package/lib/sync/index.js +0 -20
  143. package/lib/transaction/CacheLockManager.js +0 -162
  144. package/lib/transaction/DistributedCacheLockManager.js +0 -475
  145. package/lib/transaction/Transaction.js +0 -315
  146. package/lib/transaction/TransactionManager.js +0 -267
  147. package/lib/transaction/index.js +0 -11
  148. package/lib/utils/objectid-converter.js +0 -632
  149. package/types/README.md +0 -122
  150. package/types/base.ts +0 -94
  151. package/types/batch.ts +0 -187
  152. package/types/cache.ts +0 -71
  153. package/types/chain.ts +0 -254
  154. package/types/collection.ts +0 -357
  155. package/types/expression.ts +0 -109
  156. package/types/function-cache.d.ts +0 -135
  157. package/types/lock.ts +0 -95
  158. package/types/model/definition.ts +0 -152
  159. package/types/model/index.ts +0 -10
  160. package/types/model/instance.ts +0 -121
  161. package/types/model/relations.ts +0 -121
  162. package/types/model/virtuals.ts +0 -32
  163. package/types/monsqlize.ts +0 -245
  164. package/types/options.ts +0 -192
  165. package/types/pagination.ts +0 -154
  166. package/types/pool.ts +0 -125
  167. package/types/query.ts +0 -71
  168. package/types/saga.ts +0 -125
  169. package/types/stream.ts +0 -64
  170. package/types/sync.ts +0 -79
  171. package/types/transaction.ts +0 -79
  172. package/types/write.ts +0 -77
@@ -0,0 +1,491 @@
1
+ import type { LoggerLike } from './base';
2
+
3
+ /**
4
+ * SSH tunnel configuration for connecting through a bastion host.
5
+ * @since v1.3.0
6
+ */
7
+ export interface SSHConfig {
8
+ /** SSH server hostname or IP. */
9
+ host: string;
10
+ /** SSH server port (default: 22). */
11
+ scopedCollection<TSchema = unknown>(name: string, options?: { database?: string; pool?: string; }): Collection<TSchema>;
12
+ /** SSH login username. */
13
+ username: string;
14
+ /** SSH password (mutually exclusive with privateKey). */
15
+ password?: string;
16
+ /** SSH private key string or Buffer (mutually exclusive with password and privateKeyPath). */
17
+ privateKey?: string | Buffer;
18
+ /** Path to an SSH private key file; supports ~ for home directory (mutually exclusive with password and privateKey). @since v1.3.0 */
19
+ privateKeyPath?: string;
20
+ /** Passphrase for an encrypted private key. */
21
+ passphrase?: string;
22
+ /** Connection ready timeout in milliseconds (default: 20000). */
23
+ readyTimeout?: number;
24
+ /** Keep-alive interval in milliseconds (default: 30000). */
25
+ keepaliveInterval?: number;
26
+ /** Target database host as seen from the SSH server (default: auto-parsed from URI). */
27
+ dstHost?: string;
28
+ /** Target database port as seen from the SSH server (default: auto-parsed from URI). */
29
+ dstPort?: number;
30
+ /** Fixed local TCP port for the tunnel; omit for a random OS-assigned port. @since v1.3.0 */
31
+ localPort?: number;
32
+ }
33
+
34
+ import type { Collection, DbAccessor, HealthView } from './collection';
35
+ import type { Lock, LockOptions, LockStats } from './lock';
36
+ import type { ModelInstance } from './model';
37
+ import type { MongoConnectConfig } from './mongodb';
38
+ import type { ConnectionPoolManagerOptions, PoolConfig, PoolHealthStatus, PoolStats, PoolStrategy } from './pool';
39
+ import type {
40
+ BatchQueue,
41
+ CacheLike,
42
+ CacheLockManager,
43
+ DistributedCacheInvalidator,
44
+ FunctionCache,
45
+ Logger,
46
+ MemoryCache,
47
+ MultiLevelCache,
48
+ MultiLevelCacheOptions,
49
+ SlowQueryLogConfigManager,
50
+ SlowQueryLogMemoryStorage,
51
+ MongoDBSlowQueryLogStorage,
52
+ TransactionManager,
53
+ createExpression,
54
+ compilePipelineExpressions,
55
+ createRedisCacheAdapter,
56
+ expr,
57
+ generateQueryHash,
58
+ hasExpressionInObject,
59
+ hasExpressionInPipeline,
60
+ isExpressionObject,
61
+ validateSyncConfig,
62
+ withCache,
63
+ adaptLegacyCacheLike,
64
+ } from './runtime';
65
+ import type { SagaDefinition, SagaOrchestrator, SagaResult, SagaStats } from './saga';
66
+ import type { SlowQueryLogConfigInput, SlowQueryLogEntry, SlowQueryLogFilter, SlowQueryLogManager, SlowQueryLogQueryOptions, SlowQueryLogRecord } from './slow-query-log';
67
+ import type { ChangeStreamSyncManager, SyncConfig, SyncStats } from './sync';
68
+ import type { Transaction, TransactionOptions } from './transaction';
69
+
70
+ export interface MonSQLizeOptions {
71
+ type?: 'mongodb';
72
+ databaseName?: string;
73
+ /** @alias databaseName — v1 compatibility */
74
+ database?: string;
75
+ config?: MongoConnectConfig;
76
+ /**
77
+ * Cache configuration. Accepts:
78
+ * - A `MemoryCache` instance (direct injection)
79
+ * - A `CacheLike` instance (v1 compat: custom cache implementation)
80
+ * - A `MultiLevelCacheOptions` object (multi-level cache setup)
81
+ * - A plain config object. Recognised fields:
82
+ * `maxEntries` / `maxSize` (v1 alias), `maxMemory`, `defaultTtl` / `ttl` (v1 alias),
83
+ * `enableStats`, `enableTags`, `cleanupInterval`, `enabled`,
84
+ * `autoInvalidate` (v1 alias for `cacheAutoInvalidate`)
85
+ */
86
+ cache?: CacheLike | MemoryCache | MultiLevelCacheOptions | {
87
+ /** Maximum number of entries; v2 name. Alias: maxSize (v1). */
88
+ maxEntries?: number;
89
+ /** @deprecated Use `maxEntries`. v1 alias for `maxEntries`. */
90
+ maxSize?: number;
91
+ /** Maximum memory in bytes (0 = unlimited). */
92
+ maxMemory?: number;
93
+ /** Default TTL in milliseconds; v2 name. Alias: ttl (v1). */
94
+ defaultTtl?: number;
95
+ /** @deprecated Use `defaultTtl`. v1 alias for `defaultTtl`. */
96
+ ttl?: number;
97
+ /** Enable cache hit/miss statistics. Default: true. */
98
+ enableStats?: boolean;
99
+ /** Enable tag-based invalidation. Default: false. */
100
+ enableTags?: boolean;
101
+ /** Periodic TTL cleanup interval in milliseconds. */
102
+ cleanupInterval?: number;
103
+ /** Disable cache entirely when false. Default: true. */
104
+ enabled?: boolean;
105
+ /** @deprecated Use top-level `cacheAutoInvalidate`. v1 alias: auto-invalidate on writes. */
106
+ autoInvalidate?: boolean;
107
+ /**
108
+ * Distributed cache invalidation via Redis Pub/Sub.
109
+ * When configured, broadcasts `delPattern` events to all other connected instances.
110
+ * Requires `ioredis` to be installed separately.
111
+ * @since v2.0.0
112
+ */
113
+ distributed?: {
114
+ /** Redis URL for the Pub/Sub connection. Defaults to `"redis://localhost:6379"`. */
115
+ redisUrl?: string;
116
+ /** Existing ioredis `Redis` instance to use for publishing. */
117
+ redis?: unknown;
118
+ /** Pub/Sub channel name shared across instances. Default: `"cache-hub:invalidate"`. */
119
+ channel?: string;
120
+ /** Unique ID for this instance; used to filter self-published messages. Auto-generated if omitted. */
121
+ instanceId?: string;
122
+ /** Set to `false` to disable without removing the config block. Default: `true`. */
123
+ enabled?: boolean;
124
+ };
125
+ [key: string]: unknown;
126
+ };
127
+ logger?: LoggerLike | null;
128
+ pools?: PoolConfig[];
129
+ poolStrategy?: PoolStrategy;
130
+ poolFallback?: ConnectionPoolManagerOptions['poolFallback'];
131
+ maxPoolsCount?: number;
132
+ sync?: SyncConfig;
133
+ slowQueryLog?: SlowQueryLogConfigInput;
134
+ /** Global query timeout in milliseconds applied to all find/aggregate operations. Default: 2000. @since v1.3.0 */
135
+ maxTimeMS?: number;
136
+ /** Default limit for find() when caller does not specify one. Default: 10. @since v1.3.0 */
137
+ findLimit?: number;
138
+ /** Slow query threshold in milliseconds; populates slowQueryLog.filter.minExecutionTimeMs when slowQueryLog is enabled. Default: 500. @since v1.3.0 */
139
+ slowQueryMs?: number;
140
+ /** Maximum allowed limit for findPage() operations. Requests exceeding this cap are silently clamped. Default: 500. @since v1.3.0 */
141
+ findPageMaxLimit?: number;
142
+ /** Namespace scope for cursor isolation between multiple MonSQLize instances sharing a cache. @since v1.3.0 */
143
+ namespace?: { scope?: 'database' | 'connection'; instanceId?: string; };
144
+ /** HMAC-SHA256 secret used to sign and verify cursor tokens returned by findPage(). @since v1.3.0 */
145
+ cursorSecret?: string;
146
+ /** Logging tag configuration applied to slow-query event payloads. @since v1.3.0 */
147
+ log?: { slowQueryTag?: { event?: string; code?: string;[key: string]: unknown }; formatSlowQuery?: (meta: unknown) => unknown; };
148
+ /** Auto-convert 24-character hex strings to ObjectId in query filters. Pass a field map to selectively enable per field. Default: true for mongodb type (pass `false` to disable). @since v1.3.0 */
149
+ autoConvertObjectId?: boolean | {
150
+ enabled?: boolean;
151
+ excludeFields?: string[];
152
+ customFieldPatterns?: string[];
153
+ maxDepth?: number;
154
+ logLevel?: 'info' | 'warn' | 'error' | string;
155
+ } | Record<string, boolean>;
156
+ /** Batch count operations to reduce server round-trips. @since v1.3.0 */
157
+ countQueue?: boolean | { enabled?: boolean; concurrency?: number; maxQueueSize?: number; timeout?: number; };
158
+ /** Model definitions to auto-register on connect. Accepts a file path (string) or an object with { path, pattern?, recursive? }. @since v1.3.0 */
159
+ models?: string | { path: string; pattern?: string; recursive?: boolean; };
160
+ /** Auto-invalidate cache on write operations. @since v1.3.0 */
161
+ cacheAutoInvalidate?: boolean;
162
+ }
163
+
164
+ export interface MonSQLizeInstance {
165
+ /**
166
+ * Establish the database connection and return the top-level accessor bundle.
167
+ * @returns Object containing `collection`, `db`, `use` shortcuts and the current instance reference.
168
+ */
169
+ connect(): Promise<{
170
+ collection: <TSchema = any>(name: string) => Collection<TSchema>;
171
+ db: (name?: string) => DbAccessor;
172
+ use: (name: string) => {
173
+ collection: <TSchema = any>(collectionName: string) => Collection<TSchema>;
174
+ model: <TDocument = any>(modelName: string) => ModelInstance<TDocument>;
175
+ };
176
+ instance: MonSQLize;
177
+ }>;
178
+ /**
179
+ * Return the active cache instance (MemoryCache, MultiLevelCache, or a custom CacheLike).
180
+ * Can be used to manually read, write, or invalidate cache entries.
181
+ */
182
+ getCache(): CacheLike;
183
+ /** Return a frozen snapshot of the merged runtime defaults. */
184
+ getDefaults(): Record<string, unknown>;
185
+ /** Close all database connections and release associated resources. */
186
+ close(): Promise<void>;
187
+ /** Return the current connection health status view. */
188
+ health(): Promise<HealthView>;
189
+ /**
190
+ * Return a collection accessor for the given collection name.
191
+ * @param name Collection name.
192
+ */
193
+ collection<TSchema = any>(name: string): Collection<TSchema>;
194
+ collection(name: string): Collection<any>;
195
+ /**
196
+ * Return a database accessor, optionally scoped to a specific database.
197
+ * @param name Target database name; omit to use the default database.
198
+ */
199
+ db(name?: string): DbAccessor;
200
+ /**
201
+ * Switch to the given database and return its `collection` and `model` accessors.
202
+ * @param name Target database name.
203
+ */
204
+ use(name: string): {
205
+ collection: <TSchema = any>(collectionName: string) => Collection<TSchema>;
206
+ model: <TDocument = any>(modelName: string) => ModelInstance<TDocument>;
207
+ };
208
+ /**
209
+ * Return collection and model accessors for the named connection pool.
210
+ * @param poolName Connection pool name.
211
+ */
212
+ pool(poolName: string): {
213
+ collection: <TSchema = any>(name: string) => Collection<TSchema>;
214
+ model: <TDocument = any>(name: string) => ModelInstance<TDocument>;
215
+ use: (dbName: string) => {
216
+ collection: <TSchema = any>(name: string) => Collection<TSchema>;
217
+ model: <TDocument = any>(name: string) => ModelInstance<TDocument>;
218
+ };
219
+ };
220
+ /**
221
+ * Return a collection accessor scoped to the given database.
222
+ * @param name Collection name.
223
+ * @param options Optional database scope options.
224
+ */
225
+ scopedCollection<TSchema = any>(name: string, options?: { database?: string; pool?: string; }): Collection<TSchema>;
226
+ scopedCollection(name: string, options?: { database?: string; pool?: string; }): Collection<any>;
227
+ /**
228
+ * Return a model instance scoped to the given database or connection pool.
229
+ * @param name Model name.
230
+ * @param options Optional database or pool scope options.
231
+ */
232
+ scopedModel<TDocument = any>(name: string, options?: { database?: string; pool?: string; }): ModelInstance<TDocument>;
233
+ scopedModel(name: string, options?: { database?: string; pool?: string; }): ModelInstance<any>;
234
+ /**
235
+ * Return the registered model instance for the given model name.
236
+ * @param name Model name used during registration.
237
+ */
238
+ model<TDocument = any>(name: string): ModelInstance<TDocument>;
239
+ model(name: string): ModelInstance<any>;
240
+ /**
241
+ * Start a MongoDB transaction session.
242
+ * @param options Optional transaction options.
243
+ * @returns The transaction session object.
244
+ */
245
+ startSession(options?: TransactionOptions): Promise<Transaction>;
246
+ /**
247
+ * Execute a callback inside a transaction; commits on success, auto-rolls back on failure.
248
+ * @param callback Async callback that receives the transaction session.
249
+ * @param options Optional transaction options.
250
+ */
251
+ withTransaction<T>(callback: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
252
+ /**
253
+ * Execute a callback while holding a distributed lock; the lock is released automatically on completion.
254
+ * @param key Unique lock identifier key.
255
+ * @param callback Async callback executed while the lock is held.
256
+ * @param options Optional lock options.
257
+ */
258
+ withLock<T>(key: string, callback: () => Promise<T>, options?: LockOptions): Promise<T>;
259
+ /**
260
+ * Acquire a distributed lock, blocking until it is available or the timeout is reached.
261
+ * @param key Unique lock identifier key.
262
+ * @param options Optional lock options.
263
+ * @returns The acquired lock instance.
264
+ */
265
+ acquireLock(key: string, options?: LockOptions): Promise<Lock>;
266
+ /**
267
+ * Try to acquire a distributed lock without blocking; returns `null` if the lock is already held.
268
+ * @param key Unique lock identifier key.
269
+ * @param options Optional lock options (`retryTimes` is not supported).
270
+ * @returns The acquired lock instance, or `null` if unavailable.
271
+ */
272
+ tryAcquireLock(key: string, options?: Omit<LockOptions, 'retryTimes'>): Promise<Lock | null>;
273
+ /** Return the ChangeStream sync manager; `null` when sync is not enabled. */
274
+ getSyncManager(): ChangeStreamSyncManager | null;
275
+ /** Return the slow-query log manager; `null` when slow-query logging is not enabled. */
276
+ getSlowQueryLogManager(): SlowQueryLogManager | null;
277
+ /** Return the Saga orchestrator instance. */
278
+ getSagaOrchestrator(): SagaOrchestrator;
279
+ /** Shorthand alias for `getSagaOrchestrator()`. */
280
+ saga(): SagaOrchestrator;
281
+ /**
282
+ * Register a Saga definition.
283
+ * @param definition Saga definition object containing steps and compensation logic.
284
+ */
285
+ defineSaga(definition: SagaDefinition): Promise<SagaDefinition>;
286
+ /**
287
+ * Execute the named registered Saga.
288
+ * @param name Saga name.
289
+ * @param data Initial data passed into the Saga.
290
+ * @returns The Saga execution result.
291
+ */
292
+ executeSaga(name: string, data: unknown): Promise<SagaResult>;
293
+ /** List all registered Saga names. */
294
+ listSagas(): string[];
295
+ /** Return Saga execution statistics (success / failure / compensation counts, etc.). */
296
+ getSagaStats(): SagaStats;
297
+ /** Start ChangeStream data synchronisation. */
298
+ startSync(): Promise<void>;
299
+ /** Stop ChangeStream data synchronisation. */
300
+ stopSync(): Promise<void>;
301
+ /** Return current data sync statistics; `null` when sync is not enabled. */
302
+ getSyncStats(): SyncStats | null;
303
+ /**
304
+ * Manually record a slow-query log entry.
305
+ * @param log The slow-query log entry object.
306
+ */
307
+ recordSlowQuery(log: SlowQueryLogEntry): Promise<void>;
308
+ /**
309
+ * Query slow-query log records.
310
+ * @param filter Optional filter criteria.
311
+ * @param options Optional pagination and sort options.
312
+ * @returns Array of matching slow-query log records.
313
+ */
314
+ getSlowQueryLogs(filter?: SlowQueryLogFilter, options?: SlowQueryLogQueryOptions): Promise<SlowQueryLogRecord[]>;
315
+ /**
316
+ * Subscribe to an event.
317
+ * @param event Event name.
318
+ * @param handler Event handler callback.
319
+ */
320
+ on(event: string, handler: (payload: unknown) => void): void;
321
+ /**
322
+ * Subscribe to an event; automatically unsubscribes after the first invocation.
323
+ * @param event Event name.
324
+ * @param handler Event handler callback.
325
+ */
326
+ once(event: string, handler: (payload: unknown) => void): void;
327
+ /**
328
+ * Unsubscribe from an event.
329
+ * @param event Event name.
330
+ * @param handler The handler to remove.
331
+ */
332
+ off(event: string, handler: (payload: unknown) => void): void;
333
+ /**
334
+ * Emit an event and dispatch the payload to all subscribers.
335
+ * @param event Event name.
336
+ * @param payload Event payload data.
337
+ */
338
+ emit(event: string, payload: unknown): void;
339
+ /**
340
+ * Dynamically add a connection pool.
341
+ * @param config Pool configuration object.
342
+ * @since v1.3.0 — v1 pool management parity
343
+ */
344
+ addPool(config: PoolConfig): Promise<void>;
345
+ /**
346
+ * Remove the named connection pool and close its connections.
347
+ * @param name Connection pool name.
348
+ */
349
+ removePool(name: string): Promise<void>;
350
+ /** Return the names of all registered connection pools. */
351
+ getPoolNames(): string[];
352
+ /** Return runtime statistics for all connection pools. */
353
+ getPoolStats(): Record<string, PoolStats>;
354
+ /** Return the health status of all connection pools. */
355
+ getPoolHealth(): Record<string, PoolHealthStatus>;
356
+ /** Return distributed lock usage statistics; `null` when locks are not enabled. */
357
+ getLockStats(): LockStats | null;
358
+ /**
359
+ * List all databases accessible on the current connection.
360
+ * @param options Pass `nameOnly: true` to return a plain string array of database names.
361
+ * @since v1.3.0 — v1 database management parity
362
+ */
363
+ listDatabases(options?: { nameOnly?: boolean }): Promise<Array<{ name: string; sizeOnDisk: number; empty: boolean }> | string[]>;
364
+ /**
365
+ * Drop the current default database; requires explicit confirmation via `confirm: true`.
366
+ * @param options Drop confirmation and safety options.
367
+ * @returns Object containing the operation result, database name, and timestamp.
368
+ */
369
+ dropDatabase(options?: { confirm: boolean; allowProduction?: boolean; user?: string }): Promise<{ dropped: boolean; database: string; timestamp: Date }>;
370
+ /**
371
+ * List all collections in the current database.
372
+ * @param filter Optional collection name filter.
373
+ * @param options Optional driver-level options.
374
+ * @returns Array of objects containing collection name and type.
375
+ */
376
+ listCollections(filter?: Record<string, unknown>, options?: Record<string, unknown>): Promise<Array<{ name: string; type: string }>>;
377
+ /**
378
+ * Execute a raw MongoDB command on the current database.
379
+ * @param command Command document object.
380
+ * @param options Optional driver-level options.
381
+ * @returns The command result document.
382
+ */
383
+ runCommand(command: Record<string, unknown>, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
384
+ }
385
+
386
+ export default class MonSQLize implements MonSQLizeInstance {
387
+ constructor(options?: MonSQLizeOptions);
388
+ connect(): Promise<{
389
+ collection: <TSchema = any>(name: string) => Collection<TSchema>;
390
+ db: (name?: string) => DbAccessor;
391
+ use: (name: string) => {
392
+ collection: <TSchema = any>(collectionName: string) => Collection<TSchema>;
393
+ model: <TDocument = any>(modelName: string) => ModelInstance<TDocument>;
394
+ };
395
+ instance: MonSQLize;
396
+ }>;
397
+ getCache(): CacheLike;
398
+ getDefaults(): Record<string, unknown>;
399
+ close(): Promise<void>;
400
+ health(): Promise<HealthView>;
401
+ collection<TSchema = any>(name: string): Collection<TSchema>;
402
+ collection(name: string): Collection<any>;
403
+ db(name?: string): DbAccessor;
404
+ use(name: string): {
405
+ collection: <TSchema = any>(collectionName: string) => Collection<TSchema>;
406
+ model: <TDocument = any>(modelName: string) => ModelInstance<TDocument>;
407
+ };
408
+ pool(poolName: string): {
409
+ collection: <TSchema = any>(name: string) => Collection<TSchema>;
410
+ model: <TDocument = any>(name: string) => ModelInstance<TDocument>;
411
+ use: (dbName: string) => {
412
+ collection: <TSchema = any>(name: string) => Collection<TSchema>;
413
+ model: <TDocument = any>(name: string) => ModelInstance<TDocument>;
414
+ };
415
+ };
416
+ scopedCollection<TSchema = any>(name: string, options?: { database?: string; pool?: string; }): Collection<TSchema>;
417
+ scopedCollection(name: string, options?: { database?: string; pool?: string; }): Collection<any>;
418
+ scopedModel<TDocument = any>(name: string, options?: { database?: string; pool?: string; }): ModelInstance<TDocument>;
419
+ scopedModel(name: string, options?: { database?: string; pool?: string; }): ModelInstance<any>;
420
+ model<TDocument = any>(name: string): ModelInstance<TDocument>;
421
+ model(name: string): ModelInstance<any>;
422
+ startSession(options?: TransactionOptions): Promise<Transaction>;
423
+ withTransaction<T>(callback: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
424
+ withLock<T>(key: string, callback: () => Promise<T>, options?: LockOptions): Promise<T>;
425
+ acquireLock(key: string, options?: LockOptions): Promise<Lock>;
426
+ tryAcquireLock(key: string, options?: Omit<LockOptions, 'retryTimes'>): Promise<Lock | null>;
427
+ getSyncManager(): ChangeStreamSyncManager | null;
428
+ getSlowQueryLogManager(): SlowQueryLogManager | null;
429
+ getSagaOrchestrator(): SagaOrchestrator;
430
+ saga(): SagaOrchestrator;
431
+ defineSaga(definition: SagaDefinition): Promise<SagaDefinition>;
432
+ executeSaga(name: string, data: unknown): Promise<SagaResult>;
433
+ listSagas(): string[];
434
+ getSagaStats(): SagaStats;
435
+ startSync(): Promise<void>;
436
+ stopSync(): Promise<void>;
437
+ getSyncStats(): SyncStats | null;
438
+ recordSlowQuery(log: SlowQueryLogEntry): Promise<void>;
439
+ getSlowQueryLogs(filter?: SlowQueryLogFilter, options?: SlowQueryLogQueryOptions): Promise<SlowQueryLogRecord[]>;
440
+ on(event: string, handler: (payload: unknown) => void): void;
441
+ once(event: string, handler: (payload: unknown) => void): void;
442
+ off(event: string, handler: (payload: unknown) => void): void;
443
+ emit(event: string, payload: unknown): void;
444
+ addPool(config: PoolConfig): Promise<void>;
445
+ removePool(name: string): Promise<void>;
446
+ getPoolNames(): string[];
447
+ getPoolStats(): Record<string, PoolStats>;
448
+ getPoolHealth(): Record<string, PoolHealthStatus>;
449
+ getLockStats(): LockStats | null;
450
+ listDatabases(options?: { nameOnly?: boolean }): Promise<Array<{ name: string; sizeOnDisk: number; empty: boolean }> | string[]>;
451
+ dropDatabase(options?: { confirm: boolean; allowProduction?: boolean; user?: string }): Promise<{ dropped: boolean; database: string; timestamp: Date }>;
452
+ listCollections(filter?: Record<string, unknown>, options?: Record<string, unknown>): Promise<Array<{ name: string; type: string }>>;
453
+ runCommand(command: Record<string, unknown>, options?: Record<string, unknown>): Promise<Record<string, unknown>>;
454
+
455
+ static Logger: typeof Logger;
456
+ static MemoryCache: typeof MemoryCache;
457
+ static Transaction: typeof Transaction;
458
+ static TransactionManager: typeof TransactionManager;
459
+ static CacheLockManager: typeof CacheLockManager;
460
+ static Lock: typeof Lock;
461
+ static LockManager: typeof import('./lock').LockManager;
462
+ static LockAcquireError: typeof import('./lock').LockAcquireError;
463
+ static LockTimeoutError: typeof import('./lock').LockTimeoutError;
464
+ static DistributedCacheInvalidator: typeof DistributedCacheInvalidator;
465
+ static ConnectionPoolManager: typeof import('./pool').ConnectionPoolManager;
466
+ static Model: typeof import('./runtime').Model;
467
+ static ModelInstance: typeof import('./runtime').ModelInstance;
468
+ static expr: typeof expr;
469
+ static createExpression: typeof createExpression;
470
+ static compilePipelineExpressions: typeof compilePipelineExpressions;
471
+ static isExpressionObject: typeof isExpressionObject;
472
+ static hasExpressionInObject: typeof hasExpressionInObject;
473
+ static hasExpressionInPipeline: typeof hasExpressionInPipeline;
474
+ static createRedisCacheAdapter: typeof createRedisCacheAdapter;
475
+ static withCache: typeof withCache;
476
+ static FunctionCache: typeof FunctionCache;
477
+ static adaptLegacyCacheLike: typeof adaptLegacyCacheLike;
478
+ static MultiLevelCache: typeof MultiLevelCache;
479
+ static ChangeStreamSyncManager: typeof ChangeStreamSyncManager;
480
+ static ResumeTokenStore: typeof import('./sync').ResumeTokenStore;
481
+ static validateSyncConfig: typeof validateSyncConfig;
482
+ static SlowQueryLogManager: typeof SlowQueryLogManager;
483
+ static SlowQueryLogConfigManager: typeof SlowQueryLogConfigManager;
484
+ static SlowQueryLogMemoryStorage: typeof SlowQueryLogMemoryStorage;
485
+ static MongoDBSlowQueryLogStorage: typeof MongoDBSlowQueryLogStorage;
486
+ static BatchQueue: typeof BatchQueue;
487
+ static generateQueryHash: typeof generateQueryHash;
488
+ static SagaOrchestrator: typeof SagaOrchestrator;
489
+ }
490
+
491
+ export { MonSQLize };
@@ -0,0 +1,84 @@
1
+ import type { MongoClientOptions } from 'mongodb';
2
+
3
+ import type { LoggerLike } from './base';
4
+
5
+ export type PoolRole = 'primary' | 'secondary' | 'analytics' | 'custom';
6
+ export type PoolStrategy = 'auto' | 'roundRobin' | 'weighted' | 'leastConnections' | 'manual';
7
+ export type FallbackStrategy = 'error' | 'readonly' | 'primary' | 'secondary';
8
+
9
+ export interface PoolConfig {
10
+ name: string;
11
+ uri: string;
12
+ role?: PoolRole;
13
+ weight?: number;
14
+ tags?: string[];
15
+ options?: MongoClientOptions;
16
+ healthCheck?: {
17
+ enabled?: boolean;
18
+ interval?: number;
19
+ timeout?: number;
20
+ retries?: number;
21
+ };
22
+ }
23
+
24
+ export interface ConnectionPoolManagerOptions {
25
+ pools?: PoolConfig[];
26
+ maxPoolsCount?: number;
27
+ poolStrategy?: PoolStrategy;
28
+ poolFallback?: boolean | {
29
+ enabled?: boolean;
30
+ fallbackStrategy?: FallbackStrategy;
31
+ retryDelay?: number;
32
+ maxRetries?: number;
33
+ };
34
+ logger?: LoggerLike | null;
35
+ }
36
+
37
+ export interface PoolHealthStatus {
38
+ status: 'up' | 'down' | 'degraded';
39
+ consecutiveFailures: number;
40
+ lastCheckTime: Date | null;
41
+ lastError: Error | null;
42
+ uptime: number;
43
+ }
44
+
45
+ export interface PoolStats {
46
+ name: string;
47
+ /** Current active connections (reported by MongoDB driver). v2 extension — v1 fixtures may omit. */
48
+ connections?: number;
49
+ /** Available (idle) connections in the pool. v2 extension — v1 fixtures may omit. */
50
+ available?: number;
51
+ /** Requests currently waiting for a connection. v2 extension — v1 fixtures may omit. */
52
+ waiting?: number;
53
+ /** Health status from the last health check. v2 extension — v1 fixtures may omit. */
54
+ status?: 'up' | 'down' | 'degraded' | 'unknown';
55
+ totalRequests: number;
56
+ successCount: number;
57
+ errorCount: number;
58
+ avgResponseTime: number;
59
+ minResponseTime: number;
60
+ maxResponseTime: number;
61
+ errorRate: number;
62
+ lastRequestTime: Date | null;
63
+ }
64
+
65
+ export declare class ConnectionPoolManager {
66
+ constructor(options?: ConnectionPoolManagerOptions);
67
+ addPool(config: PoolConfig): Promise<void>;
68
+ removePool(name: string): Promise<void>;
69
+ getPool(name: string): unknown | null;
70
+ getPoolNames(): string[];
71
+ selectPool(operation: string, options?: { pool?: string; tags?: string[]; databaseName?: string; }): {
72
+ name: string;
73
+ client: unknown;
74
+ db: (name?: string) => unknown;
75
+ collection: (databaseName: string | undefined, collectionName: string) => unknown;
76
+ };
77
+ startHealthCheck(name?: string): void;
78
+ stopHealthCheck(name?: string): void;
79
+ getPoolHealth(): Map<string, PoolHealthStatus>;
80
+ getHealthStatus(): Record<string, PoolHealthStatus>;
81
+ getPoolStats(): Record<string, PoolStats>;
82
+ close(): Promise<void>;
83
+ }
84
+