babymongo 0.2.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.
@@ -0,0 +1,2 @@
1
+ var e,t={exports:{}};var r=function(){if(e)return t.exports;e=1;var r,n="object"==typeof Reflect?Reflect:null,i=n&&"function"==typeof n.apply?n.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};r=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var o=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}t.exports=s,t.exports.once=function(e,t){return new Promise(function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&m(e,"error",t,r)}(e,i,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function l(e,t,r,n){var i,o,s,a;if(c(r),void 0===(o=e._events)?(o=e._events=/* @__PURE__ */Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=u(e))>0&&s.length>i&&!s.warned){s.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=s.length,a=l,console&&console.warn&&console.warn(a)}return e}function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=f.bind(n);return i.listener=r,n.wrapFn=i,i}function d(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):g(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function g(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function m(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(o){n.once&&e.removeEventListener(t,i),r(o)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||o(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=/* @__PURE__ */Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||o(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,o=this._events;if(void 0!==o)n=n&&void 0===o.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var u=c.length,l=g(c,u);for(r=0;r<u;++r)i(l[r],this,t)}return!0},s.prototype.addListener=function(e,t){return l(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return l(this,e,t,!0)},s.prototype.once=function(e,t){return c(t),this.on(e,h(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,h(this,e,t)),this},s.prototype.removeListener=function(e,t){var r,n,i,o,s;if(c(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=/* @__PURE__ */Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=/* @__PURE__ */Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=/* @__PURE__ */Object.create(null):delete r[e]),this;if(0===arguments.length){var i,o=Object.keys(r);for(n=0;n<o.length;++n)"removeListener"!==(i=o[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=/* @__PURE__ */Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return d(this,e,!0)},s.prototype.rawListeners=function(e){return d(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},s.prototype.listenerCount=p,s.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]},t.exports}();const n={OK:0,INTERNAL_ERROR:1,BAD_VALUE:2,NO_SUCH_KEY:4,GRAPH_CONTAINS_CYCLE:5,HOST_UNREACHABLE:6,HOST_NOT_FOUND:7,UNKNOWN_ERROR:8,FAILED_TO_PARSE:17287,CANNOT_MUTATE_OBJECT:10,USER_NOT_FOUND:11,UNSUPPORTED_FORMAT:12,UNAUTHORIZED:13,TYPE_MISMATCH:14,OVERFLOW:15,INVALID_LENGTH:16,PROTOCOL_ERROR:17,AUTHENTICATION_FAILED:18,ILLEGAL_OPERATION:20,NAMESPACE_NOT_FOUND:26,INDEX_NOT_FOUND:27,PATH_NOT_VIABLE:28,CANNOT_CREATE_INDEX:67,INDEX_ALREADY_EXISTS:68,INDEX_EXISTS:68,COMMAND_NOT_FOUND:59,NAMESPACE_EXISTS:48,INVALID_NAMESPACE:73,INDEX_OPTIONS_CONFLICT:85,INVALID_INDEX_SPECIFICATION_OPTION:197,WRITE_CONFLICT:112,DUPLICATE_KEY:11e3,DUPLICATE_KEY_UPDATE:11001,DOCUMENT_VALIDATION_FAILURE:121,BAD_QUERY:2,CANNOT_INDEX_PARALLEL_ARRAYS:171,CURSOR_NOT_FOUND:43,COLLECTION_IS_EMPTY:26,CANNOT_DO_EXCLUSION_ON_FIELD_ID_IN_INCLUSION_PROJECTION:31254,NOT_IMPLEMENTED:999,OPERATION_NOT_SUPPORTED:998};class i extends Error{constructor(e,t={}){super(e),this.name="MongoError",this.code=t.code||n.UNKNOWN_ERROR,this.codeName=this._getCodeName(this.code),this.$err=e,t.collection&&(this.collection=t.collection),t.database&&(this.database=t.database),t.operation&&(this.operation=t.operation),t.query&&(this.query=t.query),t.document&&(this.document=t.document),t.field&&(this.field=t.field),t.index&&(this.index=t.index),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}_getCodeName(e){return{0:"OK",1:"InternalError",2:"BadValue",4:"NoSuchKey",5:"GraphContainsCycle",6:"HostUnreachable",7:"HostNotFound",8:"UnknownError",10:"CannotMutateObject",11:"UserNotFound",12:"UnsupportedFormat",13:"Unauthorized",14:"TypeMismatch",15:"Overflow",16:"InvalidLength",17:"ProtocolError",18:"AuthenticationFailed",20:"IllegalOperation",26:"NamespaceNotFound",27:"IndexNotFound",28:"PathNotViable",43:"CursorNotFound",48:"NamespaceExists",59:"CommandNotFound",67:"CannotCreateIndex",68:"IndexExists",73:"InvalidNamespace",85:"IndexOptionsConflict",112:"WriteConflict",121:"DocumentValidationFailure",171:"CannotIndexParallelArrays",197:"InvalidIndexSpecificationOption",998:"OperationNotSupported",999:"NotImplemented",11e3:"DuplicateKey",11001:"DuplicateKeyUpdate",17287:"FailedToParse"}[e]||"UnknownError"}toJSON(){const e={name:this.name,message:this.message,code:this.code,codeName:this.codeName};return this.collection&&(e.collection=this.collection),this.database&&(e.database=this.database),this.operation&&(e.operation=this.operation),this.index&&(e.index=this.index),this.indexName&&(e.indexName=this.indexName),this.field&&(e.field=this.field),this.query&&(e.query=this.query),this.document&&(e.document=this.document),this.namespace&&(e.namespace=this.namespace),this.cursorId&&(e.cursorId=this.cursorId),this.feature&&(e.feature=this.feature),this.keyPattern&&(e.keyPattern=this.keyPattern),this.keyValue&&(e.keyValue=this.keyValue),this.writeErrors&&(e.writeErrors=this.writeErrors),e}}class o extends i{constructor(e,t={}){super(e,t),this.name="MongoServerError"}}class s extends i{constructor(e,t={}){super(e,t),this.name="MongoDriverError",this.code=t.code||n.INTERNAL_ERROR}}class a extends i{constructor(e,t={}){super(e,t),this.name="WriteError",this.code=t.code||n.WRITE_CONFLICT}}class c extends a{constructor(e,t={}){const r=JSON.stringify(e);super(`E11000 duplicate key error${t.collection?` collection: ${t.collection}`:""} index: ${r} dup key: ${r}`,{...t,code:n.DUPLICATE_KEY}),this.name="DuplicateKeyError",this.keyPattern=e,this.keyValue=t.keyValue||e}}class u extends i{constructor(e,t={}){super(e,t),this.name="ValidationError",this.code=t.code||n.DOCUMENT_VALIDATION_FAILURE,this.validationErrors=t.validationErrors||[]}}class l extends i{constructor(e,t={}){super(e,t),this.name="IndexError"}}class f extends l{constructor(e,t={}){super(`Index with name '${e}' already exists`,{...t,code:n.INDEX_EXISTS}),this.name="IndexExistsError",this.indexName=e}}class h extends l{constructor(e,t={}){super(`Index '${e}' not found`,{...t,code:n.INDEX_NOT_FOUND,index:e}),this.name="IndexNotFoundError",this.indexName=e}}class d extends l{constructor(e,t={}){super(`Cannot create index: ${e}`,{...t,code:n.CANNOT_CREATE_INDEX}),this.name="CannotCreateIndexError"}}class p extends i{constructor(e,t={}){super(e,t),this.name="QueryError",this.code=t.code||n.BAD_QUERY}}class g extends i{constructor(e,t,r,i={}){super(`Type mismatch for field '${e}': expected ${t}, got ${r}`,{...i,code:n.TYPE_MISMATCH,field:e}),this.name="TypeMismatchError",this.expectedType=t,this.actualType=r}}class m extends i{constructor(e,t={}){super(e,t),this.name="NamespaceError"}}class y extends m{constructor(e,t={}){super(`Namespace '${e}' not found`,{...t,code:n.NAMESPACE_NOT_FOUND}),this.name="NamespaceNotFoundError",this.namespace=e}}class _ extends m{constructor(e,t,r={}){"object"!=typeof t||r||(r=t,t=void 0);super(t?`Invalid namespace '${e}': ${t}`:`Invalid namespace '${e}'`,{...r,code:n.INVALID_NAMESPACE}),this.name="InvalidNamespaceError",this.namespace=e}}class b extends i{constructor(e,t={}){super(e,t),this.name="CursorError"}}class v extends b{constructor(e,t={}){super(`Cursor ${e} not found`,{...t,code:n.CURSOR_NOT_FOUND}),this.name="CursorNotFoundError",this.cursorId=e}}class w extends i{constructor(e,t={}){super(`${e} is not implemented in babymongo`,{...t,code:n.NOT_IMPLEMENTED}),this.name="NotImplementedError",this.feature=e}}class C extends i{constructor(e,t,r={}){"object"!=typeof t||r||(r=t,t=void 0);super(t?`Operation '${e}' is not supported: ${t}`:`Operation '${e}' is not supported`,{...r,code:n.OPERATION_NOT_SUPPORTED,operation:e}),this.name="OperationNotSupportedError"}}class A extends i{constructor(e,t,r,i={}){super(`Bad value for field '${e}': ${r}`,{...i,code:n.BAD_VALUE,field:e}),this.name="BadValueError",this.value=t}}class E extends i{constructor(e=[],t={}){super(`Bulk write operation error: ${e.length} error(s)`,t),this.name="BulkWriteError",this.writeErrors=e,this.code=t.code||n.WRITE_CONFLICT}}class x extends i{constructor(e,t={}){super(e,t),this.name="MongoNetworkError",this.code=t.code||n.HOST_UNREACHABLE}}class N extends r.EventEmitter{static create({bridge:e,database:t,collection:r,streamId:n,pipeline:i=[],options:o={}}){const s=new N({bridge:e,streamId:n});if(!n){let n,a;null==t?(n="client",a="watch"):null==r?(n="db",a="watch"):(n="collection",a="watch"),e.sendRequest({target:n,database:t,collection:r,method:a,args:[i,o]}).then(e=>{e&&e.streamId&&(s.streamId=e.streamId)}).catch(()=>{})}return s}constructor({bridge:e,streamId:t}){super(),this.bridge=e,this.streamId=t,this.closed=!1,this._pendingNext=[],this._onEvent=this._onEvent.bind(this),this.bridge.on("event",this._onEvent)}_onEvent(e,t){if("changeStream"!==e)return;if(!t||t.streamId!==this.streamId)return;const{type:r,data:n}=t;"change"===r&&this.emit("change",n),"error"===r&&this.emit("error",n),"close"===r&&(this.emit("close"),this._cleanup())}_cleanup(){this.bridge.off("event",this._onEvent)}async close(){if(!this.closed){this.closed=!0;for(const e of this._pendingNext)e.resolve(null);this._pendingNext=[],this.bridge.sendRequest({target:"changestream",streamId:this.streamId,method:"close"}).catch(()=>{}),this.emit("close"),this._cleanup()}}async next(){return this.closed?null:new Promise((e,t)=>{const r=t=>{this._removePending(o),this.off("change",r),this.off("error",n),this.off("close",i),e(t)},n=e=>{this._removePending(o),this.off("change",r),this.off("error",n),this.off("close",i),t(e)},i=()=>{this._removePending(o),this.off("change",r),this.off("error",n),this.off("close",i),e(null)},o={resolve:e,reject:t};this._pendingNext.push(o),this.on("change",r),this.on("error",n),this.on("close",i)})}_removePending(e){const t=this._pendingNext.indexOf(e);-1!==t&&this._pendingNext.splice(t,1)}async*[Symbol.asyncIterator](){for(;!this.closed;){const e=await this.next();if(null===e)break;yield e}}}class ${constructor({bridge:e,cursorId:t,batch:r=[],exhausted:n=!1,batchSize:i=100,requestPromise:o,requestPayload:s}){this.bridge=e,this.cursorId=t,this.buffer=Array.isArray(r)?r:[],this.exhausted=n||!1,this._batchSize=i,this._requestPromise=o||null,this._requestPayload=s||null,this._initialized=!o&&!s}async _ensureInitialized(){if(!this._initialized)if(this._requestPayload){const e={};void 0!==this._limit&&(e.limit=this._limit),void 0!==this._skip&&(e.skip=this._skip),void 0!==this._sort&&(e.sort=this._sort),void 0!==this._min&&(e.min=this._min),void 0!==this._max&&(e.max=this._max),void 0!==this._hint&&(e.hint=this._hint),void 0!==this._comment&&(e.comment=this._comment),void 0!==this._maxTimeMS&&(e.maxTimeMS=this._maxTimeMS),void 0!==this._maxScan&&(e.maxScan=this._maxScan),void 0!==this._returnKey&&(e.returnKey=this._returnKey),void 0!==this._showRecordId&&(e.showRecordId=this._showRecordId),void 0!==this._collation&&(e.collation=this._collation),this._requestPayload.cursorOpts=e;const t=await this.bridge.sendRequest(this._requestPayload);this.cursorId=t.cursorId,this.buffer=t.batch||[],this.exhausted=t.exhausted||!1,this._batchSize=t.batchSize||100,this._requestPayload=null,this._initialized=!0}else if(this._requestPromise){const e=await this._requestPromise;this.cursorId=e.cursorId,this.buffer=e.batch||[],this.exhausted=e.exhausted||!1,this._batchSize=e.batchSize||100,this._requestPromise=null,this._initialized=!0}}async hasNext(){return!this._closed&&(await this._ensureInitialized(),this.buffer.length>0||!this.exhausted&&(await this._getMore(),this.buffer.length>0))}async next(){return await this.hasNext()?this.buffer.shift():null}async toArray(){await this._ensureInitialized();const e=[...this.buffer];for(this.buffer=[];!this.exhausted;)await this._getMore(),e.push(...this.buffer),this.buffer=[];return e}async count(){return(await this.toArray()).length}limit(e){return this._limit=e,this}skip(e){return this._skip=e,this}sort(e){return this._sort=e,this}batchSize(e){return this._batchSize=e,this}async close(){return this._closed=!0,await this._closeRemote(),!1}isClosed(){return this._closed||!1}comment(e){return this._comment=e,this}hint(e){return this._hint=e,this}explain(e="queryPlanner"){const t={queryPlanner:{plannerVersion:1,namespace:"unknown",indexFilterSet:!1,parsedQuery:{},winningPlan:{stage:"COLLSCAN"}},ok:1};return"executionStats"!==e&&"allPlansExecution"!==e||(t.executionStats={executionSuccess:!0,nReturned:0,executionTimeMillis:0}),t}async itcount(){let e=0;for(;await this.hasNext();)await this.next(),e++;return e}size(){return this.buffer.length}min(e){return this._min=e,this._minIndexBounds=e,this}max(e){return this._max=e,this._maxIndexBounds=e,this}maxTimeMS(e){return this._maxTimeMS=e,this}maxScan(e){return this._maxScan=e,this}noCursorTimeout(){return this._noCursorTimeout=!0,this}objsLeftInBatch(){return this.buffer.length}pretty(){return this._pretty=!0,this}readConcern(e){return this._readConcern=e,this}readPref(e,t){return this._readPref={mode:e,tagSet:t},this}returnKey(e=!0){return this._returnKey=e,this}showRecordId(e=!0){return this._showRecordId=e,this}allowDiskUse(e=!0){return this._allowDiskUse=e,this}collation(e){return this._collation=e,this}async forEach(e){for(;await this.hasNext();){const t=await this.next();await e(t)}}async map(e){const t=[];for(;await this.hasNext();){const r=await this.next();t.push(await e(r))}return t}async*[Symbol.asyncIterator](){for(;await this.hasNext();)yield await this.next()}async _getMore(){if(this.exhausted)return;const e=await this.bridge.sendRequest({target:"cursor",cursorId:this.cursorId,method:"getMore",args:[{batchSize:this._batchSize}]});this.buffer=e?.batch||[],this.exhausted=!!e?.exhausted,this.exhausted&&await this._closeRemote()}async _closeRemote(){if(this.cursorId){try{await this.bridge.sendRequest({target:"cursor",cursorId:this.cursorId,method:"close"})}catch(e){}this.cursorId=null}}}class I{constructor({dbName:e,name:t,bridge:r,db:n}){return this.dbName=e,this.name=t,this.bridge=r,this._db=n,this.indexes=[],new Proxy(this,{get:(e,t,r)=>t in e?Reflect.get(e,t,r):"symbol"==typeof t||String(t).startsWith("_")?void 0:"watch"===t?(...t)=>e._watch(...t):"find"===t||"aggregate"===t?(...r)=>e._cursorMethod(String(t),r):(...r)=>e._call(String(t),r)})}_cursorMethod(e,t=[]){"find"===e&&t.length>=2&&this._validateProjection(t[1]);const r={target:"collection",database:this.dbName,collection:this.name,method:e,args:t},n=new $({bridge:this.bridge,requestPayload:r});return"aggregate"===e&&(n.then=function(e,t){return this.toArray().then(e,t)}),n}_validateProjection(e){if(!e||0===Object.keys(e).length)return;const t=Object.keys(e);let r=!1,i=!1;for(const n of t)if("_id"!==n&&(e[n]?r=!0:i=!0,r&&i))break;if(r&&i)throw new p("Cannot do exclusion on field in inclusion projection",{code:n.CANNOT_DO_EXCLUSION_ON_FIELD_ID_IN_INCLUSION_PROJECTION,collection:this.name})}_call(e,t=[]){return this.bridge.sendRequest({target:"collection",database:this.dbName,collection:this.name,method:e,args:t}).then(r=>{if(r&&r.cursorId)return new $({bridge:this.bridge,cursorId:r.cursorId,batch:r.batch,exhausted:r.exhausted,batchSize:r.batchSize});if("copyTo"===e&&t.length>0&&this._db&&this._db.collection(t[0]),"createIndex"===e){const e=t[0],r=t[1]||{},n=r.name||Object.entries(e).map(([e,t])=>`${e}_${t}`).join("_");this.indexes.find(e=>e.name===n)||this.indexes.push({name:n,key:e,...r})}if("dropIndex"===e){const e=t[0];this.indexes=this.indexes.filter(t=>t.name!==e)}return"dropIndexes"===e&&(this.indexes=[]),"drop"===e&&(this.indexes=[]),r})}getIndexes(){return this.indexes}_watch(e=[],t={}){return N.create({bridge:this.bridge,database:this.dbName,collection:this.name,pipeline:e,options:t})}}class S{constructor({dbName:e,bridge:t,options:r={}}){this.dbName=e,this.bridge=t,this.options=r,this.collections=/* @__PURE__ */new Map;const n=/* @__PURE__ */new Set(["getCollectionNames","getCollectionInfos","createCollection","dropCollection","dropDatabase","collection","getCollection","watch"]);return this._methodNames=n,new Proxy(this,{get:(e,t,r)=>t in e?Reflect.get(e,t,r):"symbol"==typeof t||String(t).startsWith("_")?void 0:n.has(t)?"createCollection"===t?(...n)=>{const i=n[0];return e.collection(i,r),e._call(String(t),n)}:"dropCollection"===t?(...r)=>{const n=r[0];return e.collections.delete(n),e._call(String(t),r)}:"dropDatabase"===t?(...r)=>(e.collections.clear(),e._call(String(t),r)):"watch"===t?(...t)=>e._watch(...t):(...r)=>e._call(String(t),r):e.collection(t,r)})}collection(e,t){if(this.collections.has(e))return this.collections.get(e);const r=new I({dbName:this.dbName,name:e,bridge:this.bridge,db:t||this});return this.collections.set(e,r),r}getCollectionNames(){return Array.from(this.collections.keys())}async close(){}_call(e,t=[]){return this.bridge.sendRequest({target:"db",database:this.dbName,method:e,args:t}).then(e=>e&&e.streamId?N.create({bridge:this.bridge,database:this.dbName,collection:null,streamId:e.streamId}):e)}_watch(e=[],t={}){return N.create({bridge:this.bridge,database:this.dbName,collection:null,pipeline:e,options:t})}}class O extends r.EventEmitter{constructor(e="mongodb://localhost:27017",t={}){if(super(),this.uri=e,this.options=Object.freeze({...t}),this._isConnected=!1,this._defaultDb=this._parseDefaultDbName(e),this._databases=/* @__PURE__ */new Map,!t.workerBridge)throw new Error("workerBridge is required. Create one with: const bridge = await WorkerBridge.create()");this._bridge=t.workerBridge,this._ownsBridge=!1}static async connect(e,t={}){const r=new O(e,t);return await r.connect(),r}async connect(){return this._isConnected||(this._isConnected=!0,this.emit("open",this)),this}db(e,t={}){const r=e||this._defaultDb;if(!r)throw new Error("No database name provided and no default in connection string");if(this._databases.has(r))return this._databases.get(r);const n=new S({dbName:r,bridge:this._bridge,options:{...this.options,...t}});return this._databases.set(r,n),n}async close(){this._bridge&&this._ownsBridge&&(await this._bridge.terminate(),this._bridge=null),this._isConnected=!1,this.emit("close")}async close(e=!1){if(this._isConnected){for(const[e,t]of this._databases)await t.close();this._databases.clear(),this._isConnected=!1,this.emit("close")}}startSession(e={}){return{id:crypto.randomUUID(),endSession:()=>{},withTransaction:async e=>await e(this)}}async withSession(e,t){const r=this.startSession("function"==typeof e?{}:e),n="function"==typeof e?e:t;try{return await n(r)}finally{r.endSession()}}get readConcern(){return this.options.readConcern}get writeConcern(){return this.options.writeConcern}get readPreference(){return this.options.readPreference}watch(e=[],t={}){return N.create({bridge:this._bridge,database:null,collection:null,pipeline:e,options:t})}_parseDefaultDbName(e){const t=e.match(/\/([^/?]+)/);return t?t[1]:null}_parseUriParams(e){const t={},r=e.indexOf("?");if(-1===r)return t;const n=e.substring(r+1).split("&");for(const i of n){const[e,r]=i.split("=");e&&("true"===r?t[e]=!0:"false"===r?t[e]=!1:isNaN(r)?t[e]=decodeURIComponent(r||""):t[e]=Number(r))}return t}}class T{constructor(e){if(null==e)this.id=T.generate();else if("string"==typeof e){if(!T.isValid(e))throw new Error(`Argument passed in must be a string of 24 hex characters, got: ${e}`);this.id=e.toLowerCase()}else if(e instanceof Uint8Array&&12===e.length)this.id=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");else{if(!(e instanceof T))throw new Error("Argument passed in must be a string of 24 hex characters or an ObjectId");this.id=e.id}}toString(){return this.id}toHexString(){return this.id}getTimestamp(){const e=parseInt(this.id.substring(0,8),16);return new Date(1e3*e)}equals(e){if(!(e instanceof T))throw new Error("Can only compare with another ObjectId");return this.id===e.id}compare(e){if(!(e instanceof T))throw new Error("Can only compare with another ObjectId");return this.id.localeCompare(e.id)}toJSON(){return this.id}inspect(){return`ObjectId("${this.id}")`}toBytes(){const e=new Uint8Array(12);for(let t=0;t<12;t++)e[t]=parseInt(this.id.substring(2*t,2*t+2),16);return e}static isValid(e){return!!e&&("string"==typeof e&&(24===e.length&&/^[0-9a-fA-F]{24}$/.test(e)))}static createFromTime(e){const t=("00000000"+Math.floor(e/1e3).toString(16)).slice(-8);return new T(t+"0000000000000000")}static generate(){const e=Math.floor(Date.now()/1e3),t="undefined"!=typeof crypto&&crypto.getRandomValues?new Uint8Array(8):null;let r="";if(t){crypto.getRandomValues(t);for(let e=0;e<t.length;e++)r+=("0"+t[e].toString(16)).slice(-2)}else r=Math.random().toString(16).slice(2).padEnd(8,"0").slice(0,8)+Math.random().toString(16).slice(2).padEnd(8,"0").slice(0,8);return(("00000000"+e.toString(16)).slice(-8)+r).slice(0,24)}}function D(e,t){return e instanceof T||t instanceof T?e instanceof T&&t instanceof T||e instanceof T&&"string"==typeof t?e.equals(t):t instanceof T&&"string"==typeof e&&t.equals(e):e==t}function M(e,t){for(var r=t.split("."),n=e[r[0]],i=1;i<r.length;i++){if(null==n||null==n)return n;var o=r[i],s=parseInt(o,10);n=L(n)&&!isNaN(s)&&s>=0&&s<n.length?n[s]:n[o]}return n}function L(e){return Array==e.constructor}function P(e,t){for(var r=0;r<t.length;r++)if(D(t[r],e))return!0;return!1}function R(e,t){if(e.length!=t.length)return!1;for(var r=0;r<e.length;r++)if(!D(e[r],t[r])){if(typeof e[r]!=typeof t[r])return!1;if("object"==typeof e[r]&&null!==e[r]){if(L(e[r])){if(!R(e[r],t[r]))return!1}else if(!U(e[r],t[r]))return!1}else if(!D(e[r],t[r]))return!1}return!0}function U(e,t){for(var r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(!D(e[r],t[r])){if(typeof e[r]!=typeof t[r])return!1;if("object"==typeof e[r]&&null!==e[r]){if(L(e[r])){if(!R(e[r],t[r]))return!1}else if(!U(e[r],t[r]))return!1}else if(!D(e[r],t[r]))return!1}}for(var r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}const j={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},k={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},F="[aeiouy]",B="([^aeiou][^aeiouy]*)",q="("+F+"[aeiou]*)",z=new RegExp("^"+B+"?"+q+B),W=new RegExp("^"+B+"?"+q+B+q+"?$"),V=new RegExp("^"+B+"?("+q+B+"){2,}"),H=new RegExp("^"+B+"?"+F),K=new RegExp("^"+B+F+"[^aeiouwxy]$"),Y=/ll$/,X=/^(.+?)e$/,J=/^(.+?)y$/,G=/^(.+?(s|t))(ion)$/,Q=/^(.+?)(ed|ing)$/,Z=/(at|bl|iz)$/,ee=/^(.+?)eed$/,te=/^.+?[^s]s$/,re=/^.+?(ss|i)es$/,ne=/([^aeiouylsz])\1$/,ie=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,oe=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,se=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;const ae=/* @__PURE__ */new Set(["a","about","after","all","also","am","an","and","another","any","are","around","as","at","be","because","been","before","being","between","both","but","by","came","can","come","could","did","do","each","for","from","get","got","has","had","he","have","her","here","him","himself","his","how","i","if","in","into","is","it","like","make","many","me","might","more","most","much","must","my","never","now","of","on","only","or","other","our","out","over","said","same","see","should","since","some","still","such","take","than","that","the","their","them","then","there","these","they","this","those","through","to","too","under","up","very","was","way","we","well","were","what","where","which","while","who","with","would","you","your"]);function ce(e,t){if(null==e)return e;if("boolean"==typeof e||"number"==typeof e)return e;if("string"==typeof e)return e.startsWith("$$")?"$$KEEP"===e||"$$PRUNE"===e||"$$DESCEND"===e?e:M(t,e.substring(2)):"$"===e.charAt(0)?M(t,e.substring(1)):e;if("object"==typeof e){if(Array.isArray(e))return e.map(e=>ce(e,t));const r=Object.keys(e);if(0===r.length)return e;const n=r[0];if("$"===n.charAt(0)){return function(e,t,r){switch(e){case"$add":return function(e,t){if(!Array.isArray(e))return null;let r=0;for(const n of e){const e=ce(n,t);e instanceof Date?r+=e.getTime():"number"==typeof e&&(r+=e)}return r}(t,r);case"$subtract":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);if(r instanceof Date&&n instanceof Date)return r.getTime()-n.getTime();if(r instanceof Date&&"number"==typeof n)return new Date(r.getTime()-n);if("number"==typeof r&&"number"==typeof n)return r-n;return null}(t,r);case"$multiply":return function(e,t){if(!Array.isArray(e))return null;let r=1;for(const n of e){const e=ce(n,t);"number"==typeof e&&(r*=e)}return r}(t,r);case"$divide":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);if("number"==typeof r&&"number"==typeof n&&0!==n)return r/n;return null}(t,r);case"$mod":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);if("number"==typeof r&&"number"==typeof n&&0!==n)return r%n;return null}(t,r);case"$pow":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);if("number"==typeof r&&"number"==typeof n)return Math.pow(r,n);return null}(t,r);case"$sqrt":return function(e,t){const r=ce(e,t);if("number"==typeof r&&r>=0)return Math.sqrt(r);return null}(t,r);case"$abs":return function(e,t){const r=ce(e,t);if("number"==typeof r)return Math.abs(r);return null}(t,r);case"$ceil":return function(e,t){const r=ce(e,t);if("number"==typeof r)return Math.ceil(r);return null}(t,r);case"$floor":return function(e,t){const r=ce(e,t);if("number"==typeof r)return Math.floor(r);return null}(t,r);case"$trunc":return function(e,t){const r=ce(e,t);if("number"==typeof r)return Math.trunc(r);return null}(t,r);case"$round":return function(e,t){const r=ce(Array.isArray(e)?e[0]:e,t),n=Array.isArray(e)&&void 0!==e[1]?ce(e[1],t):0;if("number"==typeof r&&"number"==typeof n){const e=Math.pow(10,n);return Math.round(r*e)/e}return null}(t,r);case"$concat":return function(e,t){if(!Array.isArray(e))return null;let r="";for(const n of e){const e=ce(n,t);null!=e&&(r+=String(e))}return r}(t,r);case"$substr":return function(e,t){if(!Array.isArray(e)||e.length<3)return null;const r=String(ce(e[0],t)||""),n=ce(e[1],t),i=ce(e[2],t);if("number"==typeof n&&"number"==typeof i)return r.substr(n,i);return null}(t,r);case"$toLower":return function(e,t){const r=ce(e,t);return null!=r?String(r).toLowerCase():""}(t,r);case"$toUpper":return function(e,t){const r=ce(e,t);return null!=r?String(r).toUpperCase():""}(t,r);case"$trim":return function(e,t){const r=ce("object"==typeof e&&e.input?e.input:e,t),n=e.chars?ce(e.chars,t):null;let i=null!=r?String(r):"";if(n){const e=new RegExp(`^[${ue(n)}]+|[${ue(n)}]+$`,"g");return i.replace(e,"")}return i.trim()}(t,r);case"$ltrim":return function(e,t){const r=ce("object"==typeof e&&e.input?e.input:e,t),n=e.chars?ce(e.chars,t):null;let i=null!=r?String(r):"";if(n){const e=new RegExp(`^[${ue(n)}]+`,"g");return i.replace(e,"")}return i.replace(/^\s+/,"")}(t,r);case"$rtrim":return function(e,t){const r=ce("object"==typeof e&&e.input?e.input:e,t),n=e.chars?ce(e.chars,t):null;let i=null!=r?String(r):"";if(n){const e=new RegExp(`[${ue(n)}]+$`,"g");return i.replace(e,"")}return i.replace(/\s+$/,"")}(t,r);case"$split":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=String(ce(e[0],t)||""),n=String(ce(e[1],t)||"");return r.split(n)}(t,r);case"$strLenCP":return function(e,t){const r=ce(e,t);return null!=r?String(r).length:0}(t,r);case"$strcasecmp":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=String(ce(e[0],t)||"").toLowerCase(),n=String(ce(e[1],t)||"").toLowerCase();return r<n?-1:r>n?1:0}(t,r);case"$indexOfCP":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;const r=String(ce(e[0],t)||""),n=String(ce(e[1],t)||""),i=void 0!==e[2]?ce(e[2],t):0,o=void 0!==e[3]?ce(e[3],t):r.length,s=r.substring(i,o).indexOf(n);return-1===s?-1:s+i}(t,r);case"$replaceOne":return function(e,t){const r=String(ce(e.input,t)||""),n=String(ce(e.find,t)||""),i=String(ce(e.replacement,t)||"");return r.replace(n,i)}(t,r);case"$replaceAll":return function(e,t){const r=String(ce(e.input,t)||""),n=String(ce(e.find,t)||""),i=String(ce(e.replacement,t)||"");return r.split(n).join(i)}(t,r);case"$cmp":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r<n?-1:r>n?1:0}(t,r);case"$eq":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r===n}(t,r);case"$ne":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r!==n}(t,r);case"$gt":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r>n}(t,r);case"$gte":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r>=n}(t,r);case"$lt":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r<n}(t,r);case"$lte":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return r<=n}(t,r);case"$and":return function(e,t){if(!Array.isArray(e))return null;for(const r of e){if(!ce(r,t))return!1}return!0}(t,r);case"$or":return function(e,t){if(!Array.isArray(e))return null;for(const r of e){if(ce(r,t))return!0}return!1}(t,r);case"$not":return function(e,t){const r=ce(Array.isArray(e)?e[0]:e,t);return!r}(t,r);case"$cond":return function(e,t){let r,n,i;if(Array.isArray(e)){if(3!==e.length)return null;[r,n,i]=e}else{if("object"!=typeof e)return null;r=e.if,n=e.then,i=e.else}const o=ce(r,t);return ce(o?n:i,t)}(t,r);case"$ifNull":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;for(let r=0;r<e.length;r++){const n=ce(e[r],t);if(null!=n)return n}return null}(t,r);case"$switch":return function(e,t){if("object"!=typeof e||!Array.isArray(e.branches))return null;for(const r of e.branches){if(ce(r.case,t))return ce(r.then,t)}return void 0!==e.default?ce(e.default,t):null}(t,r);case"$year":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCFullYear();return null}(t,r);case"$month":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCMonth()+1;return null}(t,r);case"$dayOfMonth":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCDate();return null}(t,r);case"$dayOfWeek":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCDay()+1;return null}(t,r);case"$dayOfYear":return function(e,t){const r=ce(e,t);if(r instanceof Date){const e=new Date(Date.UTC(r.getUTCFullYear(),0,0)),t=r-e,n=864e5;return Math.floor(t/n)}return null}(t,r);case"$hour":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCHours();return null}(t,r);case"$minute":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCMinutes();return null}(t,r);case"$second":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCSeconds();return null}(t,r);case"$millisecond":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r.getUTCMilliseconds();return null}(t,r);case"$week":return function(e,t){const r=ce(e,t);if(r instanceof Date){const e=new Date(Date.UTC(r.getUTCFullYear(),0,1));return Math.ceil(((r-e)/864e5+e.getUTCDay()+1)/7)-1}return null}(t,r);case"$isoWeek":return function(e,t){const r=ce(e,t);if(r instanceof Date){const e=new Date(r.valueOf()),t=(r.getUTCDay()+6)%7;e.setUTCDate(e.getUTCDate()-t+3);const n=e.valueOf();return e.setUTCMonth(0,1),4!==e.getUTCDay()&&e.setUTCMonth(0,1+(4-e.getUTCDay()+7)%7),1+Math.ceil((n-e)/6048e5)}return null}(t,r);case"$isoWeekYear":return function(e,t){const r=ce(e,t);if(r instanceof Date){const e=new Date(r.valueOf());return e.setUTCDate(e.getUTCDate()-(r.getUTCDay()+6)%7+3),e.getUTCFullYear()}return null}(t,r);case"$dateToString":return function(e,t){const r=e.format?ce(e.format,t):"%Y-%m-%dT%H:%M:%S.%LZ",n=ce(e.date,t);return n instanceof Date?r.replace("%Y",n.getUTCFullYear()).replace("%m",String(n.getUTCMonth()+1).padStart(2,"0")).replace("%d",String(n.getUTCDate()).padStart(2,"0")).replace("%H",String(n.getUTCHours()).padStart(2,"0")).replace("%M",String(n.getUTCMinutes()).padStart(2,"0")).replace("%S",String(n.getUTCSeconds()).padStart(2,"0")).replace("%L",String(n.getUTCMilliseconds()).padStart(3,"0")):null}(t,r);case"$toDate":return function(e,t){const r=ce(e,t);if(r instanceof Date)return r;if("string"==typeof r||"number"==typeof r){const e=new Date(r);return isNaN(e.getTime())?null:e}return null}(t,r);case"$arrayElemAt":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);if(!Array.isArray(r)||"number"!=typeof n)return null;const i=n<0?r.length+n:n;return r[i]}(t,r);case"$concatArrays":return function(e,t){if(!Array.isArray(e))return null;const r=[];for(const n of e){const e=ce(n,t);Array.isArray(e)&&r.push(...e)}return r}(t,r);case"$filter":return function(e,t){const r=ce(e.input,t),n=e.as||"this",i=e.cond;return Array.isArray(r)?r.filter(e=>{const r={...t,[n]:e};return ce(i,r)}):null}(t,r);case"$in":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const r=ce(e[0],t),n=ce(e[1],t);return!!Array.isArray(n)&&n.includes(r)}(t,r);case"$indexOfArray":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;const r=ce(e[0],t),n=ce(e[1],t),i=void 0!==e[2]?ce(e[2],t):0,o=void 0!==e[3]?ce(e[3],t):r.length;if(!Array.isArray(r))return null;for(let s=i;s<o&&s<r.length;s++)if(r[s]===n)return s;return-1}(t,r);case"$isArray":return function(e,t){const r=ce(e,t);return Array.isArray(r)}(t,r);case"$map":return function(e,t){const r=ce(e.input,t),n=e.as||"this",i=e.in;return Array.isArray(r)?r.map(e=>{const r={...t,[n]:e};return ce(i,r)}):null}(t,r);case"$reduce":return function(e,t){const r=ce(e.input,t),n=ce(e.initialValue,t),i=e.in;if(!Array.isArray(r))return null;let o=n;for(const s of r){o=ce(i,{...t,value:o,this:s})}return o}(t,r);case"$size":return function(e,t){const r=ce(e,t);return Array.isArray(r)?r.length:null}(t,r);case"$slice":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;const r=ce(e[0],t);if(!Array.isArray(r))return null;if(2===e.length){const n=ce(e[1],t);return n>=0?r.slice(0,n):r.slice(n)}{const n=ce(e[1],t),i=ce(e[2],t);return r.slice(n,n+i)}}(t,r);case"$reverseArray":return function(e,t){const r=ce(e,t);return Array.isArray(r)?r.slice().reverse():null}(t,r);case"$zip":return function(e,t){const r=e.inputs?ce(e.inputs,t):null,n=e.useLongestLength||!1,i=e.defaults;if(!Array.isArray(r))return null;const o=r.map(e=>ce(e,t));if(!o.every(e=>Array.isArray(e)))return null;const s=Math.max(...o.map(e=>e.length)),a=n?s:Math.min(...o.map(e=>e.length)),c=[];for(let u=0;u<a;u++){const e=[];for(let t=0;t<o.length;t++)u<o[t].length?e.push(o[t][u]):i&&t<i.length?e.push(i[t]):e.push(null);c.push(e)}return c}(t,r);case"$type":return function(e,t){const r=ce(e,t);return null===r?"null":void 0===r?"missing":"boolean"==typeof r?"bool":"number"==typeof r?Number.isInteger(r)?"int":"double":"string"==typeof r?"string":r instanceof Date?"date":Array.isArray(r)?"array":"object"==typeof r?"object":"unknown"}(t,r);case"$convert":return function(e,t){const r=ce(e.input,t),n=e.to,i=e.onError,o=e.onNull;if(null===r)return void 0!==o?ce(o,t):null;try{switch(n){case"double":case"decimal":return parseFloat(r);case"int":case"long":return parseInt(r);case"bool":return Boolean(r);case"string":return String(r);case"date":return new Date(r);default:return r}}catch(s){return void 0!==i?ce(i,t):null}}(t,r);case"$toBool":return function(e,t){const r=ce(e,t);return Boolean(r)}(t,r);case"$toDecimal":return function(e,t){const r=ce(e,t);return parseFloat(r)}(t,r);case"$toDouble":return function(e,t){const r=ce(e,t);return parseFloat(r)}(t,r);case"$toInt":return function(e,t){const r=ce(e,t);return parseInt(r)}(t,r);case"$toLong":return function(e,t){const r=ce(e,t);return parseInt(r)}(t,r);case"$toString":return function(e,t){const r=ce(e,t);return null==r?null:String(r)}(t,r);case"$objectToArray":return function(e,t){const r=ce(e,t);if("object"!=typeof r||null===r||Array.isArray(r))return null;return Object.keys(r).map(e=>({k:e,v:r[e]}))}(t,r);case"$arrayToObject":return function(e,t){const r=ce(e,t);if(!Array.isArray(r))return null;const n={};for(const i of r)Array.isArray(i)&&2===i.length?n[i[0]]=i[1]:"object"==typeof i&&void 0!==i.k&&void 0!==i.v&&(n[i.k]=i.v);return n}(t,r);case"$mergeObjects":return function(e,t){if(!Array.isArray(e))return ce(e,t);const r={};for(const n of e){const e=ce(n,t);"object"!=typeof e||null===e||Array.isArray(e)||Object.assign(r,e)}return r}(t,r);case"$literal":return t;default:throw new Error(`Unsupported aggregation operator: ${e}`)}}(n,e[n],t)}{const n={};for(const i of r)n[i]=ce(e[i],t);return n}}return e}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const le={1:"double",2:"string",3:"object",4:"array",5:"binData",6:"undefined",7:"objectId",8:"bool",9:"date",10:"null",11:"regex",13:"javascript",15:"javascriptWithScope",16:"int",17:"timestamp",18:"long",19:"decimal",127:"maxKey","-1":"minKey"},fe=Object.entries(le).reduce((e,[t,r])=>(e[r]=parseInt(t),e),{});function he(e,t){if(L(t)){for(let r=0;r<t.length;r++)if(he(e,t[r]))return!0;return!1}const r="number"==typeof t?t:fe[t],n=le[r]||t;return null===e?"null"===n||10===r:void 0===e?"undefined"===n||6===r:"number"==typeof e?Number.isInteger(e)?"int"===n||16===r:"double"===n||1===r:"string"==typeof e?"string"===n||2===r:"boolean"==typeof e?"bool"===n||8===r:e instanceof Date?"date"===n||9===r:e instanceof T?"objectId"===n||7===r:e instanceof RegExp?"regex"===n||11===r:L(e)?"array"===n||4===r:"object"==typeof e?"object"===n||3===r:typeof e===t}function de(e){if(L(e)){let t=0;for(let r=0;r<e.length;r++)t|=1<<e[r];return t}return"number"==typeof e?e:0}function pe(e,t){if("number"!=typeof e)return!1;const r=de(t);return(e&r)===r}function ge(e,t){if("number"!=typeof e)return!1;return 0===(e&de(t))}function me(e,t){if("number"!=typeof e)return!1;return 0!==(e&de(t))}function ye(e,t){if("number"!=typeof e)return!1;const r=de(t);return(e&r)!==r}function _e(e,t){if(t.type){const r=L(e)?"array":null===e?"null":typeof e;if(t.type!==r)return!1}if(t.required&&L(t.required))for(let r=0;r<t.required.length;r++)if(!(t.required[r]in e))return!1;if(t.properties)for(const r in t.properties){if(!(r in e))return!1;const n=t.properties[r];if(!_e(e[r],n))return!1}if(void 0!==t.minimum&&"number"==typeof e&&e<t.minimum)return!1;if(void 0!==t.maximum&&"number"==typeof e&&e>t.maximum)return!1;if(void 0!==t.minLength&&"string"==typeof e&&e.length<t.minLength)return!1;if(void 0!==t.maxLength&&"string"==typeof e&&e.length>t.maxLength)return!1;if(t.pattern&&"string"==typeof e){if(!new RegExp(t.pattern).test(e))return!1}return!(t.enum&&L(t.enum)&&!t.enum.includes(e))}function be(e,t){return e instanceof T&&t instanceof T?e.equals(t):e==t}function ve(e,t,r){let n=e,i=t;switch(e instanceof T&&(n=e.toString()),t instanceof T&&(i=t.toString()),r){case">":return n>i;case">=":return n>=i;case"<":return n<i;case"<=":return n<=i;default:return!1}}function we(e,t){if(void 0===e)return!1;if(null===e)return t(e);if(L(e)){for(var r=0;r<e.length;r++)if(t(e[r]))return!0;return!1}return t(e)}function Ce(e){if("string"!=typeof e)return[];const t=function(e){return"string"!=typeof e?[]:e.toLowerCase().split(/\W+/).filter(e=>e.length>0).filter(e=>!ae.has(e))}(e);return t.map(e=>function(e){let t=String(e).toLowerCase();if(t.length<3)return t;let r,n=!1;return 121===t.codePointAt(0)&&(n=!0,t="Y"+t.slice(1)),re.test(t)?t=t.slice(0,-2):te.test(t)&&(t=t.slice(0,-1)),(r=ee.exec(t))?z.test(r[1])&&(t=t.slice(0,-1)):(r=Q.exec(t))&&H.test(r[1])&&(t=r[1],Z.test(t)?t+="e":ne.test(t)?t=t.slice(0,-1):K.test(t)&&(t+="e")),(r=J.exec(t))&&H.test(r[1])&&(t=r[1]+"i"),(r=ie.exec(t))&&z.test(r[1])&&(t=r[1]+j[r[2]]),(r=oe.exec(t))&&z.test(r[1])&&(t=r[1]+k[r[2]]),(r=se.exec(t))?V.test(r[1])&&(t=r[1]):(r=G.exec(t))&&V.test(r[1])&&(t=r[1]),(r=X.exec(t))&&(V.test(r[1])||W.test(r[1])&&!K.test(r[1]))&&(t=r[1]),Y.test(t)&&V.test(t)&&(t=t.slice(0,-1)),n&&(t="y"+t.slice(1)),t}(e))}function Ae(e,t){if("string"!=typeof e)return!1;const r=new Set(Ce(e));return Ce(t).some(e=>r.has(e))}function Ee(e,t){try{if(!Array.isArray(t)||2!==t.length)return!1;const r=t[0][0],n=t[0][1],i=t[1][0];return xe(e,r,i,t[1][1],n)}catch(r){return!1}}function xe(e,t,r,n,i){if(!e)return!1;if("FeatureCollection"===e.type&&e.features&&e.features.length>0){for(const o of e.features)if(o.geometry&&!xe(o.geometry,t,r,n,i))return!1;return!0}if("Feature"===e.type&&e.geometry)return xe(e.geometry,t,r,n,i);if("Point"===e.type&&e.coordinates){const[o,s]=e.coordinates;if("number"==typeof o&&"number"==typeof s)return o>=t&&o<=r&&s>=n&&s<=i}if("Polygon"===e.type&&e.coordinates&&e.coordinates.length>0){for(const o of e.coordinates)for(const e of o){const o=e[0],s=e[1];if(o<t||o>r||s<n||s>i)return!1}return!0}return!1}function Ne(e){if(!e)return null;if("FeatureCollection"===e.type&&e.features&&e.features.length>0){const t=e.features[0];if(t.geometry)return Ne(t.geometry)}if("Feature"===e.type&&e.geometry)return Ne(e.geometry);if("Point"===e.type&&e.coordinates){const[t,r]=e.coordinates;if("number"==typeof t&&"number"==typeof r)return{lat:r,lng:t}}if("Polygon"===e.type&&e.coordinates&&e.coordinates.length>0){const t=e.coordinates[0];if(t.length>0){let e=0,r=0;for(const n of t)r+=n[0],e+=n[1];return{lat:e/t.length,lng:r/t.length}}}return null}function $e(e,t,r,n){const i=(r-e)*Math.PI/180,o=(n-t)*Math.PI/180,s=Math.sin(i/2)*Math.sin(i/2)+Math.cos(e*Math.PI/180)*Math.cos(r*Math.PI/180)*Math.sin(o/2)*Math.sin(o/2);return 6371*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}function Ie(e,t,r,n){const i=Ne(e);if(!i)return!1;return 1e3*$e(i.lat,i.lng,r,t)<=n}function Se(e,t){if(!e||!t)return!1;const r=Ne(t);if(!r)return!1;const n=Ne(e);if(!n)return!1;if("Polygon"===t.type&&"Point"===e.type)return Oe(n.lng,n.lat,t.coordinates[0]);if("Polygon"===e.type&&"Point"===t.type){const r=t.coordinates;return Oe(r[0],r[1],e.coordinates[0])}if("Point"===e.type&&"Point"===t.type){return $e(n.lat,n.lng,r.lat,r.lng)<.001}return!1}function Oe(e,t,r){let n=!1;for(let i=0,o=r.length-1;i<r.length;o=i++){const s=r[i][0],a=r[i][1],c=r[o][0],u=r[o][1];a>t!=u>t&&e<(c-s)*(t-a)/(u-a)+s&&(n=!n)}return n}function Te(e,t){var r=Object.keys(t)[0],n=t[r];if("$"!=r.charAt(0))return De(e,r,n);if("$and"==r)return Me(e,n);if("$or"==r)return function(e,t){for(var r=0;r<t.length;r++)if(Te(e,t[r]))return!0;return!1}(e,n);if("$not"==r)return function(e,t){return!Te(e,t)}(e,n);if("$nor"==r)return function(e,t){for(var r=0;r<t.length;r++)if(Te(e,t[r]))return!1;return!0}(e,n);if("$where"==r)return function(e,t){if("function"==typeof t)try{return t.call(e)}catch(r){return!1}else if("string"==typeof t)try{return new Function("return "+t).call(e)}catch(r){return!1}return!1}(e,n);if("$comment"==r)return!0;if("$jsonSchema"==r)return _e(e,n);if("$text"==r){return function(e,t){return!(!e||"object"!=typeof e)&&function e(r){if("string"==typeof r)return Ae(r,t);if("object"!=typeof r||null===r)return!1;if(L(r)){for(let t=0;t<r.length;t++)if(e(r[t]))return!0;return!1}for(const t in r)if(r.hasOwnProperty(t)&&e(r[t]))return!0;return!1}(e)}(e,n.$search||n)}if("$expr"!=r)throw{$err:"Can't canonicalize query: BadValue unknown top level operator: "+r,code:17287};try{return ce(n,e)}catch(i){return!1}}function De(e,t,r){var n=function(e,t){for(var r=t.split("."),n=[e],i=0;i<r.length;i++){for(var o=r[i],s=parseInt(o,10),a=[],c=0;c<n.length;c++){var u=n[c];if(null!=u&&null!=u)if(L(u)&&!isNaN(s)&&s>=0)s<u.length&&a.push(u[s]);else if(L(u))for(var l=0;l<u.length;l++)null!=u[l]&&null!=u[l]&&"object"==typeof u[l]&&a.push(u[l][o]);else"object"==typeof u&&a.push(u[o])}n=a}if(0!==(n=n.filter(function(e){return void 0!==e})).length)return 1===n.length?n[0]:n}(e,t);if("string"==typeof r)return we(n,function(e){return be(e,r)});if("number"==typeof r)return we(n,function(e){return be(e,r)});if("boolean"==typeof r)return we(n,function(e){return be(e,r)});if(r instanceof T)return we(n,function(e){return be(e,r)});if("object"==typeof r){if(r instanceof RegExp)return null!=n&&we(n,function(e){return e&&e.match(r)});if(L(r))return null!=n&&we(n,function(e){return e&&R(e,r)});var i=Object.keys(r);if("$"==i[0].charAt(0)){for(var o=0;o<i.length;o++){var s=Object.keys(r)[o],a=r[s];if("$eq"==s){if(!we(n,function(e){return be(e,a)}))return!1}else if("$gt"==s){if(!we(n,function(e){return ve(e,a,">")}))return!1}else if("$gte"==s){if(!we(n,function(e){return ve(e,a,">=")}))return!1}else if("$lt"==s){if(!we(n,function(e){return ve(e,a,"<")}))return!1}else if("$lte"==s){if(!we(n,function(e){return ve(e,a,"<=")}))return!1}else if("$ne"==s){if(!we(n,function(e){return!be(e,a)}))return!1}else if("$in"==s){if(!we(n,function(e){return P(e,a)}))return!1}else if("$nin"==s){if(we(n,function(e){return P(e,a)}))return!1}else if("$exists"==s){var c=M(e,t);if(a?null==c:null!=c)return!1}else if("$type"==s){if(void 0===n){if(6!==("number"==typeof a?a:fe[a]))return!1}else if(!he(n,a))return!1}else if("$mod"==s){if(2!=a.length)throw{$err:"Can't canonicalize query: BadValue malformed mod, not enough elements",code:17287};if(!we(n,function(e){return null!=e&&e%a[0]==a[1]}))return!1}else if("$regex"==s){var u=a,l=r.$options||"",f="string"==typeof u?new RegExp(u,l):u;if(!we(n,function(e){return null!=e&&f.test(e)}))return!1}else{if("$options"==s)continue;if("$text"==s){if(!we(n,function(e){return null!=e&&Ae(e,a)}))return!1}else if("$expr"==s)try{if(!ce(a,e))return!1}catch(C){return!1}else if("$geoWithin"==s){if(!we(n,function(e){return null!=e&&Ee(e,a)}))return!1}else if("$near"==s||"$nearSphere"==s){let e;if(a.$geometry?e=a.$geometry.coordinates:a.coordinates?e=a.coordinates:Array.isArray(a)&&(e=a),!(e&&e.length>=2))return!1;{const[t,r]=e,i=a.$maxDistance||1e6;if(!we(n,function(e){return null!=e&&Ie(e,t,r,i)}))return!1}}else if("$geoIntersects"==s){const e=a.$geometry||a;if(!we(n,function(t){return null!=t&&Se(t,e)}))return!1}else if("$not"==s){if(De(e,t,a))return!1}else if("$all"==s){if(null==(d=M(e,t))||!L(d))return!1;for(var h=0;h<a.length;h++)if(!P(a[h],d))return!1}else if("$elemMatch"==s){var d;if(null==(d=M(e,t))||!L(d))return!1;var p=!1;for(h=0;h<d.length;h++){var g=d[h];if("object"!=typeof g||L(g)){for(var m=!0,y=Object.keys(a),_=0;_<y.length;_++){var b=y[_],v=a[b];("$gte"!=b||g>=v)&&("$gt"!=b||g>v)&&("$lte"!=b||g<=v)&&("$lt"!=b||g<v)?"$eq"==b&&g!=v||"$ne"==b&&g==v?m=!1:"$in"!=b||P(g,v)?"$nin"==b&&P(g,v)&&(m=!1):m=!1:m=!1}if(m){p=!0;break}}else if(Le(g,a)){p=!0;break}}if(!p)return!1}else if("$size"==s){var w=M(e,t);if(null==w||!L(w))return!1;if(w.length!=a)return!1}else if("$bitsAllSet"==s){if(!we(n,function(e){return pe(e,a)}))return!1}else if("$bitsAllClear"==s){if(!we(n,function(e){return ge(e,a)}))return!1}else if("$bitsAnySet"==s){if(!we(n,function(e){return me(e,a)}))return!1}else{if("$bitsAnyClear"!=s)throw{$err:"Can't canonicalize query: BadValue unknown operator: "+s,code:17287};if(!we(n,function(e){return ye(e,a)}))return!1}}}return!0}return M(e,t)&&U(M(e,t),r)}}function Me(e,t){for(var r=0;r<t.length;r++)if(!Te(e,t[r]))return!1;return!0}function Le(e,t){return Me(e,function(e){var t=[];for(var r in e)if(e.hasOwnProperty(r)){var n={};n[r]=e[r],t.push(n)}return t}(t))}class Pe extends r.EventEmitter{constructor(e,t=[],r={}){super(),this.target=e,this.pipeline=t,this.options=r,this.closed=!1,this._listeners=/* @__PURE__ */new Map,this._changeCounter=0,this._startWatching()}_isDB(e){return e&&"string"==typeof e.dbName&&"function"==typeof e.getCollectionNames&&e.collections instanceof Map}_isServer(e){return e&&e.databases instanceof Map&&"function"==typeof e._getDB}_isMongoClient(e){return e&&"function"==typeof e.connect&&"function"==typeof e.db&&"MongoClient"===e.constructor.name}_startWatching(){if(this.closed)return;const e=this._getCollectionsToWatch();for(const t of e)this._watchCollection(t);this._isServer(this.target)&&this._interceptServerDBCreation(),this._isDB(this.target)&&this._interceptDBCollectionCreation(),this._isMongoClient(this.target)&&this._interceptClientDBCreation()}_getCollectionsToWatch(){const e=[];if(this._isServer(this.target)){for(const[t,r]of this.target.databases){const t=r.getCollectionNames();for(const n of t){const t=r[n];t&&t.isCollection&&e.push(t)}}return e}if(this._isMongoClient(this.target))return this._monitorClient(),e;if(this._isDB(this.target)){const t=this.target.getCollectionNames();for(const r of t){const t=this.target[r];t&&t.isCollection&&e.push(t)}this._monitorDB()}return this.target.isCollection&&e.push(this.target),e}_watchCollection(e){if(this.closed)return;if(!e)return;if("function"!=typeof e.on)return;if(!e.isCollection)return;if(this._listeners.has(e))return;const t={insert:t=>this._emitChange("insert",e,t),update:(t,r)=>this._emitChange("update",e,t,r),replace:t=>this._emitChange("replace",e,t),delete:t=>this._emitChange("delete",e,t)};this._listeners.set(e,t),e.on("insert",t.insert),e.on("update",t.update),e.on("replace",t.replace),e.on("delete",t.delete)}_emitChange(e,t,r,n=null){if(this.closed)return;const i=this._createChangeEvent(e,t,r,n);this._matchesPipeline(i)&&this.emit("change",i)}_createChangeEvent(e,t,r,n){const i={_id:{_data:btoa(String(++this._changeCounter))},operationType:e,clusterTime:/* @__PURE__ */new Date,ns:{db:t.db.dbName,coll:t.name},documentKey:{_id:r._id}};switch(e){case"insert":case"replace":i.fullDocument=r;break;case"update":i.updateDescription=n||{updatedFields:{},removedFields:[],truncatedArrays:[]},"updateLookup"===this.options.fullDocument&&(i.fullDocument=r)}return i}_matchesPipeline(e){if(!this.pipeline||0===this.pipeline.length)return!0;for(const t of this.pipeline)if(t.$match&&!Le(e,t.$match))return!1;return!0}_getNestedValue(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}_monitorClient(){}_interceptClientDBCreation(){const e=this.target,t=e.db.bind(e),r=this;this._watchedDBs=/* @__PURE__ */new Map,e.db=function(e,n){const i=t(e,n),o=i.dbName;if(!r._watchedDBs.has(o)){r._watchedDBs.set(o,i);const e=i.getCollectionNames();for(const t of e){const e=i[t];e&&e.isCollection&&!r._listeners.has(e)&&r._watchCollection(e)}r._interceptDBCollectionCreationForClient(i)}return i},this._originalClientMethods={db:t}}_interceptServerDBCreation(){const e=this.target,t=e._getDB.bind(e),r=this;this._watchedDBs=/* @__PURE__ */new Map,e._getDB=function(e){const n=t(e);if(!r._watchedDBs.has(e)){r._watchedDBs.set(e,n);const t=n.getCollectionNames();for(const e of t){const t=n[e];t&&t.isCollection&&!r._listeners.has(t)&&r._watchCollection(t)}r._interceptDBCollectionCreationForServer(n)}return n},this._originalServerMethods={_getDB:t}}_interceptDBCollectionCreationForServer(e){const t=e.collection.bind(e),r=e.createCollection.bind(e),n=this;e.collection=function(e){const r=t(e);return r&&r.isCollection&&!n._listeners.has(r)&&n._watchCollection(r),r},e.createCollection=function(t){r(t);const i=e[t];i&&i.isCollection&&!n._listeners.has(i)&&n._watchCollection(i)}}_interceptDBCollectionCreationForClient(e){const t=e.collection.bind(e),r=e.createCollection.bind(e),n=this;e.collection=function(e){const r=t(e);return r&&r.isCollection&&!n._listeners.has(r)&&n._watchCollection(r),r},e.createCollection=function(t){r(t);const i=e[t];i&&i.isCollection&&!n._listeners.has(i)&&n._watchCollection(i)}}_monitorDB(){}_interceptDBCollectionCreation(){const e=this.target,t=e.getCollection.bind(e),r=e.createCollection?e.createCollection.bind(e):null,n=this;e.getCollection=function(e){const r=t(e);return r&&r.isCollection&&!n._listeners.has(r)&&n._watchCollection(r),r},r&&(e.createCollection=function(t){r(t);const i=e[t];i&&i.isCollection&&!n._listeners.has(i)&&n._watchCollection(i)}),this._originalDBMethods={getCollection:t,createCollection:r}}close(){if(!this.closed){this.closed=!0;for(const[e,t]of this._listeners)e.off("insert",t.insert),e.off("update",t.update),e.off("replace",t.replace),e.off("delete",t.delete);this._listeners.clear(),this._originalServerMethods&&"Server"===this.target.constructor.name&&(this.target._getDB=this._originalServerMethods._getDB),this._originalDBMethods&&"DB"===this.target.constructor.name&&(this.target.collection=this._originalDBMethods.collection,this.target.createCollection=this._originalDBMethods.createCollection),this._originalClientMethods&&"MongoClient"===this.target.constructor.name&&(this.target.db=this._originalClientMethods.db),this.emit("close"),this.removeAllListeners()}}get isClosed(){return this.closed}async*[Symbol.asyncIterator](){const e=[];let t=null,r=!1;const n=r=>{t?(t({value:r,done:!1}),t=null):e.push(r)},i=()=>{r=!0,t&&(t({done:!0}),t=null)},o=e=>{t&&(t(Promise.reject(e)),t=null)};this.on("change",n),this.on("close",i),this.on("error",o);try{for(;!r;)if(e.length>0)yield e.shift();else{const e=await new Promise(e=>{t=e,r&&e({done:!0})});if(e.done)break;yield e.value}}finally{this.off("change",n),this.off("close",i),this.off("error",o)}}async next(){return new Promise((e,t)=>{const r=t=>{o(),e(t)},n=()=>{o(),e(null)},i=e=>{o(),t(e)},o=()=>{this.off("change",r),this.off("close",n),this.off("error",i)};this.closed?e(null):(this.once("change",r),this.once("close",n),this.once("error",i))})}}const Re=new class{constructor(e=!1){this.enabled=e,this.timings=[],this.nestedLevel=0}setEnabled(e){this.enabled=e}start(e,t,r={}){return this.enabled?{category:e,operation:t,details:r,startTime:performance.now(),nestedLevel:this.nestedLevel++}:null}end(e,t={}){if(!this.enabled||!e)return;this.nestedLevel>0&&this.nestedLevel--;const r=performance.now()-e.startTime;this.timings.push({category:e.category,operation:e.operation,duration:r,details:{...e.details,...t},nestedLevel:e.nestedLevel,timestamp:e.startTime})}getTimings(){return this.timings}getTimingsByCategory(){const e={};for(const t of this.timings)e[t.category]||(e[t.category]=[]),e[t.category].push(t);return e}getSummary(){const e={};for(const t of this.timings){const r=`${t.category}.${t.operation}`;e[r]||(e[r]={category:t.category,operation:t.operation,count:0,total:0,min:1/0,max:-1/0,avg:0});const n=e[r];n.count++,n.total+=t.duration,n.min=Math.min(n.min,t.duration),n.max=Math.max(n.max,t.duration),n.avg=n.total/n.count}return Object.values(e)}clear(){this.timings=[],this.nestedLevel=0}formatTimings(){const e=this.getSummary();if(0===e.length)return"No timing data collected";let t="\n"+"=".repeat(80)+"\n";t+="PERFORMANCE TIMING REPORT\n",t+="=".repeat(80)+"\n\n";const r={};for(const n of e)r[n.category]||(r[n.category]=[]),r[n.category].push(n);for(const[n,i]of Object.entries(r)){t+=`${n.toUpperCase()}\n`,t+="-".repeat(80)+"\n",t+="Operation".padEnd(30)+"Count".padStart(8)+"Total(ms)".padStart(12)+"Avg(ms)".padStart(12)+"Min(ms)".padStart(12)+"Max(ms)".padStart(12)+"\n",t+="-".repeat(80)+"\n";for(const e of i)t+=e.operation.padEnd(30)+e.count.toString().padStart(8)+e.total.toFixed(3).padStart(12)+e.avg.toFixed(3).padStart(12)+e.min.toFixed(3).padStart(12)+e.max.toFixed(3).padStart(12)+"\n";t+="\n"}return t+="=".repeat(80)+"\n",t}}(!1);function Ue(e){if(null==e)return e;if("function"==typeof e)return{__function:e.toString()};if(e&&"object"==typeof e&&"function"==typeof e.toString)try{const t=e.toString();if(t&&24===t.length&&/^[0-9a-f]{24}$/i.test(t)&&e.constructor&&"ObjectId"===e.constructor.name)return{__objectId:t}}catch(t){}if(e instanceof T)return{__objectId:e.toString()};if(e instanceof Date)return{__date:e.toISOString()};if(Array.isArray(e))return e.map(Ue);if("object"==typeof e){const t={};for(const[r,n]of Object.entries(e))t[r]=Ue(n);return t}return e}function je(e){if(null==e)return e;if("object"==typeof e&&e.__function)return"string"==typeof e.__function?`(${e.__function}).call(this)`:void 0;if("object"==typeof e&&e.__objectId)return new T(e.__objectId);if("object"==typeof e&&e.__date)return new Date(e.__date);if(Array.isArray(e))return e.map(je);if("object"==typeof e){const t={};for(const[r,n]of Object.entries(e))t[r]=je(n);return t}return e}class ke extends r.EventEmitter{constructor(e){super(),this.worker=e,this._nextId=1,this._pending=/* @__PURE__ */new Map,this._terminating=!1,this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this),this._attach()}static async create(e={}){if("undefined"!=typeof window&&void 0!==globalThis.Worker)return new Fe(e);const{Worker:t}=await import("worker_threads"),{fileURLToPath:r}=await import("url");let n=e.workerPath;if(!n){n=r(new URL("../../dist/babymongo-server-worker.js",import.meta.url))}const i=new t(n,{workerData:e.workerData});return new Be(i)}sendRequest(e,t={}){const r=Re.start("ipc","serialize"),n=this._nextId++,i=Ue(e);Re.end(r);const o={type:"request",id:n,payload:i};return new Promise((e,r)=>{let i;t.timeout&&(i=setTimeout(()=>{this._pending.delete(n),r(new Error(`Worker request timed out after ${t.timeout}ms`))},t.timeout));const s=Re.start("ipc","roundtrip",{requestId:n}),a=e,c=r;e=e=>{Re.end(s),a(e)},r=e=>{Re.end(s),c(e)},this._pending.set(n,{resolve:e,reject:r,timeoutHandle:i}),this._post(o)})}async terminate(){this._terminating=!0;for(const[e,t]of this._pending.entries())clearTimeout(t.timeoutHandle);this._pending.clear(),await this._terminateImpl()}_handleMessage(e){const t=e?.data??e;if(t){if("response"===t.type){const e=this._pending.get(t.id);if(!e)return;if(this._pending.delete(t.id),clearTimeout(e.timeoutHandle),t.success){const r=Re.start("ipc","deserialize"),n=je(t.result);Re.end(r),e.resolve(n)}else{const r=new Error(t.error?.message||"Worker error");t.error?.name&&(r.name=t.error.name),t.error?.stack&&(r.stack=t.error.stack),t.error?.code&&(r.code=t.error.code),t.error?.$err&&(r.$err=t.error.$err),e.reject(r)}return}if("event"===t.type){const e=je(t.payload);this.emit("event",t.event,e)}}}_handleError(e){if(!this._terminating){for(const[t,r]of this._pending.entries())clearTimeout(r.timeoutHandle),r.reject(e);this._pending.clear(),this.emit("error",e)}}_attach(){throw new Error("Not implemented")}_post(){throw new Error("Not implemented")}_terminateImpl(){throw new Error("Not implemented")}}class Fe extends ke{constructor(e={}){const t=globalThis.Worker;if(!t)throw new Error("Worker API is not available in this environment");super(new t(e.workerUrl||"/dist/babymongo-server-worker.js",{type:"module"}))}_attach(){this.worker.onmessage=this._handleMessage,this.worker.onerror=this._handleError}_post(e){this.worker.postMessage(e)}_terminateImpl(){this.worker.terminate()}}class Be extends ke{constructor(e){super(e)}_attach(){this.worker.on("message",this._handleMessage),this.worker.on("error",this._handleError),this.worker.on("exit",e=>{0===e||this._terminating||this._handleError(new Error(`Worker stopped with exit code ${e}`))})}_post(e){this.worker.postMessage(e)}_terminateImpl(){return this.worker.terminate()}}export{A as BadValueError,E as BulkWriteError,d as CannotCreateIndexError,Pe as ChangeStream,b as CursorError,v as CursorNotFoundError,c as DuplicateKeyError,n as ErrorCodes,l as IndexError,f as IndexExistsError,h as IndexNotFoundError,_ as InvalidNamespaceError,O as MongoClient,s as MongoDriverError,i as MongoError,x as MongoNetworkError,o as MongoServerError,m as NamespaceError,y as NamespaceNotFoundError,w as NotImplementedError,T as ObjectId,C as OperationNotSupportedError,p as QueryError,g as TypeMismatchError,u as ValidationError,ke as WorkerBridge,a as WriteError};
2
+ //# sourceMappingURL=babymongo-node.min.js.map